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};
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};
51 use jobserver::{Client, Acquired};
54 use std::marker::PhantomData;
57 use std::ffi::{CString, CStr};
59 use std::io::{self, Write};
61 use std::path::{Path, PathBuf};
64 use std::sync::mpsc::{channel, Sender, Receiver};
66 use std::time::Instant;
68 use libc::{c_uint, c_void, c_char, size_t};
70 pub const RELOC_MODEL_ARGS : [(&str, llvm::RelocMode); 7] = [
71 ("pic", llvm::RelocMode::PIC),
72 ("static", llvm::RelocMode::Static),
73 ("default", llvm::RelocMode::Default),
74 ("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
75 ("ropi", llvm::RelocMode::ROPI),
76 ("rwpi", llvm::RelocMode::RWPI),
77 ("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
80 pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
81 ("small", llvm::CodeModel::Small),
82 ("kernel", llvm::CodeModel::Kernel),
83 ("medium", llvm::CodeModel::Medium),
84 ("large", llvm::CodeModel::Large),
87 pub const TLS_MODEL_ARGS : [(&str, llvm::ThreadLocalMode); 4] = [
88 ("global-dynamic", llvm::ThreadLocalMode::GeneralDynamic),
89 ("local-dynamic", llvm::ThreadLocalMode::LocalDynamic),
90 ("initial-exec", llvm::ThreadLocalMode::InitialExec),
91 ("local-exec", llvm::ThreadLocalMode::LocalExec),
94 const PRE_THIN_LTO_BC_EXT: &str = "pre-thin-lto.bc";
96 pub fn llvm_err(handler: &errors::Handler, msg: &str) -> FatalError {
97 match llvm::last_error() {
98 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
99 None => handler.fatal(&msg),
103 pub fn write_output_file(
104 handler: &errors::Handler,
105 target: &'ll llvm::TargetMachine,
106 pm: &llvm::PassManager<'ll>,
107 m: &'ll llvm::Module,
109 file_type: llvm::FileType) -> Result<(), FatalError> {
111 let output_c = path2cstr(output);
112 let result = llvm::LLVMRustWriteOutputFile(target, pm, m, output_c.as_ptr(), file_type);
113 if result.into_result().is_err() {
114 let msg = format!("could not write output to {}", output.display());
115 Err(llvm_err(handler, &msg))
122 fn get_llvm_opt_level(optimize: config::OptLevel) -> llvm::CodeGenOptLevel {
124 config::OptLevel::No => llvm::CodeGenOptLevel::None,
125 config::OptLevel::Less => llvm::CodeGenOptLevel::Less,
126 config::OptLevel::Default => llvm::CodeGenOptLevel::Default,
127 config::OptLevel::Aggressive => llvm::CodeGenOptLevel::Aggressive,
128 _ => llvm::CodeGenOptLevel::Default,
132 fn get_llvm_opt_size(optimize: config::OptLevel) -> llvm::CodeGenOptSize {
134 config::OptLevel::Size => llvm::CodeGenOptSizeDefault,
135 config::OptLevel::SizeMin => llvm::CodeGenOptSizeAggressive,
136 _ => llvm::CodeGenOptSizeNone,
140 pub fn create_target_machine(
143 ) -> &'static mut llvm::TargetMachine {
144 target_machine_factory(sess, find_features)().unwrap_or_else(|err| {
145 llvm_err(sess.diagnostic(), &err).raise()
149 // If find_features is true this won't access `sess.crate_types` by assuming
150 // that `is_pie_binary` is false. When we discover LLVM target features
151 // `sess.crate_types` is uninitialized so we cannot access it.
152 pub fn target_machine_factory(sess: &Session, find_features: bool)
153 -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>
155 let reloc_model = get_reloc_model(sess);
157 let opt_level = get_llvm_opt_level(sess.opts.optimize);
158 let use_softfp = sess.opts.cg.soft_float;
160 let ffunction_sections = sess.target.target.options.function_sections;
161 let fdata_sections = ffunction_sections;
163 let code_model_arg = sess.opts.cg.code_model.as_ref().or(
164 sess.target.target.options.code_model.as_ref(),
167 let code_model = match code_model_arg {
169 match CODE_GEN_MODEL_ARGS.iter().find(|arg| arg.0 == s) {
172 sess.err(&format!("{:?} is not a valid code model",
174 sess.abort_if_errors();
179 None => llvm::CodeModel::None,
182 let features = attributes::llvm_target_features(sess).collect::<Vec<_>>();
183 let mut singlethread = sess.target.target.options.singlethread;
185 // On the wasm target once the `atomics` feature is enabled that means that
186 // we're no longer single-threaded, or otherwise we don't want LLVM to
187 // lower atomic operations to single-threaded operations.
189 sess.target.target.llvm_target.contains("wasm32") &&
190 features.iter().any(|s| *s == "+atomics")
192 singlethread = false;
195 let triple = SmallCStr::new(&sess.target.target.llvm_target);
196 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
197 let features = features.join(",");
198 let features = CString::new(features).unwrap();
199 let is_pie_binary = !find_features && is_pie_binary(sess);
200 let trap_unreachable = sess.target.target.options.trap_unreachable;
201 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
203 let asm_comments = sess.asm_comments();
207 llvm::LLVMRustCreateTargetMachine(
208 triple.as_ptr(), cpu.as_ptr(), features.as_ptr(),
219 emit_stack_size_section,
224 format!("Could not create LLVM TargetMachine for triple: {}",
225 triple.to_str().unwrap())
230 /// Module-specific configuration for `optimize_and_codegen`.
231 pub struct ModuleConfig {
232 /// Names of additional optimization passes to run.
234 /// Some(level) to optimize at a certain level, or None to run
235 /// absolutely no optimizations (used for the metadata module).
236 pub opt_level: Option<llvm::CodeGenOptLevel>,
238 /// Some(level) to optimize binary size, or None to not affect program size.
239 opt_size: Option<llvm::CodeGenOptSize>,
241 pgo_gen: Option<String>,
244 // Flags indicating which outputs to produce.
245 pub emit_pre_thin_lto_bc: bool,
246 emit_no_opt_bc: bool,
248 emit_bc_compressed: bool,
253 // Miscellaneous flags. These are mostly copied from command-line
255 pub verify_llvm_ir: bool,
256 no_prepopulate_passes: bool,
259 vectorize_loop: bool,
261 merge_functions: bool,
262 inline_threshold: Option<usize>,
263 // Instead of creating an object file by doing LLVM codegen, just
264 // make the object file bitcode. Provides easy compatibility with
265 // emscripten's ecc compiler, when used as the linker.
266 obj_is_bitcode: bool,
267 no_integrated_as: bool,
269 embed_bitcode_marker: bool,
273 fn new(passes: Vec<String>) -> ModuleConfig {
280 pgo_use: String::new(),
282 emit_no_opt_bc: false,
283 emit_pre_thin_lto_bc: false,
285 emit_bc_compressed: false,
290 obj_is_bitcode: false,
291 embed_bitcode: false,
292 embed_bitcode_marker: false,
293 no_integrated_as: false,
295 verify_llvm_ir: false,
296 no_prepopulate_passes: false,
299 vectorize_loop: false,
300 vectorize_slp: false,
301 merge_functions: false,
302 inline_threshold: None
306 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
307 self.verify_llvm_ir = sess.verify_llvm_ir();
308 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
309 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
310 self.time_passes = sess.time_passes();
311 self.inline_threshold = sess.opts.cg.inline_threshold;
312 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
313 sess.opts.debugging_opts.cross_lang_lto.enabled();
314 let embed_bitcode = sess.target.target.options.embed_bitcode ||
315 sess.opts.debugging_opts.embed_bitcode;
317 match sess.opts.optimize {
318 config::OptLevel::No |
319 config::OptLevel::Less => {
320 self.embed_bitcode_marker = embed_bitcode;
322 _ => self.embed_bitcode = embed_bitcode,
326 // Copy what clang does by turning on loop vectorization at O2 and
327 // slp vectorization at O3. Otherwise configure other optimization aspects
328 // of this pass manager builder.
329 // Turn off vectorization for emscripten, as it's not very well supported.
330 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
331 (sess.opts.optimize == config::OptLevel::Default ||
332 sess.opts.optimize == config::OptLevel::Aggressive) &&
333 !sess.target.target.options.is_like_emscripten;
335 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
336 sess.opts.optimize == config::OptLevel::Aggressive &&
337 !sess.target.target.options.is_like_emscripten;
339 self.merge_functions = sess.opts.optimize == config::OptLevel::Default ||
340 sess.opts.optimize == config::OptLevel::Aggressive;
343 pub fn bitcode_needed(&self) -> bool {
344 self.emit_bc || self.obj_is_bitcode
345 || self.emit_bc_compressed || self.embed_bitcode
349 /// Assembler name and command used by codegen when no_integrated_as is enabled
350 struct AssemblerCommand {
355 /// Additional resources used by optimize_and_codegen (not module specific)
357 pub struct CodegenContext<'ll> {
358 // Resources needed when running LTO
359 pub time_passes: bool,
361 pub no_landing_pads: bool,
362 pub save_temps: bool,
363 pub fewer_names: bool,
364 pub exported_symbols: Option<Arc<ExportedSymbols>>,
365 pub opts: Arc<config::Options>,
366 pub crate_types: Vec<config::CrateType>,
367 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
368 output_filenames: Arc<OutputFilenames>,
369 regular_module_config: Arc<ModuleConfig>,
370 metadata_module_config: Arc<ModuleConfig>,
371 allocator_module_config: Arc<ModuleConfig>,
372 pub tm_factory: Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync>,
373 pub msvc_imps_needed: bool,
374 pub target_pointer_width: String,
375 debuginfo: config::DebugInfo,
377 // Number of cgus excluding the allocator/metadata modules
378 pub total_cgus: usize,
379 // Handler to use for diagnostics produced during codegen.
380 pub diag_emitter: SharedEmitter,
381 // LLVM passes added by plugins.
382 pub plugin_passes: Vec<String>,
383 // LLVM optimizations for which we want to print remarks.
385 // Worker thread number
387 // The incremental compilation session directory, or None if we are not
388 // compiling incrementally
389 pub incr_comp_session_dir: Option<PathBuf>,
390 // Used to update CGU re-use information during the thinlto phase.
391 pub cgu_reuse_tracker: CguReuseTracker,
392 // Channel back to the main control thread to send messages to
393 coordinator_send: Sender<Box<dyn Any + Send>>,
394 // A reference to the TimeGraph so we can register timings. None means that
395 // measuring is disabled.
396 time_graph: Option<TimeGraph>,
397 // The assembler command if no_integrated_as option is enabled, None otherwise
398 assembler_cmd: Option<Arc<AssemblerCommand>>,
399 // This field is used to give a lifetime parameter to the struct so that it can implement
400 // the Backend trait.
401 phantom: PhantomData<&'ll ()>
404 impl CodegenContext<'ll> {
405 pub fn create_diag_handler(&self) -> Handler {
406 Handler::with_emitter(true, false, Box::new(self.diag_emitter.clone()))
409 pub(crate) fn config(&self, kind: ModuleKind) -> &ModuleConfig {
411 ModuleKind::Regular => &self.regular_module_config,
412 ModuleKind::Metadata => &self.metadata_module_config,
413 ModuleKind::Allocator => &self.allocator_module_config,
417 pub(crate) fn save_temp_bitcode(&self, module: &ModuleCodegen, name: &str) {
418 if !self.save_temps {
422 let ext = format!("{}.bc", name);
423 let cgu = Some(&module.name[..]);
424 let path = self.output_filenames.temp_path_ext(&ext, cgu);
425 let cstr = path2cstr(&path);
426 let llmod = module.module_llvm.llmod();
427 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
432 impl<'ll> Backend for CodegenContext<'ll> {
433 type Value = &'ll Value;
434 type BasicBlock = &'ll BasicBlock;
435 type Type = &'ll Type;
436 type Context = &'ll llvm::Context;
437 type TypeKind = llvm::TypeKind;
440 impl CommonWriteMethods for CodegenContext<'ll> {
441 fn val_ty(&self, v: &'ll Value) -> &'ll Type {
445 fn c_bytes_in_context(&self, llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
446 common::c_bytes_in_context(llcx, bytes)
449 fn c_struct_in_context(
451 llcx: &'a llvm::Context,
455 common::c_struct_in_context(llcx, elts, packed)
460 pub struct DiagnosticHandlers<'a> {
461 data: *mut (&'a CodegenContext<'a>, &'a Handler),
462 llcx: &'a llvm::Context,
465 impl<'a> DiagnosticHandlers<'a> {
466 pub fn new(cgcx: &'a CodegenContext<'a>,
467 handler: &'a Handler,
468 llcx: &'a llvm::Context) -> Self {
469 let data = Box::into_raw(Box::new((cgcx, handler)));
471 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data as *mut _);
472 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data as *mut _);
474 DiagnosticHandlers { data, llcx }
478 impl<'a> Drop for DiagnosticHandlers<'a> {
480 use std::ptr::null_mut;
482 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
483 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
484 drop(Box::from_raw(self.data));
489 unsafe extern "C" fn report_inline_asm<'a, 'b>(cgcx: &'a CodegenContext,
492 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned());
495 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
501 let (cgcx, _) = *(user as *const (&CodegenContext, &Handler));
503 let msg = llvm::build_string(|s| llvm::LLVMRustWriteSMDiagnosticToString(diag, s))
504 .expect("non-UTF8 SMDiagnostic");
506 report_inline_asm(cgcx, &msg, cookie);
509 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
513 let (cgcx, diag_handler) = *(user as *const (&CodegenContext, &Handler));
515 match llvm::diagnostic::Diagnostic::unpack(info) {
516 llvm::diagnostic::InlineAsm(inline) => {
517 report_inline_asm(cgcx,
518 &llvm::twine_to_string(inline.message),
522 llvm::diagnostic::Optimization(opt) => {
523 let enabled = match cgcx.remark {
525 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
529 diag_handler.note_without_error(&format!("optimization {} for {} at {}:{}:{}: {}",
538 llvm::diagnostic::PGO(diagnostic_ref) |
539 llvm::diagnostic::Linker(diagnostic_ref) => {
540 let msg = llvm::build_string(|s| {
541 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
542 }).expect("non-UTF8 diagnostic");
543 diag_handler.warn(&msg);
545 llvm::diagnostic::UnknownDiagnostic(..) => {},
549 // Unsafe due to LLVM calls.
550 unsafe fn optimize(cgcx: &CodegenContext,
551 diag_handler: &Handler,
552 module: &ModuleCodegen,
553 config: &ModuleConfig,
554 timeline: &mut Timeline)
555 -> Result<(), FatalError>
557 let llmod = module.module_llvm.llmod();
558 let llcx = &*module.module_llvm.llcx;
559 let tm = &*module.module_llvm.tm;
560 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
562 let module_name = module.name.clone();
563 let module_name = Some(&module_name[..]);
565 if config.emit_no_opt_bc {
566 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
567 let out = path2cstr(&out);
568 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
571 if config.opt_level.is_some() {
572 // Create the two optimizing pass managers. These mirror what clang
573 // does, and are by populated by LLVM's default PassManagerBuilder.
574 // Each manager has a different set of passes, but they also share
575 // some common passes.
576 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
577 let mpm = llvm::LLVMCreatePassManager();
580 // If we're verifying or linting, add them to the function pass
582 let addpass = |pass_name: &str| {
583 let pass_name = SmallCStr::new(pass_name);
584 let pass = match llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr()) {
586 None => return false,
588 let pass_manager = match llvm::LLVMRustPassKind(pass) {
589 llvm::PassKind::Function => &*fpm,
590 llvm::PassKind::Module => &*mpm,
591 llvm::PassKind::Other => {
592 diag_handler.err("Encountered LLVM pass kind we can't handle");
596 llvm::LLVMRustAddPass(pass_manager, pass);
600 if config.verify_llvm_ir { assert!(addpass("verify")); }
602 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
603 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
604 // we'll get errors in LLVM.
605 let using_thin_buffers = config.bitcode_needed();
606 let mut have_name_anon_globals_pass = false;
607 if !config.no_prepopulate_passes {
608 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
609 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
610 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
611 let prepare_for_thin_lto = cgcx.lto == Lto::Thin || cgcx.lto == Lto::ThinLocal ||
612 (cgcx.lto != Lto::Fat && cgcx.opts.debugging_opts.cross_lang_lto.enabled());
613 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
614 if using_thin_buffers && !prepare_for_thin_lto {
615 assert!(addpass("name-anon-globals"));
616 have_name_anon_globals_pass = true;
618 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
619 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
620 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
624 for pass in &config.passes {
626 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass));
628 if pass == "name-anon-globals" {
629 have_name_anon_globals_pass = true;
633 for pass in &cgcx.plugin_passes {
635 diag_handler.err(&format!("a plugin asked for LLVM pass \
636 `{}` but LLVM does not \
637 recognize it", pass));
639 if pass == "name-anon-globals" {
640 have_name_anon_globals_pass = true;
644 if using_thin_buffers && !have_name_anon_globals_pass {
645 // As described above, this will probably cause an error in LLVM
646 if config.no_prepopulate_passes {
647 diag_handler.err("The current compilation is going to use thin LTO buffers \
648 without running LLVM's NameAnonGlobals pass. \
649 This will likely cause errors in LLVM. Consider adding \
650 -C passes=name-anon-globals to the compiler command line.");
652 bug!("We are using thin LTO buffers without running the NameAnonGlobals pass. \
653 This will likely cause errors in LLVM and should never happen.");
658 diag_handler.abort_if_errors();
660 // Finally, run the actual optimization passes
661 time_ext(config.time_passes,
663 &format!("llvm function passes [{}]", module_name.unwrap()),
665 llvm::LLVMRustRunFunctionPassManager(fpm, llmod)
667 timeline.record("fpm");
668 time_ext(config.time_passes,
670 &format!("llvm module passes [{}]", module_name.unwrap()),
672 llvm::LLVMRunPassManager(mpm, llmod)
675 // Deallocate managers that we're now done with
676 llvm::LLVMDisposePassManager(fpm);
677 llvm::LLVMDisposePassManager(mpm);
682 fn generate_lto_work(cgcx: &CodegenContext,
683 modules: Vec<ModuleCodegen>,
684 import_only_modules: Vec<(SerializedModule, WorkProduct)>)
685 -> Vec<(WorkItem, u64)>
687 let mut timeline = cgcx.time_graph.as_ref().map(|tg| {
688 tg.start(CODEGEN_WORKER_TIMELINE,
689 CODEGEN_WORK_PACKAGE_KIND,
691 }).unwrap_or(Timeline::noop());
692 let (lto_modules, copy_jobs) = lto::run(cgcx, modules, import_only_modules, &mut timeline)
693 .unwrap_or_else(|e| e.raise());
695 let lto_modules = lto_modules.into_iter().map(|module| {
696 let cost = module.cost();
697 (WorkItem::LTO(module), cost)
700 let copy_jobs = copy_jobs.into_iter().map(|wp| {
701 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
702 name: wp.cgu_name.clone(),
707 lto_modules.chain(copy_jobs).collect()
710 unsafe fn codegen(cgcx: &CodegenContext,
711 diag_handler: &Handler,
712 module: ModuleCodegen,
713 config: &ModuleConfig,
714 timeline: &mut Timeline)
715 -> Result<CompiledModule, FatalError>
717 timeline.record("codegen");
719 let llmod = module.module_llvm.llmod();
720 let llcx = &*module.module_llvm.llcx;
721 let tm = &*module.module_llvm.tm;
722 let module_name = module.name.clone();
723 let module_name = Some(&module_name[..]);
724 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
726 if cgcx.msvc_imps_needed {
727 create_msvc_imps(cgcx, llcx, llmod);
730 // A codegen-specific pass manager is used to generate object
731 // files for an LLVM module.
733 // Apparently each of these pass managers is a one-shot kind of
734 // thing, so we create a new one for each type of output. The
735 // pass manager passed to the closure should be ensured to not
736 // escape the closure itself, and the manager should only be
738 unsafe fn with_codegen<'ll, F, R>(tm: &'ll llvm::TargetMachine,
739 llmod: &'ll llvm::Module,
742 where F: FnOnce(&'ll mut PassManager<'ll>) -> R,
744 let cpm = llvm::LLVMCreatePassManager();
745 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
746 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
750 // If we don't have the integrated assembler, then we need to emit asm
751 // from LLVM and use `gcc` to create the object file.
752 let asm_to_obj = config.emit_obj && config.no_integrated_as;
754 // Change what we write and cleanup based on whether obj files are
755 // just llvm bitcode. In that case write bitcode, and possibly
756 // delete the bitcode if it wasn't requested. Don't generate the
757 // machine code, instead copy the .o file from the .bc
758 let write_bc = config.emit_bc || config.obj_is_bitcode;
759 let rm_bc = !config.emit_bc && config.obj_is_bitcode;
760 let write_obj = config.emit_obj && !config.obj_is_bitcode && !asm_to_obj;
761 let copy_bc_to_obj = config.emit_obj && config.obj_is_bitcode;
763 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
764 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
767 if write_bc || config.emit_bc_compressed || config.embed_bitcode {
768 let thin = ThinBuffer::new(llmod);
769 let data = thin.data();
770 timeline.record("make-bc");
773 if let Err(e) = fs::write(&bc_out, data) {
774 diag_handler.err(&format!("failed to write bytecode: {}", e));
776 timeline.record("write-bc");
779 if config.embed_bitcode {
780 embed_bitcode(cgcx, llcx, llmod, Some(data));
781 timeline.record("embed-bc");
784 if config.emit_bc_compressed {
785 let dst = bc_out.with_extension(RLIB_BYTECODE_EXTENSION);
786 let data = bytecode::encode(&module.name, data);
787 if let Err(e) = fs::write(&dst, data) {
788 diag_handler.err(&format!("failed to write bytecode: {}", e));
790 timeline.record("compress-bc");
792 } else if config.embed_bitcode_marker {
793 embed_bitcode(cgcx, llcx, llmod, None);
796 time_ext(config.time_passes, None, &format!("codegen passes [{}]", module_name.unwrap()),
797 || -> Result<(), FatalError> {
799 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
800 let out = path2cstr(&out);
802 extern "C" fn demangle_callback(input_ptr: *const c_char,
804 output_ptr: *mut c_char,
805 output_len: size_t) -> size_t {
807 slice::from_raw_parts(input_ptr as *const u8, input_len as usize)
810 let input = match str::from_utf8(input) {
815 let output = unsafe {
816 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
818 let mut cursor = io::Cursor::new(output);
820 let demangled = match rustc_demangle::try_demangle(input) {
825 if let Err(_) = write!(cursor, "{:#}", demangled) {
826 // Possible only if provided buffer is not big enough
830 cursor.position() as size_t
833 with_codegen(tm, llmod, config.no_builtins, |cpm| {
834 llvm::LLVMRustPrintModule(cpm, llmod, out.as_ptr(), demangle_callback);
835 llvm::LLVMDisposePassManager(cpm);
837 timeline.record("ir");
840 if config.emit_asm || asm_to_obj {
841 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
843 // We can't use the same module for asm and binary output, because that triggers
844 // various errors like invalid IR or broken binaries, so we might have to clone the
845 // module to produce the asm output
846 let llmod = if config.emit_obj {
847 llvm::LLVMCloneModule(llmod)
851 with_codegen(tm, llmod, config.no_builtins, |cpm| {
852 write_output_file(diag_handler, tm, cpm, llmod, &path,
853 llvm::FileType::AssemblyFile)
855 timeline.record("asm");
859 with_codegen(tm, llmod, config.no_builtins, |cpm| {
860 write_output_file(diag_handler, tm, cpm, llmod, &obj_out,
861 llvm::FileType::ObjectFile)
863 timeline.record("obj");
864 } else if asm_to_obj {
865 let assembly = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
866 run_assembler(cgcx, diag_handler, &assembly, &obj_out);
867 timeline.record("asm_to_obj");
869 if !config.emit_asm && !cgcx.save_temps {
870 drop(fs::remove_file(&assembly));
878 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
879 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
880 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
885 debug!("removing_bitcode {:?}", bc_out);
886 if let Err(e) = fs::remove_file(&bc_out) {
887 diag_handler.err(&format!("failed to remove bitcode: {}", e));
893 Ok(module.into_compiled_module(config.emit_obj,
895 config.emit_bc_compressed,
896 &cgcx.output_filenames))
899 /// Embed the bitcode of an LLVM module in the LLVM module itself.
901 /// This is done primarily for iOS where it appears to be standard to compile C
902 /// code at least with `-fembed-bitcode` which creates two sections in the
905 /// * __LLVM,__bitcode
906 /// * __LLVM,__cmdline
908 /// It appears *both* of these sections are necessary to get the linker to
909 /// recognize what's going on. For us though we just always throw in an empty
912 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
913 /// embed an empty section.
915 /// Basically all of this is us attempting to follow in the footsteps of clang
916 /// on iOS. See #35968 for lots more info.
917 unsafe fn embed_bitcode(cgcx: &CodegenContext,
918 llcx: &llvm::Context,
919 llmod: &llvm::Module,
920 bitcode: Option<&[u8]>) {
921 let llconst = cgcx.c_bytes_in_context(llcx, bitcode.unwrap_or(&[]));
922 let llglobal = llvm::LLVMAddGlobal(
924 cgcx.val_ty(llconst),
925 "rustc.embedded.module\0".as_ptr() as *const _,
927 llvm::LLVMSetInitializer(llglobal, llconst);
929 let is_apple = cgcx.opts.target_triple.triple().contains("-ios") ||
930 cgcx.opts.target_triple.triple().contains("-darwin");
932 let section = if is_apple {
937 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
938 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
939 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
941 let llconst = cgcx.c_bytes_in_context(llcx, &[]);
942 let llglobal = llvm::LLVMAddGlobal(
944 cgcx.val_ty(llconst),
945 "rustc.embedded.cmdline\0".as_ptr() as *const _,
947 llvm::LLVMSetInitializer(llglobal, llconst);
948 let section = if is_apple {
953 llvm::LLVMSetSection(llglobal, section.as_ptr() as *const _);
954 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
957 pub(crate) struct CompiledModules {
958 pub modules: Vec<CompiledModule>,
959 pub metadata_module: CompiledModule,
960 pub allocator_module: Option<CompiledModule>,
963 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
964 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
965 sess.opts.output_types.contains_key(&OutputType::Exe)
968 fn need_pre_thin_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
969 if sess.opts.incremental.is_none() {
977 Lto::ThinLocal => true,
981 pub fn start_async_codegen(tcx: TyCtxt,
982 time_graph: Option<TimeGraph>,
983 metadata: EncodedMetadata,
984 coordinator_receive: Receiver<Box<dyn Any + Send>>,
988 let crate_name = tcx.crate_name(LOCAL_CRATE);
989 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
990 let no_builtins = attr::contains_name(&tcx.hir.krate().attrs, "no_builtins");
991 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir.krate().attrs,
992 "windows_subsystem");
993 let windows_subsystem = subsystem.map(|subsystem| {
994 if subsystem != "windows" && subsystem != "console" {
995 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
996 `windows` and `console` are allowed",
999 subsystem.to_string()
1002 let linker_info = LinkerInfo::new(tcx);
1003 let crate_info = CrateInfo::new(tcx);
1005 // Figure out what we actually need to build.
1006 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
1007 let mut metadata_config = ModuleConfig::new(vec![]);
1008 let mut allocator_config = ModuleConfig::new(vec![]);
1010 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
1012 Sanitizer::Address => {
1013 modules_config.passes.push("asan".to_owned());
1014 modules_config.passes.push("asan-module".to_owned());
1016 Sanitizer::Memory => {
1017 modules_config.passes.push("msan".to_owned())
1019 Sanitizer::Thread => {
1020 modules_config.passes.push("tsan".to_owned())
1026 if sess.opts.debugging_opts.profile {
1027 modules_config.passes.push("insert-gcov-profiling".to_owned())
1030 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
1031 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
1033 modules_config.opt_level = Some(get_llvm_opt_level(sess.opts.optimize));
1034 modules_config.opt_size = Some(get_llvm_opt_size(sess.opts.optimize));
1036 // Save all versions of the bytecode if we're saving our temporaries.
1037 if sess.opts.cg.save_temps {
1038 modules_config.emit_no_opt_bc = true;
1039 modules_config.emit_pre_thin_lto_bc = true;
1040 modules_config.emit_bc = true;
1041 modules_config.emit_lto_bc = true;
1042 metadata_config.emit_bc = true;
1043 allocator_config.emit_bc = true;
1046 // Emit compressed bitcode files for the crate if we're emitting an rlib.
1047 // Whenever an rlib is created, the bitcode is inserted into the archive in
1048 // order to allow LTO against it.
1049 if need_crate_bitcode_for_rlib(sess) {
1050 modules_config.emit_bc_compressed = true;
1051 allocator_config.emit_bc_compressed = true;
1054 modules_config.emit_pre_thin_lto_bc =
1055 need_pre_thin_lto_bitcode_for_incr_comp(sess);
1057 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1058 tcx.sess.target.target.options.no_integrated_as;
1060 for output_type in sess.opts.output_types.keys() {
1061 match *output_type {
1062 OutputType::Bitcode => { modules_config.emit_bc = true; }
1063 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
1064 OutputType::Assembly => {
1065 modules_config.emit_asm = true;
1066 // If we're not using the LLVM assembler, this function
1067 // could be invoked specially with output_type_assembly, so
1068 // in this case we still want the metadata object file.
1069 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
1070 metadata_config.emit_obj = true;
1071 allocator_config.emit_obj = true;
1074 OutputType::Object => { modules_config.emit_obj = true; }
1075 OutputType::Metadata => { metadata_config.emit_obj = true; }
1076 OutputType::Exe => {
1077 modules_config.emit_obj = true;
1078 metadata_config.emit_obj = true;
1079 allocator_config.emit_obj = true;
1081 OutputType::Mir => {}
1082 OutputType::DepInfo => {}
1086 modules_config.set_flags(sess, no_builtins);
1087 metadata_config.set_flags(sess, no_builtins);
1088 allocator_config.set_flags(sess, no_builtins);
1090 // Exclude metadata and allocator modules from time_passes output, since
1091 // they throw off the "LLVM passes" measurement.
1092 metadata_config.time_passes = false;
1093 allocator_config.time_passes = false;
1095 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
1096 let (codegen_worker_send, codegen_worker_receive) = channel();
1098 let coordinator_thread = start_executing_work(tcx,
1101 codegen_worker_send,
1102 coordinator_receive,
1104 sess.jobserver.clone(),
1106 Arc::new(modules_config),
1107 Arc::new(metadata_config),
1108 Arc::new(allocator_config));
1119 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
1120 codegen_worker_receive,
1121 shared_emitter_main,
1122 future: coordinator_thread,
1123 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1127 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
1129 compiled_modules: &CompiledModules,
1130 ) -> FxHashMap<WorkProductId, WorkProduct> {
1131 let mut work_products = FxHashMap::default();
1133 if sess.opts.incremental.is_none() {
1134 return work_products;
1137 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
1138 let mut files = vec![];
1140 if let Some(ref path) = module.object {
1141 files.push((WorkProductFileKind::Object, path.clone()));
1143 if let Some(ref path) = module.bytecode {
1144 files.push((WorkProductFileKind::Bytecode, path.clone()));
1146 if let Some(ref path) = module.bytecode_compressed {
1147 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
1150 if let Some((id, product)) =
1151 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files)
1153 work_products.insert(id, product);
1160 fn produce_final_output_artifacts(sess: &Session,
1161 compiled_modules: &CompiledModules,
1162 crate_output: &OutputFilenames) {
1163 let mut user_wants_bitcode = false;
1164 let mut user_wants_objects = false;
1166 // Produce final compile outputs.
1167 let copy_gracefully = |from: &Path, to: &Path| {
1168 if let Err(e) = fs::copy(from, to) {
1169 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
1173 let copy_if_one_unit = |output_type: OutputType,
1174 keep_numbered: bool| {
1175 if compiled_modules.modules.len() == 1 {
1176 // 1) Only one codegen unit. In this case it's no difficulty
1177 // to copy `foo.0.x` to `foo.x`.
1178 let module_name = Some(&compiled_modules.modules[0].name[..]);
1179 let path = crate_output.temp_path(output_type, module_name);
1180 copy_gracefully(&path,
1181 &crate_output.path(output_type));
1182 if !sess.opts.cg.save_temps && !keep_numbered {
1183 // The user just wants `foo.x`, not `foo.#module-name#.x`.
1184 remove(sess, &path);
1187 let ext = crate_output.temp_path(output_type, None)
1194 if crate_output.outputs.contains_key(&output_type) {
1195 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
1196 // no good solution for this case, so warn the user.
1197 sess.warn(&format!("ignoring emit path because multiple .{} files \
1198 were produced", ext));
1199 } else if crate_output.single_output_file.is_some() {
1200 // 3) Multiple codegen units, with `-o some_name`. We have
1201 // no good solution for this case, so warn the user.
1202 sess.warn(&format!("ignoring -o because multiple .{} files \
1203 were produced", ext));
1205 // 4) Multiple codegen units, but no explicit name. We
1206 // just leave the `foo.0.x` files in place.
1207 // (We don't have to do any work in this case.)
1212 // Flag to indicate whether the user explicitly requested bitcode.
1213 // Otherwise, we produced it only as a temporary output, and will need
1214 // to get rid of it.
1215 for output_type in crate_output.outputs.keys() {
1216 match *output_type {
1217 OutputType::Bitcode => {
1218 user_wants_bitcode = true;
1219 // Copy to .bc, but always keep the .0.bc. There is a later
1220 // check to figure out if we should delete .0.bc files, or keep
1221 // them for making an rlib.
1222 copy_if_one_unit(OutputType::Bitcode, true);
1224 OutputType::LlvmAssembly => {
1225 copy_if_one_unit(OutputType::LlvmAssembly, false);
1227 OutputType::Assembly => {
1228 copy_if_one_unit(OutputType::Assembly, false);
1230 OutputType::Object => {
1231 user_wants_objects = true;
1232 copy_if_one_unit(OutputType::Object, true);
1235 OutputType::Metadata |
1237 OutputType::DepInfo => {}
1241 // Clean up unwanted temporary files.
1243 // We create the following files by default:
1244 // - #crate#.#module-name#.bc
1245 // - #crate#.#module-name#.o
1246 // - #crate#.crate.metadata.bc
1247 // - #crate#.crate.metadata.o
1248 // - #crate#.o (linked from crate.##.o)
1249 // - #crate#.bc (copied from crate.##.bc)
1250 // We may create additional files if requested by the user (through
1251 // `-C save-temps` or `--emit=` flags).
1253 if !sess.opts.cg.save_temps {
1254 // Remove the temporary .#module-name#.o objects. If the user didn't
1255 // explicitly request bitcode (with --emit=bc), and the bitcode is not
1256 // needed for building an rlib, then we must remove .#module-name#.bc as
1259 // Specific rules for keeping .#module-name#.bc:
1260 // - If the user requested bitcode (`user_wants_bitcode`), and
1261 // codegen_units > 1, then keep it.
1262 // - If the user requested bitcode but codegen_units == 1, then we
1263 // can toss .#module-name#.bc because we copied it to .bc earlier.
1264 // - If we're not building an rlib and the user didn't request
1265 // bitcode, then delete .#module-name#.bc.
1266 // If you change how this works, also update back::link::link_rlib,
1267 // where .#module-name#.bc files are (maybe) deleted after making an
1269 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
1271 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
1273 let keep_numbered_objects = needs_crate_object ||
1274 (user_wants_objects && sess.codegen_units() > 1);
1276 for module in compiled_modules.modules.iter() {
1277 if let Some(ref path) = module.object {
1278 if !keep_numbered_objects {
1283 if let Some(ref path) = module.bytecode {
1284 if !keep_numbered_bitcode {
1290 if !user_wants_bitcode {
1291 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
1292 remove(sess, &path);
1295 if let Some(ref allocator_module) = compiled_modules.allocator_module {
1296 if let Some(ref path) = allocator_module.bytecode {
1303 // We leave the following files around by default:
1305 // - #crate#.crate.metadata.o
1307 // These are used in linking steps and will be cleaned up afterward.
1310 pub(crate) fn dump_incremental_data(_codegen_results: &CodegenResults) {
1311 // FIXME(mw): This does not work at the moment because the situation has
1312 // become more complicated due to incremental LTO. Now a CGU
1313 // can have more than two caching states.
1314 // println!("[incremental] Re-using {} out of {} modules",
1315 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
1316 // codegen_results.modules.len());
1320 /// Optimize a newly codegened, totally unoptimized module.
1321 Optimize(ModuleCodegen),
1322 /// Copy the post-LTO artifacts from the incremental cache to the output
1324 CopyPostLtoArtifacts(CachedModuleCodegen),
1325 /// Perform (Thin)LTO on the given module.
1326 LTO(lto::LtoModuleCodegen),
1330 fn module_kind(&self) -> ModuleKind {
1332 WorkItem::Optimize(ref m) => m.kind,
1333 WorkItem::CopyPostLtoArtifacts(_) |
1334 WorkItem::LTO(_) => ModuleKind::Regular,
1338 fn name(&self) -> String {
1340 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
1341 WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
1342 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
1347 enum WorkItemResult {
1348 Compiled(CompiledModule),
1349 NeedsLTO(ModuleCodegen),
1352 fn execute_work_item(cgcx: &CodegenContext,
1353 work_item: WorkItem,
1354 timeline: &mut Timeline)
1355 -> Result<WorkItemResult, FatalError>
1357 let module_config = cgcx.config(work_item.module_kind());
1360 WorkItem::Optimize(module) => {
1361 execute_optimize_work_item(cgcx, module, module_config, timeline)
1363 WorkItem::CopyPostLtoArtifacts(module) => {
1364 execute_copy_from_cache_work_item(cgcx, module, module_config, timeline)
1366 WorkItem::LTO(module) => {
1367 execute_lto_work_item(cgcx, module, module_config, timeline)
1372 fn execute_optimize_work_item(cgcx: &CodegenContext,
1373 module: ModuleCodegen,
1374 module_config: &ModuleConfig,
1375 timeline: &mut Timeline)
1376 -> Result<WorkItemResult, FatalError>
1378 let diag_handler = cgcx.create_diag_handler();
1381 optimize(cgcx, &diag_handler, &module, module_config, timeline)?;
1384 let linker_does_lto = cgcx.opts.debugging_opts.cross_lang_lto.enabled();
1386 // After we've done the initial round of optimizations we need to
1387 // decide whether to synchronously codegen this module or ship it
1388 // back to the coordinator thread for further LTO processing (which
1389 // has to wait for all the initial modules to be optimized).
1391 // Here we dispatch based on the `cgcx.lto` and kind of module we're
1393 let needs_lto = match cgcx.lto {
1396 // If the linker does LTO, we don't have to do it. Note that we
1397 // keep doing full LTO, if it is requested, as not to break the
1398 // assumption that the output will be a single module.
1399 Lto::Thin | Lto::ThinLocal if linker_does_lto => false,
1401 // Here we've got a full crate graph LTO requested. We ignore
1402 // this, however, if the crate type is only an rlib as there's
1403 // no full crate graph to process, that'll happen later.
1405 // This use case currently comes up primarily for targets that
1406 // require LTO so the request for LTO is always unconditionally
1407 // passed down to the backend, but we don't actually want to do
1408 // anything about it yet until we've got a final product.
1409 Lto::Fat | Lto::Thin => {
1410 cgcx.crate_types.len() != 1 ||
1411 cgcx.crate_types[0] != config::CrateType::Rlib
1414 // When we're automatically doing ThinLTO for multi-codegen-unit
1415 // builds we don't actually want to LTO the allocator modules if
1416 // it shows up. This is due to various linker shenanigans that
1417 // we'll encounter later.
1419 module.kind != ModuleKind::Allocator
1423 // Metadata modules never participate in LTO regardless of the lto
1425 let needs_lto = needs_lto && module.kind != ModuleKind::Metadata;
1428 Ok(WorkItemResult::NeedsLTO(module))
1430 let module = unsafe {
1431 codegen(cgcx, &diag_handler, module, module_config, timeline)?
1433 Ok(WorkItemResult::Compiled(module))
1437 fn execute_copy_from_cache_work_item(cgcx: &CodegenContext,
1438 module: CachedModuleCodegen,
1439 module_config: &ModuleConfig,
1441 -> Result<WorkItemResult, FatalError>
1443 let incr_comp_session_dir = cgcx.incr_comp_session_dir
1446 let mut object = None;
1447 let mut bytecode = None;
1448 let mut bytecode_compressed = None;
1449 for (kind, saved_file) in &module.source.saved_files {
1450 let obj_out = match kind {
1451 WorkProductFileKind::Object => {
1452 let path = cgcx.output_filenames.temp_path(OutputType::Object,
1453 Some(&module.name));
1454 object = Some(path.clone());
1457 WorkProductFileKind::Bytecode => {
1458 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1459 Some(&module.name));
1460 bytecode = Some(path.clone());
1463 WorkProductFileKind::BytecodeCompressed => {
1464 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
1466 .with_extension(RLIB_BYTECODE_EXTENSION);
1467 bytecode_compressed = Some(path.clone());
1471 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
1473 debug!("copying pre-existing module `{}` from {:?} to {}",
1477 if let Err(err) = link_or_copy(&source_file, &obj_out) {
1478 let diag_handler = cgcx.create_diag_handler();
1479 diag_handler.err(&format!("unable to copy {} to {}: {}",
1480 source_file.display(),
1486 assert_eq!(object.is_some(), module_config.emit_obj);
1487 assert_eq!(bytecode.is_some(), module_config.emit_bc);
1488 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
1490 Ok(WorkItemResult::Compiled(CompiledModule {
1492 kind: ModuleKind::Regular,
1495 bytecode_compressed,
1499 fn execute_lto_work_item(cgcx: &CodegenContext,
1500 mut module: lto::LtoModuleCodegen,
1501 module_config: &ModuleConfig,
1502 timeline: &mut Timeline)
1503 -> Result<WorkItemResult, FatalError>
1505 let diag_handler = cgcx.create_diag_handler();
1508 let module = module.optimize(cgcx, timeline)?;
1509 let module = codegen(cgcx, &diag_handler, module, module_config, timeline)?;
1510 Ok(WorkItemResult::Compiled(module))
1515 Token(io::Result<Acquired>),
1517 result: ModuleCodegen,
1521 result: Result<CompiledModule, ()>,
1525 llvm_work_item: WorkItem,
1528 AddImportOnlyModule {
1529 module_data: SerializedModule,
1530 work_product: WorkProduct,
1539 code: Option<DiagnosticId>,
1543 #[derive(PartialEq, Clone, Copy, Debug)]
1544 enum MainThreadWorkerState {
1550 fn start_executing_work(tcx: TyCtxt,
1551 crate_info: &CrateInfo,
1552 shared_emitter: SharedEmitter,
1553 codegen_worker_send: Sender<Message>,
1554 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1557 time_graph: Option<TimeGraph>,
1558 modules_config: Arc<ModuleConfig>,
1559 metadata_config: Arc<ModuleConfig>,
1560 allocator_config: Arc<ModuleConfig>)
1561 -> thread::JoinHandle<Result<CompiledModules, ()>> {
1562 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1563 let sess = tcx.sess;
1565 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1566 let exported_symbols = {
1567 let mut exported_symbols = FxHashMap::default();
1569 let copy_symbols = |cnum| {
1570 let symbols = tcx.exported_symbols(cnum)
1572 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1580 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1581 Some(Arc::new(exported_symbols))
1583 Lto::Fat | Lto::Thin => {
1584 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1585 for &cnum in tcx.crates().iter() {
1586 exported_symbols.insert(cnum, copy_symbols(cnum));
1588 Some(Arc::new(exported_symbols))
1593 // First up, convert our jobserver into a helper thread so we can use normal
1594 // mpsc channels to manage our messages and such.
1595 // After we've requested tokens then we'll, when we can,
1596 // get tokens on `coordinator_receive` which will
1597 // get managed in the main loop below.
1598 let coordinator_send2 = coordinator_send.clone();
1599 let helper = jobserver.into_helper_thread(move |token| {
1600 drop(coordinator_send2.send(Box::new(Message::Token(token))));
1601 }).expect("failed to spawn helper thread");
1603 let mut each_linked_rlib_for_lto = Vec::new();
1604 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1605 if link::ignored_for_lto(sess, crate_info, cnum) {
1608 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1611 let assembler_cmd = if modules_config.no_integrated_as {
1612 // HACK: currently we use linker (gcc) as our assembler
1613 let (linker, flavor) = link::linker_and_flavor(sess);
1615 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1616 cmd.args(&sess.target.target.options.asm_args);
1618 Some(Arc::new(AssemblerCommand { name, cmd }))
1623 let cgcx = CodegenContext {
1624 crate_types: sess.crate_types.borrow().clone(),
1625 each_linked_rlib_for_lto,
1627 no_landing_pads: sess.no_landing_pads(),
1628 fewer_names: sess.fewer_names(),
1629 save_temps: sess.opts.cg.save_temps,
1630 opts: Arc::new(sess.opts.clone()),
1631 time_passes: sess.time_passes(),
1633 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1634 remark: sess.opts.cg.remark.clone(),
1636 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1637 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1639 diag_emitter: shared_emitter.clone(),
1641 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1642 regular_module_config: modules_config,
1643 metadata_module_config: metadata_config,
1644 allocator_module_config: allocator_config,
1645 tm_factory: target_machine_factory(tcx.sess, false),
1647 msvc_imps_needed: msvc_imps_needed(tcx),
1648 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1649 debuginfo: tcx.sess.opts.debuginfo,
1651 phantom: PhantomData
1654 // This is the "main loop" of parallel work happening for parallel codegen.
1655 // It's here that we manage parallelism, schedule work, and work with
1656 // messages coming from clients.
1658 // There are a few environmental pre-conditions that shape how the system
1661 // - Error reporting only can happen on the main thread because that's the
1662 // only place where we have access to the compiler `Session`.
1663 // - LLVM work can be done on any thread.
1664 // - Codegen can only happen on the main thread.
1665 // - Each thread doing substantial work most be in possession of a `Token`
1666 // from the `Jobserver`.
1667 // - The compiler process always holds one `Token`. Any additional `Tokens`
1668 // have to be requested from the `Jobserver`.
1672 // The error reporting restriction is handled separately from the rest: We
1673 // set up a `SharedEmitter` the holds an open channel to the main thread.
1674 // When an error occurs on any thread, the shared emitter will send the
1675 // error message to the receiver main thread (`SharedEmitterMain`). The
1676 // main thread will periodically query this error message queue and emit
1677 // any error messages it has received. It might even abort compilation if
1678 // has received a fatal error. In this case we rely on all other threads
1679 // being torn down automatically with the main thread.
1680 // Since the main thread will often be busy doing codegen work, error
1681 // reporting will be somewhat delayed, since the message queue can only be
1682 // checked in between to work packages.
1684 // Work Processing Infrastructure
1685 // ==============================
1686 // The work processing infrastructure knows three major actors:
1688 // - the coordinator thread,
1689 // - the main thread, and
1690 // - LLVM worker threads
1692 // The coordinator thread is running a message loop. It instructs the main
1693 // thread about what work to do when, and it will spawn off LLVM worker
1694 // threads as open LLVM WorkItems become available.
1696 // The job of the main thread is to codegen CGUs into LLVM work package
1697 // (since the main thread is the only thread that can do this). The main
1698 // thread will block until it receives a message from the coordinator, upon
1699 // which it will codegen one CGU, send it to the coordinator and block
1700 // again. This way the coordinator can control what the main thread is
1703 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1704 // available, it will spawn off a new LLVM worker thread and let it process
1705 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1706 // it will just shut down, which also frees all resources associated with
1707 // the given LLVM module, and sends a message to the coordinator that the
1708 // has been completed.
1712 // The scheduler's goal is to minimize the time it takes to complete all
1713 // work there is, however, we also want to keep memory consumption low
1714 // if possible. These two goals are at odds with each other: If memory
1715 // consumption were not an issue, we could just let the main thread produce
1716 // LLVM WorkItems at full speed, assuring maximal utilization of
1717 // Tokens/LLVM worker threads. However, since codegen usual is faster
1718 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1719 // WorkItem potentially holds on to a substantial amount of memory.
1721 // So the actual goal is to always produce just enough LLVM WorkItems as
1722 // not to starve our LLVM worker threads. That means, once we have enough
1723 // WorkItems in our queue, we can block the main thread, so it does not
1724 // produce more until we need them.
1726 // Doing LLVM Work on the Main Thread
1727 // ----------------------------------
1728 // Since the main thread owns the compiler processes implicit `Token`, it is
1729 // wasteful to keep it blocked without doing any work. Therefore, what we do
1730 // in this case is: We spawn off an additional LLVM worker thread that helps
1731 // reduce the queue. The work it is doing corresponds to the implicit
1732 // `Token`. The coordinator will mark the main thread as being busy with
1733 // LLVM work. (The actual work happens on another OS thread but we just care
1734 // about `Tokens`, not actual threads).
1736 // When any LLVM worker thread finishes while the main thread is marked as
1737 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1738 // of the just finished thread to the LLVM worker thread that is working on
1739 // behalf of the main thread's implicit Token, thus freeing up the main
1740 // thread again. The coordinator can then again decide what the main thread
1741 // should do. This allows the coordinator to make decisions at more points
1744 // Striking a Balance between Throughput and Memory Consumption
1745 // ------------------------------------------------------------
1746 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1747 // memory consumption as low as possible, are in conflict with each other,
1748 // we have to find a trade off between them. Right now, the goal is to keep
1749 // all workers busy, which means that no worker should find the queue empty
1750 // when it is ready to start.
1751 // How do we do achieve this? Good question :) We actually never know how
1752 // many `Tokens` are potentially available so it's hard to say how much to
1753 // fill up the queue before switching the main thread to LLVM work. Also we
1754 // currently don't have a means to estimate how long a running LLVM worker
1755 // will still be busy with it's current WorkItem. However, we know the
1756 // maximal count of available Tokens that makes sense (=the number of CPU
1757 // cores), so we can take a conservative guess. The heuristic we use here
1758 // is implemented in the `queue_full_enough()` function.
1760 // Some Background on Jobservers
1761 // -----------------------------
1762 // It's worth also touching on the management of parallelism here. We don't
1763 // want to just spawn a thread per work item because while that's optimal
1764 // parallelism it may overload a system with too many threads or violate our
1765 // configuration for the maximum amount of cpu to use for this process. To
1766 // manage this we use the `jobserver` crate.
1768 // Job servers are an artifact of GNU make and are used to manage
1769 // parallelism between processes. A jobserver is a glorified IPC semaphore
1770 // basically. Whenever we want to run some work we acquire the semaphore,
1771 // and whenever we're done with that work we release the semaphore. In this
1772 // manner we can ensure that the maximum number of parallel workers is
1773 // capped at any one point in time.
1775 // LTO and the coordinator thread
1776 // ------------------------------
1778 // The final job the coordinator thread is responsible for is managing LTO
1779 // and how that works. When LTO is requested what we'll to is collect all
1780 // optimized LLVM modules into a local vector on the coordinator. Once all
1781 // modules have been codegened and optimized we hand this to the `lto`
1782 // module for further optimization. The `lto` module will return back a list
1783 // of more modules to work on, which the coordinator will continue to spawn
1786 // Each LLVM module is automatically sent back to the coordinator for LTO if
1787 // necessary. There's already optimizations in place to avoid sending work
1788 // back to the coordinator if LTO isn't requested.
1789 return thread::spawn(move || {
1790 // We pretend to be within the top-level LLVM time-passes task here:
1793 let max_workers = ::num_cpus::get();
1794 let mut worker_id_counter = 0;
1795 let mut free_worker_ids = Vec::new();
1796 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1797 if let Some(id) = free_worker_ids.pop() {
1800 let id = worker_id_counter;
1801 worker_id_counter += 1;
1806 // This is where we collect codegen units that have gone all the way
1807 // through codegen and LLVM.
1808 let mut compiled_modules = vec![];
1809 let mut compiled_metadata_module = None;
1810 let mut compiled_allocator_module = None;
1811 let mut needs_lto = Vec::new();
1812 let mut lto_import_only_modules = Vec::new();
1813 let mut started_lto = false;
1814 let mut codegen_aborted = false;
1816 // This flag tracks whether all items have gone through codegens
1817 let mut codegen_done = false;
1819 // This is the queue of LLVM work items that still need processing.
1820 let mut work_items = Vec::<(WorkItem, u64)>::new();
1822 // This are the Jobserver Tokens we currently hold. Does not include
1823 // the implicit Token the compiler process owns no matter what.
1824 let mut tokens = Vec::new();
1826 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1827 let mut running = 0;
1829 let mut llvm_start_time = None;
1831 // Run the message loop while there's still anything that needs message
1832 // processing. Note that as soon as codegen is aborted we simply want to
1833 // wait for all existing work to finish, so many of the conditions here
1834 // only apply if codegen hasn't been aborted as they represent pending
1836 while !codegen_done ||
1838 (!codegen_aborted && (
1839 work_items.len() > 0 ||
1840 needs_lto.len() > 0 ||
1841 lto_import_only_modules.len() > 0 ||
1842 main_thread_worker_state != MainThreadWorkerState::Idle
1846 // While there are still CGUs to be codegened, the coordinator has
1847 // to decide how to utilize the compiler processes implicit Token:
1848 // For codegenning more CGU or for running them through LLVM.
1850 if main_thread_worker_state == MainThreadWorkerState::Idle {
1851 if !queue_full_enough(work_items.len(), running, max_workers) {
1852 // The queue is not full enough, codegen more items:
1853 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1854 panic!("Could not send Message::CodegenItem to main thread")
1856 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1858 // The queue is full enough to not let the worker
1859 // threads starve. Use the implicit Token to do some
1861 let (item, _) = work_items.pop()
1862 .expect("queue empty - queue_full_enough() broken?");
1863 let cgcx = CodegenContext {
1864 worker: get_worker_id(&mut free_worker_ids),
1867 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1868 &mut llvm_start_time);
1869 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1870 spawn_work(cgcx, item);
1873 } else if codegen_aborted {
1874 // don't queue up any more work if codegen was aborted, we're
1875 // just waiting for our existing children to finish
1877 // If we've finished everything related to normal codegen
1878 // then it must be the case that we've got some LTO work to do.
1879 // Perform the serial work here of figuring out what we're
1880 // going to LTO and then push a bunch of work items onto our
1882 if work_items.len() == 0 &&
1884 main_thread_worker_state == MainThreadWorkerState::Idle {
1885 assert!(!started_lto);
1886 assert!(needs_lto.len() + lto_import_only_modules.len() > 0);
1888 let modules = mem::replace(&mut needs_lto, Vec::new());
1889 let import_only_modules =
1890 mem::replace(&mut lto_import_only_modules, Vec::new());
1891 for (work, cost) in generate_lto_work(&cgcx, modules, import_only_modules) {
1892 let insertion_index = work_items
1893 .binary_search_by_key(&cost, |&(_, cost)| cost)
1894 .unwrap_or_else(|e| e);
1895 work_items.insert(insertion_index, (work, cost));
1896 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1897 helper.request_token();
1902 // In this branch, we know that everything has been codegened,
1903 // so it's just a matter of determining whether the implicit
1904 // Token is free to use for LLVM work.
1905 match main_thread_worker_state {
1906 MainThreadWorkerState::Idle => {
1907 if let Some((item, _)) = work_items.pop() {
1908 let cgcx = CodegenContext {
1909 worker: get_worker_id(&mut free_worker_ids),
1912 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1913 &mut llvm_start_time);
1914 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1915 spawn_work(cgcx, item);
1917 // There is no unstarted work, so let the main thread
1918 // take over for a running worker. Otherwise the
1919 // implicit token would just go to waste.
1920 // We reduce the `running` counter by one. The
1921 // `tokens.truncate()` below will take care of
1922 // giving the Token back.
1923 debug_assert!(running > 0);
1925 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1928 MainThreadWorkerState::Codegenning => {
1929 bug!("codegen worker should not be codegenning after \
1930 codegen was already completed")
1932 MainThreadWorkerState::LLVMing => {
1933 // Already making good use of that token
1938 // Spin up what work we can, only doing this while we've got available
1939 // parallelism slots and work left to spawn.
1940 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1941 let (item, _) = work_items.pop().unwrap();
1943 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1944 &mut llvm_start_time);
1946 let cgcx = CodegenContext {
1947 worker: get_worker_id(&mut free_worker_ids),
1951 spawn_work(cgcx, item);
1955 // Relinquish accidentally acquired extra tokens
1956 tokens.truncate(running);
1958 let msg = coordinator_receive.recv().unwrap();
1959 match *msg.downcast::<Message>().ok().unwrap() {
1960 // Save the token locally and the next turn of the loop will use
1961 // this to spawn a new unit of work, or it may get dropped
1962 // immediately if we have no more work to spawn.
1963 Message::Token(token) => {
1968 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1969 // If the main thread token is used for LLVM work
1970 // at the moment, we turn that thread into a regular
1971 // LLVM worker thread, so the main thread is free
1972 // to react to codegen demand.
1973 main_thread_worker_state = MainThreadWorkerState::Idle;
1978 let msg = &format!("failed to acquire jobserver token: {}", e);
1979 shared_emitter.fatal(msg);
1980 // Exit the coordinator thread
1986 Message::CodegenDone { llvm_work_item, cost } => {
1987 // We keep the queue sorted by estimated processing cost,
1988 // so that more expensive items are processed earlier. This
1989 // is good for throughput as it gives the main thread more
1990 // time to fill up the queue and it avoids scheduling
1991 // expensive items to the end.
1992 // Note, however, that this is not ideal for memory
1993 // consumption, as LLVM module sizes are not evenly
1995 let insertion_index =
1996 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1997 let insertion_index = match insertion_index {
1998 Ok(idx) | Err(idx) => idx
2000 work_items.insert(insertion_index, (llvm_work_item, cost));
2002 if !cgcx.opts.debugging_opts.no_parallel_llvm {
2003 helper.request_token();
2005 assert!(!codegen_aborted);
2006 assert_eq!(main_thread_worker_state,
2007 MainThreadWorkerState::Codegenning);
2008 main_thread_worker_state = MainThreadWorkerState::Idle;
2011 Message::CodegenComplete => {
2012 codegen_done = true;
2013 assert!(!codegen_aborted);
2014 assert_eq!(main_thread_worker_state,
2015 MainThreadWorkerState::Codegenning);
2016 main_thread_worker_state = MainThreadWorkerState::Idle;
2019 // If codegen is aborted that means translation was aborted due
2020 // to some normal-ish compiler error. In this situation we want
2021 // to exit as soon as possible, but we want to make sure all
2022 // existing work has finished. Flag codegen as being done, and
2023 // then conditions above will ensure no more work is spawned but
2024 // we'll keep executing this loop until `running` hits 0.
2025 Message::CodegenAborted => {
2026 assert!(!codegen_aborted);
2027 codegen_done = true;
2028 codegen_aborted = true;
2029 assert_eq!(main_thread_worker_state,
2030 MainThreadWorkerState::Codegenning);
2033 // If a thread exits successfully then we drop a token associated
2034 // with that worker and update our `running` count. We may later
2035 // re-acquire a token to continue running more work. We may also not
2036 // actually drop a token here if the worker was running with an
2037 // "ephemeral token"
2039 // Note that if the thread failed that means it panicked, so we
2040 // abort immediately.
2041 Message::Done { result: Ok(compiled_module), worker_id } => {
2042 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2043 main_thread_worker_state = MainThreadWorkerState::Idle;
2048 free_worker_ids.push(worker_id);
2050 match compiled_module.kind {
2051 ModuleKind::Regular => {
2052 compiled_modules.push(compiled_module);
2054 ModuleKind::Metadata => {
2055 assert!(compiled_metadata_module.is_none());
2056 compiled_metadata_module = Some(compiled_module);
2058 ModuleKind::Allocator => {
2059 assert!(compiled_allocator_module.is_none());
2060 compiled_allocator_module = Some(compiled_module);
2064 Message::NeedsLTO { result, worker_id } => {
2065 assert!(!started_lto);
2066 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
2067 main_thread_worker_state = MainThreadWorkerState::Idle;
2071 free_worker_ids.push(worker_id);
2072 needs_lto.push(result);
2074 Message::AddImportOnlyModule { module_data, work_product } => {
2075 assert!(!started_lto);
2076 assert!(!codegen_done);
2077 assert_eq!(main_thread_worker_state,
2078 MainThreadWorkerState::Codegenning);
2079 lto_import_only_modules.push((module_data, work_product));
2080 main_thread_worker_state = MainThreadWorkerState::Idle;
2082 Message::Done { result: Err(()), worker_id: _ } => {
2083 bug!("worker thread panicked");
2085 Message::CodegenItem => {
2086 bug!("the coordinator should not receive codegen requests")
2091 if let Some(llvm_start_time) = llvm_start_time {
2092 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
2093 // This is the top-level timing for all of LLVM, set the time-depth
2096 print_time_passes_entry(cgcx.time_passes,
2101 // Regardless of what order these modules completed in, report them to
2102 // the backend in the same order every time to ensure that we're handing
2103 // out deterministic results.
2104 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
2106 let compiled_metadata_module = compiled_metadata_module
2107 .expect("Metadata module not compiled?");
2109 Ok(CompiledModules {
2110 modules: compiled_modules,
2111 metadata_module: compiled_metadata_module,
2112 allocator_module: compiled_allocator_module,
2116 // A heuristic that determines if we have enough LLVM WorkItems in the
2117 // queue so that the main thread can do LLVM work instead of codegen
2118 fn queue_full_enough(items_in_queue: usize,
2119 workers_running: usize,
2120 max_workers: usize) -> bool {
2122 items_in_queue > 0 &&
2123 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
2126 fn maybe_start_llvm_timer(config: &ModuleConfig,
2127 llvm_start_time: &mut Option<Instant>) {
2128 // We keep track of the -Ztime-passes output manually,
2129 // since the closure-based interface does not fit well here.
2130 if config.time_passes {
2131 if llvm_start_time.is_none() {
2132 *llvm_start_time = Some(Instant::now());
2138 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
2139 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
2140 time_graph::TimelineId(CODEGEN_WORKER_ID);
2141 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2142 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
2143 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
2144 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
2146 fn spawn_work(cgcx: CodegenContext<'static>, work: WorkItem) {
2147 let depth = time_depth();
2149 thread::spawn(move || {
2150 set_time_depth(depth);
2152 // Set up a destructor which will fire off a message that we're done as
2155 coordinator_send: Sender<Box<dyn Any + Send>>,
2156 result: Option<WorkItemResult>,
2159 impl Drop for Bomb {
2160 fn drop(&mut self) {
2161 let worker_id = self.worker_id;
2162 let msg = match self.result.take() {
2163 Some(WorkItemResult::Compiled(m)) => {
2164 Message::Done { result: Ok(m), worker_id }
2166 Some(WorkItemResult::NeedsLTO(m)) => {
2167 Message::NeedsLTO { result: m, worker_id }
2169 None => Message::Done { result: Err(()), worker_id }
2171 drop(self.coordinator_send.send(Box::new(msg)));
2175 let mut bomb = Bomb {
2176 coordinator_send: cgcx.coordinator_send.clone(),
2178 worker_id: cgcx.worker,
2181 // Execute the work itself, and if it finishes successfully then flag
2182 // ourselves as a success as well.
2184 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
2185 // as a diagnostic was already sent off to the main thread - just
2186 // surface that there was an error in this worker.
2188 let timeline = cgcx.time_graph.as_ref().map(|tg| {
2189 tg.start(time_graph::TimelineId(cgcx.worker),
2190 LLVM_WORK_PACKAGE_KIND,
2193 let mut timeline = timeline.unwrap_or(Timeline::noop());
2194 execute_work_item(&cgcx, work, &mut timeline).ok()
2199 pub fn run_assembler(cgcx: &CodegenContext, handler: &Handler, assembly: &Path, object: &Path) {
2200 let assembler = cgcx.assembler_cmd
2202 .expect("cgcx.assembler_cmd is missing?");
2204 let pname = &assembler.name;
2205 let mut cmd = assembler.cmd.clone();
2206 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
2207 debug!("{:?}", cmd);
2209 match cmd.output() {
2211 if !prog.status.success() {
2212 let mut note = prog.stderr.clone();
2213 note.extend_from_slice(&prog.stdout);
2215 handler.struct_err(&format!("linking with `{}` failed: {}",
2218 .note(&format!("{:?}", &cmd))
2219 .note(str::from_utf8(¬e[..]).unwrap())
2221 handler.abort_if_errors();
2225 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
2226 handler.abort_if_errors();
2231 pub unsafe fn with_llvm_pmb(llmod: &llvm::Module,
2232 config: &ModuleConfig,
2233 opt_level: llvm::CodeGenOptLevel,
2234 prepare_for_thin_lto: bool,
2235 f: &mut dyn FnMut(&llvm::PassManagerBuilder)) {
2238 // Create the PassManagerBuilder for LLVM. We configure it with
2239 // reasonable defaults and prepare it to actually populate the pass
2241 let builder = llvm::LLVMPassManagerBuilderCreate();
2242 let opt_size = config.opt_size.unwrap_or(llvm::CodeGenOptSizeNone);
2243 let inline_threshold = config.inline_threshold;
2245 let pgo_gen_path = config.pgo_gen.as_ref().map(|s| {
2246 let s = if s.is_empty() { "default_%m.profraw" } else { s };
2247 CString::new(s.as_bytes()).unwrap()
2250 let pgo_use_path = if config.pgo_use.is_empty() {
2253 Some(CString::new(config.pgo_use.as_bytes()).unwrap())
2256 llvm::LLVMRustConfigurePassManagerBuilder(
2259 config.merge_functions,
2260 config.vectorize_slp,
2261 config.vectorize_loop,
2262 prepare_for_thin_lto,
2263 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2264 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
2267 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
2269 if opt_size != llvm::CodeGenOptSizeNone {
2270 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
2273 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
2275 // Here we match what clang does (kinda). For O0 we only inline
2276 // always-inline functions (but don't add lifetime intrinsics), at O1 we
2277 // inline with lifetime intrinsics, and O2+ we add an inliner with a
2278 // thresholds copied from clang.
2279 match (opt_level, opt_size, inline_threshold) {
2281 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
2283 (llvm::CodeGenOptLevel::Aggressive, ..) => {
2284 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
2286 (_, llvm::CodeGenOptSizeDefault, _) => {
2287 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
2289 (_, llvm::CodeGenOptSizeAggressive, _) => {
2290 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
2292 (llvm::CodeGenOptLevel::None, ..) => {
2293 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
2295 (llvm::CodeGenOptLevel::Less, ..) => {
2296 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
2298 (llvm::CodeGenOptLevel::Default, ..) => {
2299 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
2301 (llvm::CodeGenOptLevel::Other, ..) => {
2302 bug!("CodeGenOptLevel::Other selected")
2307 llvm::LLVMPassManagerBuilderDispose(builder);
2311 enum SharedEmitterMessage {
2312 Diagnostic(Diagnostic),
2313 InlineAsmError(u32, String),
2319 pub struct SharedEmitter {
2320 sender: Sender<SharedEmitterMessage>,
2323 pub struct SharedEmitterMain {
2324 receiver: Receiver<SharedEmitterMessage>,
2327 impl SharedEmitter {
2328 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
2329 let (sender, receiver) = channel();
2331 (SharedEmitter { sender }, SharedEmitterMain { receiver })
2334 fn inline_asm_error(&self, cookie: u32, msg: String) {
2335 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
2338 fn fatal(&self, msg: &str) {
2339 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2343 impl Emitter for SharedEmitter {
2344 fn emit(&mut self, db: &DiagnosticBuilder) {
2345 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2347 code: db.code.clone(),
2350 for child in &db.children {
2351 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2352 msg: child.message(),
2357 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
2361 impl SharedEmitterMain {
2362 pub fn check(&self, sess: &Session, blocking: bool) {
2364 let message = if blocking {
2365 match self.receiver.recv() {
2366 Ok(message) => Ok(message),
2370 match self.receiver.try_recv() {
2371 Ok(message) => Ok(message),
2377 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2378 let handler = sess.diagnostic();
2381 handler.emit_with_code(&MultiSpan::new(),
2387 handler.emit(&MultiSpan::new(),
2393 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
2394 match Mark::from_u32(cookie).expn_info() {
2395 Some(ei) => sess.span_err(ei.call_site, &msg),
2396 None => sess.err(&msg),
2399 Ok(SharedEmitterMessage::AbortIfErrors) => {
2400 sess.abort_if_errors();
2402 Ok(SharedEmitterMessage::Fatal(msg)) => {
2414 pub struct OngoingCodegen {
2417 metadata: EncodedMetadata,
2418 windows_subsystem: Option<String>,
2419 linker_info: LinkerInfo,
2420 crate_info: CrateInfo,
2421 time_graph: Option<TimeGraph>,
2422 coordinator_send: Sender<Box<dyn Any + Send>>,
2423 codegen_worker_receive: Receiver<Message>,
2424 shared_emitter_main: SharedEmitterMain,
2425 future: thread::JoinHandle<Result<CompiledModules, ()>>,
2426 output_filenames: Arc<OutputFilenames>,
2429 impl OngoingCodegen {
2433 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
2434 self.shared_emitter_main.check(sess, true);
2435 let compiled_modules = match self.future.join() {
2436 Ok(Ok(compiled_modules)) => compiled_modules,
2438 sess.abort_if_errors();
2439 panic!("expected abort due to worker thread errors")
2442 bug!("panic during codegen/LLVM phase");
2446 sess.cgu_reuse_tracker.check_expected_reuse(sess);
2448 sess.abort_if_errors();
2450 if let Some(time_graph) = self.time_graph {
2451 time_graph.dump(&format!("{}-timings", self.crate_name));
2455 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
2457 produce_final_output_artifacts(sess,
2459 &self.output_filenames);
2461 // FIXME: time_llvm_passes support - does this use a global context or
2463 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
2464 unsafe { llvm::LLVMRustPrintPassTimings(); }
2468 crate_name: self.crate_name,
2469 crate_hash: self.crate_hash,
2470 metadata: self.metadata,
2471 windows_subsystem: self.windows_subsystem,
2472 linker_info: self.linker_info,
2473 crate_info: self.crate_info,
2475 modules: compiled_modules.modules,
2476 allocator_module: compiled_modules.allocator_module,
2477 metadata_module: compiled_modules.metadata_module,
2481 pub(crate) fn submit_pre_codegened_module_to_llvm(&self,
2483 module: ModuleCodegen) {
2484 self.wait_for_signal_to_codegen_item();
2485 self.check_for_errors(tcx.sess);
2487 // These are generally cheap and won't through off scheduling.
2489 submit_codegened_module_to_llvm(tcx, module, cost);
2492 pub fn codegen_finished(&self, tcx: TyCtxt) {
2493 self.wait_for_signal_to_codegen_item();
2494 self.check_for_errors(tcx.sess);
2495 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete)));
2498 /// Consume this context indicating that codegen was entirely aborted, and
2499 /// we need to exit as quickly as possible.
2501 /// This method blocks the current thread until all worker threads have
2502 /// finished, and all worker threads should have exited or be real close to
2503 /// exiting at this point.
2504 pub fn codegen_aborted(self) {
2505 // Signal to the coordinator it should spawn no more work and start
2507 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted)));
2508 drop(self.future.join());
2511 pub fn check_for_errors(&self, sess: &Session) {
2512 self.shared_emitter_main.check(sess, false);
2515 pub fn wait_for_signal_to_codegen_item(&self) {
2516 match self.codegen_worker_receive.recv() {
2517 Ok(Message::CodegenItem) => {
2520 Ok(_) => panic!("unexpected message"),
2522 // One of the LLVM threads must have panicked, fall through so
2523 // error handling can be reached.
2529 // impl Drop for OngoingCodegen {
2530 // fn drop(&mut self) {
2534 pub(crate) fn submit_codegened_module_to_llvm(tcx: TyCtxt,
2535 module: ModuleCodegen,
2537 let llvm_work_item = WorkItem::Optimize(module);
2538 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2544 pub(crate) fn submit_post_lto_module_to_llvm(tcx: TyCtxt,
2545 module: CachedModuleCodegen) {
2546 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2547 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone {
2553 pub(crate) fn submit_pre_lto_module_to_llvm(tcx: TyCtxt,
2554 module: CachedModuleCodegen) {
2555 let filename = pre_lto_bitcode_filename(&module.name);
2556 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2557 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
2558 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
2562 memmap::Mmap::map(&file).unwrap_or_else(|e| {
2563 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2567 // Schedule the module to be loaded
2568 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule {
2569 module_data: SerializedModule::FromUncompressedFile(mmap),
2570 work_product: module.source,
2574 pub(super) fn pre_lto_bitcode_filename(module_name: &str) -> String {
2575 format!("{}.{}", module_name, PRE_THIN_LTO_BC_EXT)
2578 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
2579 // This should never be true (because it's not supported). If it is true,
2580 // something is wrong with commandline arg validation.
2581 assert!(!(tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
2582 tcx.sess.target.target.options.is_like_msvc &&
2583 tcx.sess.opts.cg.prefer_dynamic));
2585 tcx.sess.target.target.options.is_like_msvc &&
2586 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
2587 // ThinLTO can't handle this workaround in all cases, so we don't
2588 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2589 // dynamic linking when cross-language LTO is enabled.
2590 !tcx.sess.opts.debugging_opts.cross_lang_lto.enabled()
2593 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2594 // This is required to satisfy `dllimport` references to static data in .rlibs
2595 // when using MSVC linker. We do this only for data, as linker can fix up
2596 // code references on its own.
2597 // See #26591, #27438
2598 fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
2599 if !cgcx.msvc_imps_needed {
2602 // The x86 ABI seems to require that leading underscores are added to symbol
2603 // names, so we need an extra underscore on 32-bit. There's also a leading
2604 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2605 // underscores added in front).
2606 let prefix = if cgcx.target_pointer_width == "32" {
2612 let i8p_ty = Type::i8p_llcx(llcx);
2613 let globals = base::iter_globals(llmod)
2615 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
2616 llvm::LLVMIsDeclaration(val) == 0
2619 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2620 let mut imp_name = prefix.as_bytes().to_vec();
2621 imp_name.extend(name.to_bytes());
2622 let imp_name = CString::new(imp_name).unwrap();
2625 .collect::<Vec<_>>();
2626 for (imp_name, val) in globals {
2627 let imp = llvm::LLVMAddGlobal(llmod,
2629 imp_name.as_ptr() as *const _);
2630 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
2631 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);