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, BasicBlock, True};
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 interfaces::{Backend, CommonWriteMethods};
50 use jobserver::{Client, Acquired};
53 use std::marker::PhantomData;
56 use std::ffi::{CString, CStr};
58 use std::io::{self, Write};
60 use std::path::{Path, PathBuf};
63 use std::sync::mpsc::{channel, Sender, Receiver};
65 use std::time::Instant;
67 use libc::{c_uint, c_void, c_char, size_t};
69 pub const RELOC_MODEL_ARGS : [(&str, llvm::RelocMode); 7] = [
70 ("pic", llvm::RelocMode::PIC),
71 ("static", llvm::RelocMode::Static),
72 ("default", llvm::RelocMode::Default),
73 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
74 ("ropi", llvm::RelocMode::ROPI),
75 ("rwpi", llvm::RelocMode::RWPI),
76 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
79 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
80 ("small", llvm::CodeModel::Small),
81 ("kernel", llvm::CodeModel::Kernel),
82 ("medium", llvm::CodeModel::Medium),
83 ("large", llvm::CodeModel::Large),
86 pub const TLS_MODEL_ARGS : [(&str, llvm::ThreadLocalMode); 4] = [
87 ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
88 ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
89 ("initial-exec", llvm::ThreadLocalMode::InitialExec),
90 ("local-exec", llvm::ThreadLocalMode::LocalExec),
93 const PRE_THIN_LTO_BC_EXT: &str = "pre-thin-lto.bc";
95 pub fn llvm_err(handler: &errors::Handler, msg: &str) -> FatalError {
96 match llvm::last_error() {
97 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
98 None => handler.fatal(&msg),
102 pub fn write_output_file(
103 handler: &errors::Handler,
104 target: &'ll llvm::TargetMachine,
105 pm: &llvm::PassManager<'ll>,
106 m: &'ll llvm::Module,
108 file_type: llvm::FileType) -> Result<(), FatalError> {
110 let output_c = path2cstr(output);
111 let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type);
112 if result.into_result().is_err() {
113 let msg = format!("could not write output to {}", output.display());
114 Err(llvm_err(handler, &msg))
121 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
123 config::OptLevel::No => llvm::CodeGenOptLevel::None,
124 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
125 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
126 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
127 _ => llvm::CodeGenOptLevel::Default,
131 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
133 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
134 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
135 _ => llvm::CodeGenOptSizeNone,
139 pub fn create_target_machine(
142 ) -> &'static mut llvm::TargetMachine {
143 target_machine_factory(sess, find_features)().unwrap_or_else(|err| {
144 llvm_err(sess.diagnostic(), &err).raise()
148 // If find_features is true this won't access `sess.crate_types` by assuming
149 // that `is_pie_binary` is false. When we discover LLVM target features
150 // `sess.crate_types` is uninitialized so we cannot access it.
151 pub fn target_machine_factory(sess: &Session, find_features: bool)
152 -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
154 let reloc_model = get_reloc_model(sess);
156 let opt_level = get_llvm_opt_level(sess.opts.optimize);
157 let use_softfp = sess.opts.cg.soft_float;
159 let ffunction_sections = sess.target.target.options.function_sections;
160 let fdata_sections = ffunction_sections;
162 let code_model_arg = sess.opts.cg.code_model.as_ref().or(
163 sess.target.target.options.code_model.as_ref(),
166 let code_model = match code_model_arg {
168 match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
171 sess.err(&format!("{:?} is not a valid code model",
173 sess.abort_if_errors();
178 None => llvm::CodeModel::None,
181 let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
182 let mut singlethread = sess.target.target.options.singlethread;
184 // On the wasm target once the `atomics` feature is enabled that means that
185 // we're no longer single-threaded, or otherwise we don't want LLVM to
186 // lower atomic operations to single-threaded operations.
188 sess.target.target.llvm_target.contains("wasm32") &&
189 features.iter().any(|s| *s == "+atomics")
191 singlethread = false;
194 let triple = SmallCStr::new(&sess.target.target.llvm_target);
195 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
196 let features = features.join(",");
197 let features = CString::new(features).unwrap();
198 let is_pie_binary = !find_features && is_pie_binary(sess);
199 let trap_unreachable = sess.target.target.options.trap_unreachable;
200 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
202 let asm_comments = sess.asm_comments();
206 llvm::LLVMRustCreateTargetMachine(
207 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
218 emit_stack_size_section,
223 format!("Could not create LLVM TargetMachine for triple: {}",
224 triple.to_str().unwrap())
229 /// Module-specific configuration for `optimize_and_codegen`.
230 pub struct ModuleConfig {
231 /// Names of additional optimization passes to run.
233 /// Some(level) to optimize at a certain level, or None to run
234 /// absolutely no optimizations (used for the metadata module).
235 pub opt_level: Option<llvm::CodeGenOptLevel>,
237 /// Some(level) to optimize binary size, or None to not affect program size.
238 opt_size: Option<llvm::CodeGenOptSize>,
240 pgo_gen: Option<String>,
243 // Flags indicating which outputs to produce.
244 pub emit_pre_thin_lto_bc: bool,
245 emit_no_opt_bc: bool,
247 emit_bc_compressed: bool,
252 // Miscellaneous flags. These are mostly copied from command-line
254 pub verify_llvm_ir: bool,
255 no_prepopulate_passes: bool,
258 vectorize_loop: bool,
260 merge_functions: bool,
261 inline_threshold: Option<usize>,
262 // Instead of creating an object file by doing LLVM codegen, just
263 // make the object file bitcode. Provides easy compatibility with
264 // emscripten's ecc compiler, when used as the linker.
265 obj_is_bitcode: bool,
266 no_integrated_as: bool,
268 embed_bitcode_marker: bool,
272 fn new(passes: Vec<String>) -> ModuleConfig {
279 pgo_use: String::new(),
281 emit_no_opt_bc: false,
282 emit_pre_thin_lto_bc: false,
284 emit_bc_compressed: false,
289 obj_is_bitcode: false,
290 embed_bitcode: false,
291 embed_bitcode_marker: false,
292 no_integrated_as: false,
294 verify_llvm_ir: false,
295 no_prepopulate_passes: false,
298 vectorize_loop: false,
299 vectorize_slp: false,
300 merge_functions: false,
301 inline_threshold: None
305 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
306 self.verify_llvm_ir = sess.verify_llvm_ir();
307 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
308 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
309 self.time_passes = sess.time_passes();
310 self.inline_threshold = sess.opts.cg.inline_threshold;
311 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
312 sess.opts.debugging_opts.cross_lang_lto.enabled();
313 let embed_bitcode = sess.target.target.options.embed_bitcode ||
314 sess.opts.debugging_opts.embed_bitcode;
316 match sess.opts.optimize {
317 config::OptLevel::No |
318 config::OptLevel::Less => {
319 self.embed_bitcode_marker = embed_bitcode;
321 _ => self.embed_bitcode = embed_bitcode,
325 // Copy what clang does by turning on loop vectorization at O2 and
326 // slp vectorization at O3. Otherwise configure other optimization aspects
327 // of this pass manager builder.
328 // Turn off vectorization for emscripten, as it's not very well supported.
329 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
330 (sess.opts.optimize == config::OptLevel::Default ||
331 sess.opts.optimize == config::OptLevel::Aggressive) &&
332 !sess.target.target.options.is_like_emscripten;
334 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
335 sess.opts.optimize == config::OptLevel::Aggressive &&
336 !sess.target.target.options.is_like_emscripten;
338 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
339 sess.opts.optimize == config::OptLevel::Aggressive;
342 pub fn bitcode_needed(&self) -> bool {
343 self.emit_bc || self.obj_is_bitcode
344 || self.emit_bc_compressed || self.embed_bitcode
348 /// Assembler name and command used by codegen when no_integrated_as is enabled
349 struct AssemblerCommand {
354 /// Additional resources used by optimize_and_codegen (not module specific)
356 pub struct CodegenContext<'ll> {
357 // Resources needed when running LTO
358 pub time_passes: bool,
360 pub no_landing_pads: bool,
361 pub save_temps: bool,
362 pub fewer_names: bool,
363 pub exported_symbols: Option<Arc<ExportedSymbols>>,
364 pub opts: Arc<config::Options>,
365 pub crate_types: Vec<config::CrateType>,
366 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
367 output_filenames: Arc<OutputFilenames>,
368 regular_module_config: Arc<ModuleConfig>,
369 metadata_module_config: Arc<ModuleConfig>,
370 allocator_module_config: Arc<ModuleConfig>,
371 pub tm_factory: Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>,
372 pub msvc_imps_needed: bool,
373 pub target_pointer_width: String,
374 debuginfo: config::DebugInfo,
376 // Number of cgus excluding the allocator/metadata modules
377 pub total_cgus: usize,
378 // Handler to use for diagnostics produced during codegen.
379 pub diag_emitter: SharedEmitter,
380 // LLVM passes added by plugins.
381 pub plugin_passes: Vec<String>,
382 // LLVM optimizations for which we want to print remarks.
384 // Worker thread number
386 // The incremental compilation session directory, or None if we are not
387 // compiling incrementally
388 pub incr_comp_session_dir: Option<PathBuf>,
389 // Used to update CGU re-use information during the thinlto phase.
390 pub cgu_reuse_tracker: CguReuseTracker,
391 // Channel back to the main control thread to send messages to
392 coordinator_send: Sender<Box<dyn Any + Send>>,
393 // A reference to the TimeGraph so we can register timings. None means that
394 // measuring is disabled.
395 time_graph: Option<TimeGraph>,
396 // The assembler command if no_integrated_as option is enabled, None otherwise
397 assembler_cmd: Option<Arc<AssemblerCommand>>,
398 // This field is used to give a lifetime parameter to the struct so that it can implement
399 // the Backend trait.
400 phantom: PhantomData<&'ll ()>
403 impl CodegenContext<'ll> {
404 pub fn create_diag_handler(&self) -> Handler {
405 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
408 pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
410 ModuleKind::Regular => &self.regular_module_config,
411 ModuleKind::Metadata => &self.metadata_module_config,
412 ModuleKind::Allocator => &self.allocator_module_config,
416 pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
417 if !self.save_temps {
421 let ext = format!("{}.bc", name);
422 let cgu = Some(&module.name[..]);
423 let path = self.output_filenames.temp_path_ext(&ext, cgu);
424 let cstr = path2cstr(&path);
425 let llmod = module.module_llvm.llmod();
426 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
431 impl<'ll> Backend for CodegenContext<'ll> {
432 type Value = &'ll Value;
433 type BasicBlock = &'ll BasicBlock;
434 type Type = &'ll Type;
435 type Context = &'ll llvm::Context;
438 impl CommonWriteMethods for CodegenContext<'ll> {
439 fn val_ty(&self, v: &'ll Value) -> &'ll Type {
445 fn c_bytes_in_context(&self, llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
447 let ptr = bytes.as_ptr() as *const c_char;
448 return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
452 fn c_struct_in_context(
454 llcx: &'a llvm::Context,
459 llvm::LLVMConstStructInContext(llcx,
460 elts.as_ptr(), elts.len() as c_uint,
461 packed as llvm::Bool)
467 pub struct DiagnosticHandlers<'a> {
468 data: *mut (&'a CodegenContext<'a>, &'a Handler),
469 llcx: &'a llvm::Context,
472 impl<'a> DiagnosticHandlers<'a> {
473 pub fn new(cgcx: &'a CodegenContext<'a>,
474 handler: &'a Handler,
475 llcx: &'a llvm::Context) -> Self {
476 let data = Box::into_raw(Box::new((cgcx, handler)));
478 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
479 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
481 DiagnosticHandlers { data, llcx }
485 impl<'a> Drop for DiagnosticHandlers<'a> {
487 use std::ptr::null_mut;
489 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
490 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
491 drop(Box::from_raw(self.data));
496 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
499 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned());
502 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
508 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
510 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
511 .expect("non-UTF8 SMDiagnostic");
513 report_inline_asm(cgcx, &msg, cookie);
516 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
520 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
522 match llvm::diagnostic::Diagnostic::unpack(info) {
523 llvm::diagnostic::InlineAsm(inline) => {
524 report_inline_asm(cgcx,
525 &llvm::twine_to_string(inline.message),
529 llvm::diagnostic::Optimization(opt) => {
530 let enabled = match cgcx.remark {
532 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
536 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
545 llvm::diagnostic::PGO(diagnostic_ref) |
546 llvm::diagnostic::Linker(diagnostic_ref) => {
547 let msg = llvm::build_string(|s| {
548 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
549 }).expect("non-UTF8 diagnostic");
550 diag_handler.warn(&msg);
552 llvm::diagnostic::UnknownDiagnostic(..) => {},
556 // Unsafe due to LLVM calls.
557 unsafe fn optimize(cgcx: &CodegenContext,
558 diag_handler: &Handler,
559 module: &ModuleCodegen,
560 config: &ModuleConfig,
561 timeline: &mut Timeline)
562 -> Result<(), FatalError>
564 let llmod = module.module_llvm.llmod();
565 let llcx = &*module.module_llvm.llcx;
566 let tm = &*module.module_llvm.tm;
567 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
569 let module_name = module.name.clone();
570 let module_name = Some(&module_name[..]);
572 if config.emit_no_opt_bc {
573 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
574 let out = path2cstr(&out);
575 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
578 if config.opt_level.is_some() {
579 // Create the two optimizing pass managers. These mirror what clang
580 // does, and are by populated by LLVM's default PassManagerBuilder.
581 // Each manager has a different set of passes, but they also share
582 // some common passes.
583 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
584 let mpm = llvm::LLVMCreatePassManager();
587 // If we're verifying or linting, add them to the function pass
589 let addpass = |pass_name: &str| {
590 let pass_name = SmallCStr::new(pass_name);
591 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
593 None => return false,
595 let pass_manager = match llvm::LLVMRustPassKind(pass) {
596 llvm::PassKind::Function => &*fpm,
597 llvm::PassKind::Module => &*mpm,
598 llvm::PassKind::Other => {
599 diag_handler.err("Encountered LLVM pass kind we can't handle");
603 llvm::LLVMRustAddPass(pass_manager, pass);
607 if config.verify_llvm_ir { assert!(addpass("verify")); }
609 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
610 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
611 // we'll get errors in LLVM.
612 let using_thin_buffers = config.bitcode_needed();
613 let mut have_name_anon_globals_pass = false;
614 if !config.no_prepopulate_passes {
615 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
616 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
617 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
618 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
619 (cgcx.lto != Lto::Fat && cgcx.opts.debugging_opts.cross_lang_lto.enabled());
620 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
621 if using_thin_buffers && !prepare_for_thin_lto {
622 assert!(addpass("name-anon-globals"));
623 have_name_anon_globals_pass = true;
625 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
626 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
627 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
631 for pass in &config.passes {
633 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass));
635 if pass == "name-anon-globals" {
636 have_name_anon_globals_pass = true;
640 for pass in &cgcx.plugin_passes {
642 diag_handler.err(&format!("a plugin asked for LLVM pass \
643 `{}` but LLVM does not \
644 recognize it", pass));
646 if pass == "name-anon-globals" {
647 have_name_anon_globals_pass = true;
651 if using_thin_buffers && !have_name_anon_globals_pass {
652 // As described above, this will probably cause an error in LLVM
653 if config.no_prepopulate_passes {
654 diag_handler.err("The current compilation is going to use thin LTO buffers \
655 without running LLVM's NameAnonGlobals pass. \
656 This will likely cause errors in LLVM. Consider adding \
657 -C passes=name-anon-globals to the compiler command line.");
659 bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
660 This will likely cause errors in LLVM and should never happen.");
665 diag_handler.abort_if_errors();
667 // Finally, run the actual optimization passes
668 time_ext(config.time_passes,
670 &format!("llvm function passes [{}]", module_name.unwrap()),
672 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
674 timeline.record("fpm");
675 time_ext(config.time_passes,
677 &format!("llvm module passes [{}]", module_name.unwrap()),
679 llvm::LLVMRunPassManager(mpm, llmod)
682 // Deallocate managers that we're now done with
683 llvm::LLVMDisposePassManager(fpm);
684 llvm::LLVMDisposePassManager(mpm);
689 fn generate_lto_work(cgcx: &CodegenContext,
690 modules: Vec<ModuleCodegen>,
691 import_only_modules: Vec<(SerializedModule, WorkProduct)>)
692 -> Vec<(WorkItem, u64)>
694 let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
695 tg.start(CODEGEN_WORKER_TIMELINE,
696 CODEGEN_WORK_PACKAGE_KIND,
698 }).unwrap_or(Timeline::noop());
699 let (lto_modules, copy_jobs) = lto::run(cgcx, modules, import_only_modules, &mut timeline)
700 .unwrap_or_else(|e| e.raise());
702 let lto_modules = lto_modules.into_iter().map(|module| {
703 let cost = module.cost();
704 (WorkItem::LTO(module), cost)
707 let copy_jobs = copy_jobs.into_iter().map(|wp| {
708 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
709 name: wp.cgu_name.clone(),
714 lto_modules.chain(copy_jobs).collect()
717 unsafe fn codegen(cgcx: &CodegenContext,
718 diag_handler: &Handler,
719 module: ModuleCodegen,
720 config: &ModuleConfig,
721 timeline: &mut Timeline)
722 -> Result<CompiledModule, FatalError>
724 timeline.record("codegen");
726 let llmod = module.module_llvm.llmod();
727 let llcx = &*module.module_llvm.llcx;
728 let tm = &*module.module_llvm.tm;
729 let module_name = module.name.clone();
730 let module_name = Some(&module_name[..]);
731 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
733 if cgcx.msvc_imps_needed {
734 create_msvc_imps(cgcx, llcx, llmod);
737 // A codegen-specific pass manager is used to generate object
738 // files for an LLVM module.
740 // Apparently each of these pass managers is a one-shot kind of
741 // thing, so we create a new one for each type of output. The
742 // pass manager passed to the closure should be ensured to not
743 // escape the closure itself, and the manager should only be
745 unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
746 llmod: &'ll llvm::Module,
749 where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
751 let cpm = llvm::LLVMCreatePassManager();
752 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
753 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
757 // If we don't have the integrated assembler, then we need to emit asm
758 // from LLVM and use `gcc` to create the object file.
759 let asm_to_obj = config.emit_obj && config.no_integrated_as;
761 // Change what we write and cleanup based on whether obj files are
762 // just llvm bitcode. In that case write bitcode, and possibly
763 // delete the bitcode if it wasn't requested. Don't generate the
764 // machine code, instead copy the .o file from the .bc
765 let write_bc = config.emit_bc || config.obj_is_bitcode;
766 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
767 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
768 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
770 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
771 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
774 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
775 let thin = ThinBuffer::new(llmod);
776 let data = thin.data();
777 timeline.record("make-bc");
780 if let Err(e) = fs::write(&bc_out, data) {
781 diag_handler.err(&format!("failed to write bytecode: {}", e));
783 timeline.record("write-bc");
786 if config.embed_bitcode {
787 embed_bitcode(cgcx, llcx, llmod, Some(data));
788 timeline.record("embed-bc");
791 if config.emit_bc_compressed {
792 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
793 let data = bytecode::encode(&module.name, data);
794 if let Err(e) = fs::write(&dst, data) {
795 diag_handler.err(&format!("failed to write bytecode: {}", e));
797 timeline.record("compress-bc");
799 } else if config.embed_bitcode_marker {
800 embed_bitcode(cgcx, llcx, llmod, None);
803 time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
804 || -> Result<(), FatalError> {
806 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
807 let out = path2cstr(&out);
809 extern "C" fn demangle_callback(input_ptr: *const c_char,
811 output_ptr: *mut c_char,
812 output_len: size_t) -> size_t {
814 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
817 let input = match str::from_utf8(input) {
822 let output = unsafe {
823 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
825 let mut cursor = io::Cursor::new(output);
827 let demangled = match rustc_demangle::try_demangle(input) {
832 if let Err(_) = write!(cursor, "{:#}", demangled) {
833 // Possible only if provided buffer is not big enough
837 cursor.position() as size_t
840 with_codegen(tm, llmod, config.no_builtins, |cpm| {
841 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
842 llvm::LLVMDisposePassManager(cpm);
844 timeline.record("ir");
847 if config.emit_asm || asm_to_obj {
848 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
850 // We can't use the same module for asm and binary output, because that triggers
851 // various errors like invalid IR or broken binaries, so we might have to clone the
852 // module to produce the asm output
853 let llmod = if config.emit_obj {
854 llvm::LLVMCloneModule(llmod)
858 with_codegen(tm, llmod, config.no_builtins, |cpm| {
859 write_output_file(diag_handler, tm, cpm, llmod, &path,
860 llvm::FileType::AssemblyFile)
862 timeline.record("asm");
866 with_codegen(tm, llmod, config.no_builtins, |cpm| {
867 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
868 llvm::FileType::ObjectFile)
870 timeline.record("obj");
871 } else if asm_to_obj {
872 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
873 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
874 timeline.record("asm_to_obj");
876 if !config.emit_asm && !cgcx.save_temps {
877 drop(fs::remove_file(&assembly));
885 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
886 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
887 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
892 debug!("removing_bitcode {:?}", bc_out);
893 if let Err(e) = fs::remove_file(&bc_out) {
894 diag_handler.err(&format!("failed to remove bitcode: {}", e));
900 Ok(module.into_compiled_module(config.emit_obj,
902 config.emit_bc_compressed,
903 &cgcx.output_filenames))
906 /// Embed the bitcode of an LLVM module in the LLVM module itself.
908 /// This is done primarily for iOS where it appears to be standard to compile C
909 /// code at least with `-fembed-bitcode` which creates two sections in the
912 /// * __LLVM,__bitcode
913 /// * __LLVM,__cmdline
915 /// It appears *both* of these sections are necessary to get the linker to
916 /// recognize what's going on. For us though we just always throw in an empty
919 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
920 /// embed an empty section.
922 /// Basically all of this is us attempting to follow in the footsteps of clang
923 /// on iOS. See #35968 for lots more info.
924 unsafe fn embed_bitcode(cgcx: &CodegenContext,
925 llcx: &llvm::Context,
926 llmod: &llvm::Module,
927 bitcode: Option<&[u8]>) {
928 let llconst = cgcx.c_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
929 let llglobal = llvm::LLVMAddGlobal(
931 cgcx.val_ty(llconst),
932 "rustc.embedded.module\0".as_ptr() as *const _,
934 llvm::LLVMSetInitializer(llglobal, llconst);
936 let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
937 cgcx.opts.target_triple.triple().contains("-darwin");
939 let section = if is_apple {
944 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
945 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
946 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
948 let llconst = cgcx.c_bytes_in_context(llcx, &[]);
949 let llglobal = llvm::LLVMAddGlobal(
951 cgcx.val_ty(llconst),
952 "rustc.embedded.cmdline\0".as_ptr() as *const _,
954 llvm::LLVMSetInitializer(llglobal, llconst);
955 let section = if is_apple {
960 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
961 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
964 pub(crate) struct CompiledModules {
965 pub modules: Vec<CompiledModule>,
966 pub metadata_module: CompiledModule,
967 pub allocator_module: Option<CompiledModule>,
970 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
971 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
972 sess.opts.output_types.contains_key(&OutputType::Exe)
975 fn need_pre_thin_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
976 if sess.opts.incremental.is_none() {
984 Lto::ThinLocal => true,
988 pub fn start_async_codegen(tcx: TyCtxt,
989 time_graph: Option<TimeGraph>,
990 metadata: EncodedMetadata,
991 coordinator_receive: Receiver<Box<dyn Any + Send>>,
995 let crate_name = tcx.crate_name(LOCAL_CRATE);
996 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
997 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
998 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
999 "windows_subsystem");
1000 let windows_subsystem = subsystem.map(|subsystem| {
1001 if subsystem != "windows" && subsystem != "console" {
1002 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
1003 `windows` and `console` are allowed",
1006 subsystem.to_string()
1009 let linker_info = LinkerInfo::new(tcx);
1010 let crate_info = CrateInfo::new(tcx);
1012 // Figure out what we actually need to build.
1013 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
1014 let mut metadata_config = ModuleConfig::new(vec![]);
1015 let mut allocator_config = ModuleConfig::new(vec![]);
1017 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
1019 Sanitizer::Address => {
1020 modules_config.passes.push("asan".to_owned());
1021 modules_config.passes.push("asan-module".to_owned());
1023 Sanitizer::Memory => {
1024 modules_config.passes.push("msan".to_owned())
1026 Sanitizer::Thread => {
1027 modules_config.passes.push("tsan".to_owned())
1033 if sess.opts.debugging_opts.profile {
1034 modules_config.passes.push("insert-gcov-profiling".to_owned())
1037 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
1038 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
1040 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
1041 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
1043 // Save all versions of the bytecode if we're saving our temporaries.
1044 if sess.opts.cg.save_temps {
1045 modules_config.emit_no_opt_bc = true;
1046 modules_config.emit_pre_thin_lto_bc = true;
1047 modules_config.emit_bc = true;
1048 modules_config.emit_lto_bc = true;
1049 metadata_config.emit_bc = true;
1050 allocator_config.emit_bc = true;
1053 // Emit compressed bitcode files for the crate if we're emitting an rlib.
1054 // Whenever an rlib is created, the bitcode is inserted into the archive in
1055 // order to allow LTO against it.
1056 if need_crate_bitcode_for_rlib(sess) {
1057 modules_config.emit_bc_compressed = true;
1058 allocator_config.emit_bc_compressed = true;
1061 modules_config.emit_pre_thin_lto_bc =
1062 need_pre_thin_lto_bitcode_for_incr_comp(sess);
1064 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1065 tcx.sess.target.target.options.no_integrated_as;
1067 for output_type in sess.opts.output_types.keys() {
1068 match *output_type {
1069 OutputType::Bitcode => { modules_config.emit_bc = true; }
1070 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
1071 OutputType::Assembly => {
1072 modules_config.emit_asm = true;
1073 // If we're not using the LLVM assembler, this function
1074 // could be invoked specially with output_type_assembly, so
1075 // in this case we still want the metadata object file.
1076 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
1077 metadata_config.emit_obj = true;
1078 allocator_config.emit_obj = true;
1081 OutputType::Object => { modules_config.emit_obj = true; }
1082 OutputType::Metadata => { metadata_config.emit_obj = true; }
1083 OutputType::Exe => {
1084 modules_config.emit_obj = true;
1085 metadata_config.emit_obj = true;
1086 allocator_config.emit_obj = true;
1088 OutputType::Mir => {}
1089 OutputType::DepInfo => {}
1093 modules_config.set_flags(sess, no_builtins);
1094 metadata_config.set_flags(sess, no_builtins);
1095 allocator_config.set_flags(sess, no_builtins);
1097 // Exclude metadata and allocator modules from time_passes output, since
1098 // they throw off the "LLVM passes" measurement.
1099 metadata_config.time_passes = false;
1100 allocator_config.time_passes = false;
1102 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
1103 let (codegen_worker_send, codegen_worker_receive) = channel();
1105 let coordinator_thread = start_executing_work(tcx,
1108 codegen_worker_send,
1109 coordinator_receive,
1111 sess.jobserver.clone(),
1113 Arc::new(modules_config),
1114 Arc::new(metadata_config),
1115 Arc::new(allocator_config));
1126 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1127 codegen_worker_receive,
1128 shared_emitter_main,
1129 future: coordinator_thread,
1130 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1134 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1136 compiled_modules: &CompiledModules,
1137 ) -> FxHashMap<WorkProductId, WorkProduct> {
1138 let mut work_products = FxHashMap::default();
1140 if sess.opts.incremental.is_none() {
1141 return work_products;
1144 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
1145 let mut files = vec![];
1147 if let Some(ref path) = module.object {
1148 files.push((WorkProductFileKind::Object, path.clone()));
1150 if let Some(ref path) = module.bytecode {
1151 files.push((WorkProductFileKind::Bytecode, path.clone()));
1153 if let Some(ref path) = module.bytecode_compressed {
1154 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1157 if let Some((id, product)) =
1158 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files)
1160 work_products.insert(id, product);
1167 fn produce_final_output_artifacts(sess: &Session,
1168 compiled_modules: &CompiledModules,
1169 crate_output: &OutputFilenames) {
1170 let mut user_wants_bitcode = false;
1171 let mut user_wants_objects = false;
1173 // Produce final compile outputs.
1174 let copy_gracefully = |from: &Path, to: &Path| {
1175 if let Err(e) = fs::copy(from, to) {
1176 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1180 let copy_if_one_unit = |output_type: OutputType,
1181 keep_numbered: bool| {
1182 if compiled_modules.modules.len() == 1 {
1183 // 1) Only one codegen unit. In this case it's no difficulty
1184 // to copy `foo.0.x` to `foo.x`.
1185 let module_name = Some(&compiled_modules.modules[0].name[..]);
1186 let path = crate_output.temp_path(output_type, module_name);
1187 copy_gracefully(&path,
1188 &crate_output.path(output_type));
1189 if !sess.opts.cg.save_temps && !keep_numbered {
1190 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1191 remove(sess, &path);
1194 let ext = crate_output.temp_path(output_type, None)
1201 if crate_output.outputs.contains_key(&output_type) {
1202 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
1203 // no good solution for this case, so warn the user.
1204 sess.warn(&format!("ignoring emit path because multiple .{} files \
1205 were produced", ext));
1206 } else if crate_output.single_output_file.is_some() {
1207 // 3) Multiple codegen units, with `-o some_name`. We have
1208 // no good solution for this case, so warn the user.
1209 sess.warn(&format!("ignoring -o because multiple .{} files \
1210 were produced", ext));
1212 // 4) Multiple codegen units, but no explicit name. We
1213 // just leave the `foo.0.x` files in place.
1214 // (We don't have to do any work in this case.)
1219 // Flag to indicate whether the user explicitly requested bitcode.
1220 // Otherwise, we produced it only as a temporary output, and will need
1221 // to get rid of it.
1222 for output_type in crate_output.outputs.keys() {
1223 match *output_type {
1224 OutputType::Bitcode => {
1225 user_wants_bitcode = true;
1226 // Copy to .bc, but always keep the .0.bc. There is a later
1227 // check to figure out if we should delete .0.bc files, or keep
1228 // them for making an rlib.
1229 copy_if_one_unit(OutputType::Bitcode, true);
1231 OutputType::LlvmAssembly => {
1232 copy_if_one_unit(OutputType::LlvmAssembly, false);
1234 OutputType::Assembly => {
1235 copy_if_one_unit(OutputType::Assembly, false);
1237 OutputType::Object => {
1238 user_wants_objects = true;
1239 copy_if_one_unit(OutputType::Object, true);
1242 OutputType::Metadata |
1244 OutputType::DepInfo => {}
1248 // Clean up unwanted temporary files.
1250 // We create the following files by default:
1251 // - #crate#.#module-name#.bc
1252 // - #crate#.#module-name#.o
1253 // - #crate#.crate.metadata.bc
1254 // - #crate#.crate.metadata.o
1255 // - #crate#.o (linked from crate.##.o)
1256 // - #crate#.bc (copied from crate.##.bc)
1257 // We may create additional files if requested by the user (through
1258 // `-C save-temps` or `--emit=` flags).
1260 if !sess.opts.cg.save_temps {
1261 // Remove the temporary .#module-name#.o objects. If the user didn't
1262 // explicitly request bitcode (with --emit=bc), and the bitcode is not
1263 // needed for building an rlib, then we must remove .#module-name#.bc as
1266 // Specific rules for keeping .#module-name#.bc:
1267 // - If the user requested bitcode (`user_wants_bitcode`), and
1268 // codegen_units > 1, then keep it.
1269 // - If the user requested bitcode but codegen_units == 1, then we
1270 // can toss .#module-name#.bc because we copied it to .bc earlier.
1271 // - If we're not building an rlib and the user didn't request
1272 // bitcode, then delete .#module-name#.bc.
1273 // If you change how this works, also update back::link::link_rlib,
1274 // where .#module-name#.bc files are (maybe) deleted after making an
1276 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1278 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1280 let keep_numbered_objects = needs_crate_object ||
1281 (user_wants_objects && sess.codegen_units() > 1);
1283 for module in compiled_modules.modules.iter() {
1284 if let Some(ref path) = module.object {
1285 if !keep_numbered_objects {
1290 if let Some(ref path) = module.bytecode {
1291 if !keep_numbered_bitcode {
1297 if !user_wants_bitcode {
1298 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1299 remove(sess, &path);
1302 if let Some(ref allocator_module) = compiled_modules.allocator_module {
1303 if let Some(ref path) = allocator_module.bytecode {
1310 // We leave the following files around by default:
1312 // - #crate#.crate.metadata.o
1314 // These are used in linking steps and will be cleaned up afterward.
1317 pub(crate) fn dump_incremental_data(_codegen_results: &CodegenResults) {
1318 // FIXME(mw): This does not work at the moment because the situation has
1319 // become more complicated due to incremental LTO. Now a CGU
1320 // can have more than two caching states.
1321 // println!("[incremental] Re-using {} out of {} modules",
1322 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
1323 // codegen_results.modules.len());
1327 /// Optimize a newly codegened, totally unoptimized module.
1328 Optimize(ModuleCodegen),
1329 /// Copy the post-LTO artifacts from the incremental cache to the output
1331 CopyPostLtoArtifacts(CachedModuleCodegen),
1332 /// Perform (Thin)LTO on the given module.
1333 LTO(lto::LtoModuleCodegen),
1337 fn module_kind(&self) -> ModuleKind {
1339 WorkItem::Optimize(ref m) => m.kind,
1340 WorkItem::CopyPostLtoArtifacts(_) |
1341 WorkItem::LTO(_) => ModuleKind::Regular,
1345 fn name(&self) -> String {
1347 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1348 WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
1349 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1354 enum WorkItemResult {
1355 Compiled(CompiledModule),
1356 NeedsLTO(ModuleCodegen),
1359 fn execute_work_item(cgcx: &CodegenContext,
1360 work_item: WorkItem,
1361 timeline: &mut Timeline)
1362 -> Result<WorkItemResult, FatalError>
1364 let module_config = cgcx.config(work_item.module_kind());
1367 WorkItem::Optimize(module) => {
1368 execute_optimize_work_item(cgcx, module, module_config, timeline)
1370 WorkItem::CopyPostLtoArtifacts(module) => {
1371 execute_copy_from_cache_work_item(cgcx, module, module_config, timeline)
1373 WorkItem::LTO(module) => {
1374 execute_lto_work_item(cgcx, module, module_config, timeline)
1379 fn execute_optimize_work_item(cgcx: &CodegenContext,
1380 module: ModuleCodegen,
1381 module_config: &ModuleConfig,
1382 timeline: &mut Timeline)
1383 -> Result<WorkItemResult, FatalError>
1385 let diag_handler = cgcx.create_diag_handler();
1388 optimize(cgcx, &diag_handler, &module, module_config, timeline)?;
1391 let linker_does_lto = cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1393 // After we've done the initial round of optimizations we need to
1394 // decide whether to synchronously codegen this module or ship it
1395 // back to the coordinator thread for further LTO processing (which
1396 // has to wait for all the initial modules to be optimized).
1398 // Here we dispatch based on the `cgcx.lto` and kind of module we're
1400 let needs_lto = match cgcx.lto {
1403 // If the linker does LTO, we don't have to do it. Note that we
1404 // keep doing full LTO, if it is requested, as not to break the
1405 // assumption that the output will be a single module.
1406 Lto::Thin | Lto::ThinLocal if linker_does_lto => false,
1408 // Here we've got a full crate graph LTO requested. We ignore
1409 // this, however, if the crate type is only an rlib as there's
1410 // no full crate graph to process, that'll happen later.
1412 // This use case currently comes up primarily for targets that
1413 // require LTO so the request for LTO is always unconditionally
1414 // passed down to the backend, but we don't actually want to do
1415 // anything about it yet until we've got a final product.
1416 Lto::Fat | Lto::Thin => {
1417 cgcx.crate_types.len() != 1 ||
1418 cgcx.crate_types[0] != config::CrateType::Rlib
1421 // When we're automatically doing ThinLTO for multi-codegen-unit
1422 // builds we don't actually want to LTO the allocator modules if
1423 // it shows up. This is due to various linker shenanigans that
1424 // we'll encounter later.
1426 module.kind != ModuleKind::Allocator
1430 // Metadata modules never participate in LTO regardless of the lto
1432 let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1435 Ok(WorkItemResult::NeedsLTO(module))
1437 let module = unsafe {
1438 codegen(cgcx, &diag_handler, module, module_config, timeline)?
1440 Ok(WorkItemResult::Compiled(module))
1444 fn execute_copy_from_cache_work_item(cgcx: &CodegenContext,
1445 module: CachedModuleCodegen,
1446 module_config: &ModuleConfig,
1448 -> Result<WorkItemResult, FatalError>
1450 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1453 let mut object = None;
1454 let mut bytecode = None;
1455 let mut bytecode_compressed = None;
1456 for (kind, saved_file) in &module.source.saved_files {
1457 let obj_out = match kind {
1458 WorkProductFileKind::Object => {
1459 let path = cgcx.output_filenames.temp_path(OutputType::Object,
1460 Some(&module.name));
1461 object = Some(path.clone());
1464 WorkProductFileKind::Bytecode => {
1465 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1466 Some(&module.name));
1467 bytecode = Some(path.clone());
1470 WorkProductFileKind::BytecodeCompressed => {
1471 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1473 .with_extension(RLIB_BYTECODE_EXTENSION);
1474 bytecode_compressed = Some(path.clone());
1478 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1480 debug!("copying pre-existing module `{}` from {:?} to {}",
1484 if let Err(err) = link_or_copy(&source_file, &obj_out) {
1485 let diag_handler = cgcx.create_diag_handler();
1486 diag_handler.err(&format!("unable to copy {} to {}: {}",
1487 source_file.display(),
1493 assert_eq!(object.is_some(), module_config.emit_obj);
1494 assert_eq!(bytecode.is_some(), module_config.emit_bc);
1495 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
1497 Ok(WorkItemResult::Compiled(CompiledModule {
1499 kind: ModuleKind::Regular,
1502 bytecode_compressed,
1506 fn execute_lto_work_item(cgcx: &CodegenContext,
1507 mut module: lto::LtoModuleCodegen,
1508 module_config: &ModuleConfig,
1509 timeline: &mut Timeline)
1510 -> Result<WorkItemResult, FatalError>
1512 let diag_handler = cgcx.create_diag_handler();
1515 let module = module.optimize(cgcx, timeline)?;
1516 let module = codegen(cgcx, &diag_handler, module, module_config, timeline)?;
1517 Ok(WorkItemResult::Compiled(module))
1522 Token(io::Result<Acquired>),
1524 result: ModuleCodegen,
1528 result: Result<CompiledModule, ()>,
1532 llvm_work_item: WorkItem,
1535 AddImportOnlyModule {
1536 module_data: SerializedModule,
1537 work_product: WorkProduct,
1546 code: Option<DiagnosticId>,
1550 #[derive(PartialEq, Clone, Copy, Debug)]
1551 enum MainThreadWorkerState {
1557 fn start_executing_work(tcx: TyCtxt,
1558 crate_info: &CrateInfo,
1559 shared_emitter: SharedEmitter,
1560 codegen_worker_send: Sender<Message>,
1561 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1564 time_graph: Option<TimeGraph>,
1565 modules_config: Arc<ModuleConfig>,
1566 metadata_config: Arc<ModuleConfig>,
1567 allocator_config: Arc<ModuleConfig>)
1568 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1569 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1570 let sess = tcx.sess;
1572 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1573 let exported_symbols = {
1574 let mut exported_symbols = FxHashMap::default();
1576 let copy_symbols = |cnum| {
1577 let symbols = tcx.exported_symbols(cnum)
1579 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1587 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1588 Some(Arc::new(exported_symbols))
1590 Lto::Fat | Lto::Thin => {
1591 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1592 for &cnum in tcx.crates().iter() {
1593 exported_symbols.insert(cnum, copy_symbols(cnum));
1595 Some(Arc::new(exported_symbols))
1600 // First up, convert our jobserver into a helper thread so we can use normal
1601 // mpsc channels to manage our messages and such.
1602 // After we've requested tokens then we'll, when we can,
1603 // get tokens on `coordinator_receive` which will
1604 // get managed in the main loop below.
1605 let coordinator_send2 = coordinator_send.clone();
1606 let helper = jobserver.into_helper_thread(move |token| {
1607 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1608 }).expect("failed to spawn helper thread");
1610 let mut each_linked_rlib_for_lto = Vec::new();
1611 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1612 if link::ignored_for_lto(sess, crate_info, cnum) {
1615 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1618 let assembler_cmd = if modules_config.no_integrated_as {
1619 // HACK: currently we use linker (gcc) as our assembler
1620 let (linker, flavor) = link::linker_and_flavor(sess);
1622 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1623 cmd.args(&sess.target.target.options.asm_args);
1625 Some(Arc::new(AssemblerCommand { name, cmd }))
1630 let cgcx = CodegenContext {
1631 crate_types: sess.crate_types.borrow().clone(),
1632 each_linked_rlib_for_lto,
1634 no_landing_pads: sess.no_landing_pads(),
1635 fewer_names: sess.fewer_names(),
1636 save_temps: sess.opts.cg.save_temps,
1637 opts: Arc::new(sess.opts.clone()),
1638 time_passes: sess.time_passes(),
1640 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1641 remark: sess.opts.cg.remark.clone(),
1643 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1644 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1646 diag_emitter: shared_emitter.clone(),
1648 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1649 regular_module_config: modules_config,
1650 metadata_module_config: metadata_config,
1651 allocator_module_config: allocator_config,
1652 tm_factory: target_machine_factory(tcx.sess, false),
1654 msvc_imps_needed: msvc_imps_needed(tcx),
1655 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1656 debuginfo: tcx.sess.opts.debuginfo,
1658 phantom: PhantomData
1661 // This is the "main loop" of parallel work happening for parallel codegen.
1662 // It's here that we manage parallelism, schedule work, and work with
1663 // messages coming from clients.
1665 // There are a few environmental pre-conditions that shape how the system
1668 // - Error reporting only can happen on the main thread because that's the
1669 // only place where we have access to the compiler `Session`.
1670 // - LLVM work can be done on any thread.
1671 // - Codegen can only happen on the main thread.
1672 // - Each thread doing substantial work most be in possession of a `Token`
1673 // from the `Jobserver`.
1674 // - The compiler process always holds one `Token`. Any additional `Tokens`
1675 // have to be requested from the `Jobserver`.
1679 // The error reporting restriction is handled separately from the rest: We
1680 // set up a `SharedEmitter` the holds an open channel to the main thread.
1681 // When an error occurs on any thread, the shared emitter will send the
1682 // error message to the receiver main thread (`SharedEmitterMain`). The
1683 // main thread will periodically query this error message queue and emit
1684 // any error messages it has received. It might even abort compilation if
1685 // has received a fatal error. In this case we rely on all other threads
1686 // being torn down automatically with the main thread.
1687 // Since the main thread will often be busy doing codegen work, error
1688 // reporting will be somewhat delayed, since the message queue can only be
1689 // checked in between to work packages.
1691 // Work Processing Infrastructure
1692 // ==============================
1693 // The work processing infrastructure knows three major actors:
1695 // - the coordinator thread,
1696 // - the main thread, and
1697 // - LLVM worker threads
1699 // The coordinator thread is running a message loop. It instructs the main
1700 // thread about what work to do when, and it will spawn off LLVM worker
1701 // threads as open LLVM WorkItems become available.
1703 // The job of the main thread is to codegen CGUs into LLVM work package
1704 // (since the main thread is the only thread that can do this). The main
1705 // thread will block until it receives a message from the coordinator, upon
1706 // which it will codegen one CGU, send it to the coordinator and block
1707 // again. This way the coordinator can control what the main thread is
1710 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1711 // available, it will spawn off a new LLVM worker thread and let it process
1712 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1713 // it will just shut down, which also frees all resources associated with
1714 // the given LLVM module, and sends a message to the coordinator that the
1715 // has been completed.
1719 // The scheduler's goal is to minimize the time it takes to complete all
1720 // work there is, however, we also want to keep memory consumption low
1721 // if possible. These two goals are at odds with each other: If memory
1722 // consumption were not an issue, we could just let the main thread produce
1723 // LLVM WorkItems at full speed, assuring maximal utilization of
1724 // Tokens/LLVM worker threads. However, since codegen usual is faster
1725 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1726 // WorkItem potentially holds on to a substantial amount of memory.
1728 // So the actual goal is to always produce just enough LLVM WorkItems as
1729 // not to starve our LLVM worker threads. That means, once we have enough
1730 // WorkItems in our queue, we can block the main thread, so it does not
1731 // produce more until we need them.
1733 // Doing LLVM Work on the Main Thread
1734 // ----------------------------------
1735 // Since the main thread owns the compiler processes implicit `Token`, it is
1736 // wasteful to keep it blocked without doing any work. Therefore, what we do
1737 // in this case is: We spawn off an additional LLVM worker thread that helps
1738 // reduce the queue. The work it is doing corresponds to the implicit
1739 // `Token`. The coordinator will mark the main thread as being busy with
1740 // LLVM work. (The actual work happens on another OS thread but we just care
1741 // about `Tokens`, not actual threads).
1743 // When any LLVM worker thread finishes while the main thread is marked as
1744 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1745 // of the just finished thread to the LLVM worker thread that is working on
1746 // behalf of the main thread's implicit Token, thus freeing up the main
1747 // thread again. The coordinator can then again decide what the main thread
1748 // should do. This allows the coordinator to make decisions at more points
1751 // Striking a Balance between Throughput and Memory Consumption
1752 // ------------------------------------------------------------
1753 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1754 // memory consumption as low as possible, are in conflict with each other,
1755 // we have to find a trade off between them. Right now, the goal is to keep
1756 // all workers busy, which means that no worker should find the queue empty
1757 // when it is ready to start.
1758 // How do we do achieve this? Good question :) We actually never know how
1759 // many `Tokens` are potentially available so it's hard to say how much to
1760 // fill up the queue before switching the main thread to LLVM work. Also we
1761 // currently don't have a means to estimate how long a running LLVM worker
1762 // will still be busy with it's current WorkItem. However, we know the
1763 // maximal count of available Tokens that makes sense (=the number of CPU
1764 // cores), so we can take a conservative guess. The heuristic we use here
1765 // is implemented in the `queue_full_enough()` function.
1767 // Some Background on Jobservers
1768 // -----------------------------
1769 // It's worth also touching on the management of parallelism here. We don't
1770 // want to just spawn a thread per work item because while that's optimal
1771 // parallelism it may overload a system with too many threads or violate our
1772 // configuration for the maximum amount of cpu to use for this process. To
1773 // manage this we use the `jobserver` crate.
1775 // Job servers are an artifact of GNU make and are used to manage
1776 // parallelism between processes. A jobserver is a glorified IPC semaphore
1777 // basically. Whenever we want to run some work we acquire the semaphore,
1778 // and whenever we're done with that work we release the semaphore. In this
1779 // manner we can ensure that the maximum number of parallel workers is
1780 // capped at any one point in time.
1782 // LTO and the coordinator thread
1783 // ------------------------------
1785 // The final job the coordinator thread is responsible for is managing LTO
1786 // and how that works. When LTO is requested what we'll to is collect all
1787 // optimized LLVM modules into a local vector on the coordinator. Once all
1788 // modules have been codegened and optimized we hand this to the `lto`
1789 // module for further optimization. The `lto` module will return back a list
1790 // of more modules to work on, which the coordinator will continue to spawn
1793 // Each LLVM module is automatically sent back to the coordinator for LTO if
1794 // necessary. There's already optimizations in place to avoid sending work
1795 // back to the coordinator if LTO isn't requested.
1796 return thread::spawn(move || {
1797 // We pretend to be within the top-level LLVM time-passes task here:
1800 let max_workers = ::num_cpus::get();
1801 let mut worker_id_counter = 0;
1802 let mut free_worker_ids = Vec::new();
1803 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1804 if let Some(id) = free_worker_ids.pop() {
1807 let id = worker_id_counter;
1808 worker_id_counter += 1;
1813 // This is where we collect codegen units that have gone all the way
1814 // through codegen and LLVM.
1815 let mut compiled_modules = vec![];
1816 let mut compiled_metadata_module = None;
1817 let mut compiled_allocator_module = None;
1818 let mut needs_lto = Vec::new();
1819 let mut lto_import_only_modules = Vec::new();
1820 let mut started_lto = false;
1821 let mut codegen_aborted = false;
1823 // This flag tracks whether all items have gone through codegens
1824 let mut codegen_done = false;
1826 // This is the queue of LLVM work items that still need processing.
1827 let mut work_items = Vec::<(WorkItem, u64)>::new();
1829 // This are the Jobserver Tokens we currently hold. Does not include
1830 // the implicit Token the compiler process owns no matter what.
1831 let mut tokens = Vec::new();
1833 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1834 let mut running = 0;
1836 let mut llvm_start_time = None;
1838 // Run the message loop while there's still anything that needs message
1839 // processing. Note that as soon as codegen is aborted we simply want to
1840 // wait for all existing work to finish, so many of the conditions here
1841 // only apply if codegen hasn't been aborted as they represent pending
1843 while !codegen_done ||
1845 (!codegen_aborted && (
1846 work_items.len() > 0 ||
1847 needs_lto.len() > 0 ||
1848 lto_import_only_modules.len() > 0 ||
1849 main_thread_worker_state != MainThreadWorkerState::Idle
1853 // While there are still CGUs to be codegened, the coordinator has
1854 // to decide how to utilize the compiler processes implicit Token:
1855 // For codegenning more CGU or for running them through LLVM.
1857 if main_thread_worker_state == MainThreadWorkerState::Idle {
1858 if !queue_full_enough(work_items.len(), running, max_workers) {
1859 // The queue is not full enough, codegen more items:
1860 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1861 panic!("Could not send Message::CodegenItem to main thread")
1863 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1865 // The queue is full enough to not let the worker
1866 // threads starve. Use the implicit Token to do some
1868 let (item, _) = work_items.pop()
1869 .expect("queue empty - queue_full_enough() broken?");
1870 let cgcx = CodegenContext {
1871 worker: get_worker_id(&mut free_worker_ids),
1874 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1875 &mut llvm_start_time);
1876 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1877 spawn_work(cgcx, item);
1880 } else if codegen_aborted {
1881 // don't queue up any more work if codegen was aborted, we're
1882 // just waiting for our existing children to finish
1884 // If we've finished everything related to normal codegen
1885 // then it must be the case that we've got some LTO work to do.
1886 // Perform the serial work here of figuring out what we're
1887 // going to LTO and then push a bunch of work items onto our
1889 if work_items.len() == 0 &&
1891 main_thread_worker_state == MainThreadWorkerState::Idle {
1892 assert!(!started_lto);
1893 assert!(needs_lto.len() + lto_import_only_modules.len() > 0);
1895 let modules = mem::replace(&mut needs_lto, Vec::new());
1896 let import_only_modules =
1897 mem::replace(&mut lto_import_only_modules, Vec::new());
1898 for (work, cost) in generate_lto_work(&cgcx, modules, import_only_modules) {
1899 let insertion_index = work_items
1900 .binary_search_by_key(&cost, |&(_, cost)| cost)
1901 .unwrap_or_else(|e| e);
1902 work_items.insert(insertion_index, (work, cost));
1903 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1904 helper.request_token();
1909 // In this branch, we know that everything has been codegened,
1910 // so it's just a matter of determining whether the implicit
1911 // Token is free to use for LLVM work.
1912 match main_thread_worker_state {
1913 MainThreadWorkerState::Idle => {
1914 if let Some((item, _)) = work_items.pop() {
1915 let cgcx = CodegenContext {
1916 worker: get_worker_id(&mut free_worker_ids),
1919 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1920 &mut llvm_start_time);
1921 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1922 spawn_work(cgcx, item);
1924 // There is no unstarted work, so let the main thread
1925 // take over for a running worker. Otherwise the
1926 // implicit token would just go to waste.
1927 // We reduce the `running` counter by one. The
1928 // `tokens.truncate()` below will take care of
1929 // giving the Token back.
1930 debug_assert!(running > 0);
1932 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1935 MainThreadWorkerState::Codegenning => {
1936 bug!("codegen worker should not be codegenning after \
1937 codegen was already completed")
1939 MainThreadWorkerState::LLVMing => {
1940 // Already making good use of that token
1945 // Spin up what work we can, only doing this while we've got available
1946 // parallelism slots and work left to spawn.
1947 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1948 let (item, _) = work_items.pop().unwrap();
1950 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1951 &mut llvm_start_time);
1953 let cgcx = CodegenContext {
1954 worker: get_worker_id(&mut free_worker_ids),
1958 spawn_work(cgcx, item);
1962 // Relinquish accidentally acquired extra tokens
1963 tokens.truncate(running);
1965 let msg = coordinator_receive.recv().unwrap();
1966 match *msg.downcast::<Message>().ok().unwrap() {
1967 // Save the token locally and the next turn of the loop will use
1968 // this to spawn a new unit of work, or it may get dropped
1969 // immediately if we have no more work to spawn.
1970 Message::Token(token) => {
1975 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1976 // If the main thread token is used for LLVM work
1977 // at the moment, we turn that thread into a regular
1978 // LLVM worker thread, so the main thread is free
1979 // to react to codegen demand.
1980 main_thread_worker_state = MainThreadWorkerState::Idle;
1985 let msg = &format!("failed to acquire jobserver token: {}", e);
1986 shared_emitter.fatal(msg);
1987 // Exit the coordinator thread
1993 Message::CodegenDone { llvm_work_item, cost } => {
1994 // We keep the queue sorted by estimated processing cost,
1995 // so that more expensive items are processed earlier. This
1996 // is good for throughput as it gives the main thread more
1997 // time to fill up the queue and it avoids scheduling
1998 // expensive items to the end.
1999 // Note, however, that this is not ideal for memory
2000 // consumption, as LLVM module sizes are not evenly
2002 let insertion_index =
2003 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
2004 let insertion_index = match insertion_index {
2005 Ok(idx) | Err(idx) => idx
2007 work_items.insert(insertion_index, (llvm_work_item, cost));
2009 if !cgcx.opts.debugging_opts.no_parallel_llvm {
2010 helper.request_token();
2012 assert!(!codegen_aborted);
2013 assert_eq!(main_thread_worker_state,
2014 MainThreadWorkerState::Codegenning);
2015 main_thread_worker_state = MainThreadWorkerState::Idle;
2018 Message::CodegenComplete => {
2019 codegen_done = true;
2020 assert!(!codegen_aborted);
2021 assert_eq!(main_thread_worker_state,
2022 MainThreadWorkerState::Codegenning);
2023 main_thread_worker_state = MainThreadWorkerState::Idle;
2026 // If codegen is aborted that means translation was aborted due
2027 // to some normal-ish compiler error. In this situation we want
2028 // to exit as soon as possible, but we want to make sure all
2029 // existing work has finished. Flag codegen as being done, and
2030 // then conditions above will ensure no more work is spawned but
2031 // we'll keep executing this loop until `running` hits 0.
2032 Message::CodegenAborted => {
2033 assert!(!codegen_aborted);
2034 codegen_done = true;
2035 codegen_aborted = true;
2036 assert_eq!(main_thread_worker_state,
2037 MainThreadWorkerState::Codegenning);
2040 // If a thread exits successfully then we drop a token associated
2041 // with that worker and update our `running` count. We may later
2042 // re-acquire a token to continue running more work. We may also not
2043 // actually drop a token here if the worker was running with an
2044 // "ephemeral token"
2046 // Note that if the thread failed that means it panicked, so we
2047 // abort immediately.
2048 Message::Done { result: Ok(compiled_module), worker_id } => {
2049 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2050 main_thread_worker_state = MainThreadWorkerState::Idle;
2055 free_worker_ids.push(worker_id);
2057 match compiled_module.kind {
2058 ModuleKind::Regular => {
2059 compiled_modules.push(compiled_module);
2061 ModuleKind::Metadata => {
2062 assert!(compiled_metadata_module.is_none());
2063 compiled_metadata_module = Some(compiled_module);
2065 ModuleKind::Allocator => {
2066 assert!(compiled_allocator_module.is_none());
2067 compiled_allocator_module = Some(compiled_module);
2071 Message::NeedsLTO { result, worker_id } => {
2072 assert!(!started_lto);
2073 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2074 main_thread_worker_state = MainThreadWorkerState::Idle;
2078 free_worker_ids.push(worker_id);
2079 needs_lto.push(result);
2081 Message::AddImportOnlyModule { module_data, work_product } => {
2082 assert!(!started_lto);
2083 assert!(!codegen_done);
2084 assert_eq!(main_thread_worker_state,
2085 MainThreadWorkerState::Codegenning);
2086 lto_import_only_modules.push((module_data, work_product));
2087 main_thread_worker_state = MainThreadWorkerState::Idle;
2089 Message::Done { result: Err(()), worker_id: _ } => {
2090 bug!("worker thread panicked");
2092 Message::CodegenItem => {
2093 bug!("the coordinator should not receive codegen requests")
2098 if let Some(llvm_start_time) = llvm_start_time {
2099 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
2100 // This is the top-level timing for all of LLVM, set the time-depth
2103 print_time_passes_entry(cgcx.time_passes,
2108 // Regardless of what order these modules completed in, report them to
2109 // the backend in the same order every time to ensure that we're handing
2110 // out deterministic results.
2111 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
2113 let compiled_metadata_module = compiled_metadata_module
2114 .expect("Metadata module not compiled?");
2116 Ok(CompiledModules {
2117 modules: compiled_modules,
2118 metadata_module: compiled_metadata_module,
2119 allocator_module: compiled_allocator_module,
2123 // A heuristic that determines if we have enough LLVM WorkItems in the
2124 // queue so that the main thread can do LLVM work instead of codegen
2125 fn queue_full_enough(items_in_queue: usize,
2126 workers_running: usize,
2127 max_workers: usize) -> bool {
2129 items_in_queue > 0 &&
2130 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
2133 fn maybe_start_llvm_timer(config: &ModuleConfig,
2134 llvm_start_time: &mut Option<Instant>) {
2135 // We keep track of the -Ztime-passes output manually,
2136 // since the closure-based interface does not fit well here.
2137 if config.time_passes {
2138 if llvm_start_time.is_none() {
2139 *llvm_start_time = Some(Instant::now());
2145 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
2146 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
2147 time_graph::TimelineId(CODEGEN_WORKER_ID);
2148 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2149 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
2150 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2151 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
2153 fn spawn_work(cgcx: CodegenContext<'static>, work: WorkItem) {
2154 let depth = time_depth();
2156 thread::spawn(move || {
2157 set_time_depth(depth);
2159 // Set up a destructor which will fire off a message that we're done as
2162 coordinator_send: Sender<Box<dyn Any + Send>>,
2163 result: Option<WorkItemResult>,
2166 impl Drop for Bomb {
2167 fn drop(&mut self) {
2168 let worker_id = self.worker_id;
2169 let msg = match self.result.take() {
2170 Some(WorkItemResult::Compiled(m)) => {
2171 Message::Done { result: Ok(m), worker_id }
2173 Some(WorkItemResult::NeedsLTO(m)) => {
2174 Message::NeedsLTO { result: m, worker_id }
2176 None => Message::Done { result: Err(()), worker_id }
2178 drop(self.coordinator_send.send(Box::new(msg)));
2182 let mut bomb = Bomb {
2183 coordinator_send: cgcx.coordinator_send.clone(),
2185 worker_id: cgcx.worker,
2188 // Execute the work itself, and if it finishes successfully then flag
2189 // ourselves as a success as well.
2191 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2192 // as a diagnostic was already sent off to the main thread - just
2193 // surface that there was an error in this worker.
2195 let timeline = cgcx.time_graph.as_ref().map(|tg| {
2196 tg.start(time_graph::TimelineId(cgcx.worker),
2197 LLVM_WORK_PACKAGE_KIND,
2200 let mut timeline = timeline.unwrap_or(Timeline::noop());
2201 execute_work_item(&cgcx, work, &mut timeline).ok()
2206 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2207 let assembler = cgcx.assembler_cmd
2209 .expect("cgcx.assembler_cmd is missing?");
2211 let pname = &assembler.name;
2212 let mut cmd = assembler.cmd.clone();
2213 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2214 debug!("{:?}", cmd);
2216 match cmd.output() {
2218 if !prog.status.success() {
2219 let mut note = prog.stderr.clone();
2220 note.extend_from_slice(&prog.stdout);
2222 handler.struct_err(&format!("linking with `{}` failed: {}",
2225 .note(&format!("{:?}", &cmd))
2226 .note(str::from_utf8(¬e[..]).unwrap())
2228 handler.abort_if_errors();
2232 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2233 handler.abort_if_errors();
2238 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
2239 config: &ModuleConfig,
2240 opt_level: llvm::CodeGenOptLevel,
2241 prepare_for_thin_lto: bool,
2242 f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
2245 // Create the PassManagerBuilder for LLVM. We configure it with
2246 // reasonable defaults and prepare it to actually populate the pass
2248 let builder = llvm::LLVMPassManagerBuilderCreate();
2249 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2250 let inline_threshold = config.inline_threshold;
2252 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2253 let s = if s.is_empty() { "default_%m.profraw" } else { s };
2254 CString::new(s.as_bytes()).unwrap()
2257 let pgo_use_path = if config.pgo_use.is_empty() {
2260 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2263 llvm::LLVMRustConfigurePassManagerBuilder(
2266 config.merge_functions,
2267 config.vectorize_slp,
2268 config.vectorize_loop,
2269 prepare_for_thin_lto,
2270 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2271 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2274 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2276 if opt_size != llvm::CodeGenOptSizeNone {
2277 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2280 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2282 // Here we match what clang does (kinda). For O0 we only inline
2283 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2284 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2285 // thresholds copied from clang.
2286 match (opt_level, opt_size, inline_threshold) {
2288 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2290 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2291 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2293 (_, llvm::CodeGenOptSizeDefault, _) => {
2294 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2296 (_, llvm::CodeGenOptSizeAggressive, _) => {
2297 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2299 (llvm::CodeGenOptLevel::None, ..) => {
2300 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2302 (llvm::CodeGenOptLevel::Less, ..) => {
2303 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2305 (llvm::CodeGenOptLevel::Default, ..) => {
2306 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2308 (llvm::CodeGenOptLevel::Other, ..) => {
2309 bug!("CodeGenOptLevel::Other selected")
2314 llvm::LLVMPassManagerBuilderDispose(builder);
2318 enum SharedEmitterMessage {
2319 Diagnostic(Diagnostic),
2320 InlineAsmError(u32, String),
2326 pub struct SharedEmitter {
2327 sender: Sender<SharedEmitterMessage>,
2330 pub struct SharedEmitterMain {
2331 receiver: Receiver<SharedEmitterMessage>,
2334 impl SharedEmitter {
2335 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2336 let (sender, receiver) = channel();
2338 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2341 fn inline_asm_error(&self, cookie: u32, msg: String) {
2342 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2345 fn fatal(&self, msg: &str) {
2346 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2350 impl Emitter for SharedEmitter {
2351 fn emit(&mut self, db: &DiagnosticBuilder) {
2352 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2354 code: db.code.clone(),
2357 for child in &db.children {
2358 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2359 msg: child.message(),
2364 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2368 impl SharedEmitterMain {
2369 pub fn check(&self, sess: &Session, blocking: bool) {
2371 let message = if blocking {
2372 match self.receiver.recv() {
2373 Ok(message) => Ok(message),
2377 match self.receiver.try_recv() {
2378 Ok(message) => Ok(message),
2384 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2385 let handler = sess.diagnostic();
2388 handler.emit_with_code(&MultiSpan::new(),
2394 handler.emit(&MultiSpan::new(),
2400 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2401 match Mark::from_u32(cookie).expn_info() {
2402 Some(ei) => sess.span_err(ei.call_site, &msg),
2403 None => sess.err(&msg),
2406 Ok(SharedEmitterMessage::AbortIfErrors) => {
2407 sess.abort_if_errors();
2409 Ok(SharedEmitterMessage::Fatal(msg)) => {
2421 pub struct OngoingCodegen {
2424 metadata: EncodedMetadata,
2425 windows_subsystem: Option<String>,
2426 linker_info: LinkerInfo,
2427 crate_info: CrateInfo,
2428 time_graph: Option<TimeGraph>,
2429 coordinator_send: Sender<Box<dyn Any + Send>>,
2430 codegen_worker_receive: Receiver<Message>,
2431 shared_emitter_main: SharedEmitterMain,
2432 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2433 output_filenames: Arc<OutputFilenames>,
2436 impl OngoingCodegen {
2440 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2441 self.shared_emitter_main.check(sess, true);
2442 let compiled_modules = match self.future.join() {
2443 Ok(Ok(compiled_modules)) => compiled_modules,
2445 sess.abort_if_errors();
2446 panic!("expected abort due to worker thread errors")
2449 bug!("panic during codegen/LLVM phase");
2453 sess.cgu_reuse_tracker.check_expected_reuse(sess);
2455 sess.abort_if_errors();
2457 if let Some(time_graph) = self.time_graph {
2458 time_graph.dump(&format!("{}-timings", self.crate_name));
2462 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2464 produce_final_output_artifacts(sess,
2466 &self.output_filenames);
2468 // FIXME: time_llvm_passes support - does this use a global context or
2470 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2471 unsafe { llvm::LLVMRustPrintPassTimings(); }
2475 crate_name: self.crate_name,
2476 crate_hash: self.crate_hash,
2477 metadata: self.metadata,
2478 windows_subsystem: self.windows_subsystem,
2479 linker_info: self.linker_info,
2480 crate_info: self.crate_info,
2482 modules: compiled_modules.modules,
2483 allocator_module: compiled_modules.allocator_module,
2484 metadata_module: compiled_modules.metadata_module,
2488 pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2490 module: ModuleCodegen) {
2491 self.wait_for_signal_to_codegen_item();
2492 self.check_for_errors(tcx.sess);
2494 // These are generally cheap and won't through off scheduling.
2496 submit_codegened_module_to_llvm(tcx, module, cost);
2499 pub fn codegen_finished(&self, tcx: TyCtxt) {
2500 self.wait_for_signal_to_codegen_item();
2501 self.check_for_errors(tcx.sess);
2502 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2505 /// Consume this context indicating that codegen was entirely aborted, and
2506 /// we need to exit as quickly as possible.
2508 /// This method blocks the current thread until all worker threads have
2509 /// finished, and all worker threads should have exited or be real close to
2510 /// exiting at this point.
2511 pub fn codegen_aborted(self) {
2512 // Signal to the coordinator it should spawn no more work and start
2514 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted)));
2515 drop(self.future.join());
2518 pub fn check_for_errors(&self, sess: &Session) {
2519 self.shared_emitter_main.check(sess, false);
2522 pub fn wait_for_signal_to_codegen_item(&self) {
2523 match self.codegen_worker_receive.recv() {
2524 Ok(Message::CodegenItem) => {
2527 Ok(_) => panic!("unexpected message"),
2529 // One of the LLVM threads must have panicked, fall through so
2530 // error handling can be reached.
2536 // impl Drop for OngoingCodegen {
2537 // fn drop(&mut self) {
2541 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2542 module: ModuleCodegen,
2544 let llvm_work_item = WorkItem::Optimize(module);
2545 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2551 pub(crate) fn submit_post_lto_module_to_llvm(tcx: TyCtxt,
2552 module: CachedModuleCodegen) {
2553 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2554 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2560 pub(crate) fn submit_pre_lto_module_to_llvm(tcx: TyCtxt,
2561 module: CachedModuleCodegen) {
2562 let filename = pre_lto_bitcode_filename(&module.name);
2563 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2564 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
2565 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
2569 memmap::Mmap::map(&file).unwrap_or_else(|e| {
2570 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2574 // Schedule the module to be loaded
2575 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule {
2576 module_data: SerializedModule::FromUncompressedFile(mmap),
2577 work_product: module.source,
2581 pub(super) fn pre_lto_bitcode_filename(module_name: &str) -> String {
2582 format!("{}.{}", module_name, PRE_THIN_LTO_BC_EXT)
2585 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2586 // This should never be true (because it's not supported). If it is true,
2587 // something is wrong with commandline arg validation.
2588 assert!(!(tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
2589 tcx.sess.target.target.options.is_like_msvc &&
2590 tcx.sess.opts.cg.prefer_dynamic));
2592 tcx.sess.target.target.options.is_like_msvc &&
2593 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
2594 // ThinLTO can't handle this workaround in all cases, so we don't
2595 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2596 // dynamic linking when cross-language LTO is enabled.
2597 !tcx.sess.opts.debugging_opts.cross_lang_lto.enabled()
2600 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2601 // This is required to satisfy `dllimport` references to static data in .rlibs
2602 // when using MSVC linker. We do this only for data, as linker can fix up
2603 // code references on its own.
2604 // See #26591, #27438
2605 fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
2606 if !cgcx.msvc_imps_needed {
2609 // The x86 ABI seems to require that leading underscores are added to symbol
2610 // names, so we need an extra underscore on 32-bit. There's also a leading
2611 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2612 // underscores added in front).
2613 let prefix = if cgcx.target_pointer_width == "32" {
2619 let i8p_ty = Type::i8p_llcx(llcx);
2620 let globals = base::iter_globals(llmod)
2622 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2623 llvm::LLVMIsDeclaration(val) == 0
2626 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2627 let mut imp_name = prefix.as_bytes().to_vec();
2628 imp_name.extend(name.to_bytes());
2629 let imp_name = CString::new(imp_name).unwrap();
2632 .collect::<Vec<_>>();
2633 for (imp_name, val) in globals {
2634 let imp = llvm::LLVMAddGlobal(llmod,
2636 imp_name.as_ptr() as *const _);
2637 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2638 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);