1 use crate::back::lto::ThinBuffer;
2 use crate::back::profiling::{
3 selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler,
8 use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
10 use crate::type_::Type;
11 use crate::LlvmCodegenBackend;
12 use crate::ModuleLlvm;
13 use rustc_codegen_ssa::back::link::ensure_removed;
14 use rustc_codegen_ssa::back::write::{
15 BitcodeSection, CodegenContext, EmitObj, ModuleConfig, TargetMachineFactoryConfig,
16 TargetMachineFactoryFn,
18 use rustc_codegen_ssa::traits::*;
19 use rustc_codegen_ssa::{CompiledModule, ModuleCodegen};
20 use rustc_data_structures::small_c_str::SmallCStr;
21 use rustc_errors::{FatalError, Handler, Level};
22 use rustc_fs_util::{link_or_copy, path_to_c_string};
23 use rustc_hir::def_id::LOCAL_CRATE;
24 use rustc_middle::bug;
25 use rustc_middle::ty::TyCtxt;
26 use rustc_session::config::{self, Lto, OutputType, Passes, SwitchWithOptPath};
27 use rustc_session::Session;
28 use rustc_span::symbol::sym;
29 use rustc_span::InnerSpan;
30 use rustc_target::spec::{CodeModel, RelocModel, SanitizerSet, SplitDebuginfo};
33 use libc::{c_char, c_int, c_uint, c_void, size_t};
34 use std::ffi::CString;
36 use std::io::{self, Write};
37 use std::path::{Path, PathBuf};
42 pub fn llvm_err(handler: &rustc_errors::Handler, msg: &str) -> FatalError {
43 match llvm::last_error() {
44 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
45 None => handler.fatal(&msg),
49 pub fn write_output_file(
50 handler: &rustc_errors::Handler,
51 target: &'ll llvm::TargetMachine,
52 pm: &llvm::PassManager<'ll>,
55 dwo_output: Option<&Path>,
56 file_type: llvm::FileType,
57 ) -> Result<(), FatalError> {
59 let output_c = path_to_c_string(output);
60 let result = if let Some(dwo_output) = dwo_output {
61 let dwo_output_c = path_to_c_string(dwo_output);
62 llvm::LLVMRustWriteOutputFile(
67 dwo_output_c.as_ptr(),
71 llvm::LLVMRustWriteOutputFile(
80 result.into_result().map_err(|()| {
81 let msg = format!("could not write output to {}", output.display());
82 llvm_err(handler, &msg)
87 pub fn create_informational_target_machine(sess: &Session) -> &'static mut llvm::TargetMachine {
88 let config = TargetMachineFactoryConfig { split_dwarf_file: None };
89 target_machine_factory(sess, config::OptLevel::No)(config)
90 .unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise())
93 pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> &'static mut llvm::TargetMachine {
94 let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
95 tcx.output_filenames(LOCAL_CRATE)
96 .split_dwarf_path(tcx.sess.split_debuginfo(), Some(mod_name))
100 let config = TargetMachineFactoryConfig { split_dwarf_file };
101 target_machine_factory(&tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE))(config)
102 .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise())
105 pub fn to_llvm_opt_settings(
106 cfg: config::OptLevel,
107 ) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
108 use self::config::OptLevel::*;
110 No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
111 Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
112 Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
113 Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
114 Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
115 SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
119 fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
120 use config::OptLevel::*;
122 No => llvm::PassBuilderOptLevel::O0,
123 Less => llvm::PassBuilderOptLevel::O1,
124 Default => llvm::PassBuilderOptLevel::O2,
125 Aggressive => llvm::PassBuilderOptLevel::O3,
126 Size => llvm::PassBuilderOptLevel::Os,
127 SizeMin => llvm::PassBuilderOptLevel::Oz,
131 fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
132 match relocation_model {
133 RelocModel::Static => llvm::RelocModel::Static,
134 RelocModel::Pic => llvm::RelocModel::PIC,
135 RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
136 RelocModel::Ropi => llvm::RelocModel::ROPI,
137 RelocModel::Rwpi => llvm::RelocModel::RWPI,
138 RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
142 pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
144 Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
145 Some(CodeModel::Small) => llvm::CodeModel::Small,
146 Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
147 Some(CodeModel::Medium) => llvm::CodeModel::Medium,
148 Some(CodeModel::Large) => llvm::CodeModel::Large,
149 None => llvm::CodeModel::None,
153 pub fn target_machine_factory(
155 optlvl: config::OptLevel,
156 ) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
157 let reloc_model = to_llvm_relocation_model(sess.relocation_model());
159 let (opt_level, _) = to_llvm_opt_settings(optlvl);
160 let use_softfp = sess.opts.cg.soft_float;
162 let ffunction_sections =
163 sess.opts.debugging_opts.function_sections.unwrap_or(sess.target.function_sections);
164 let fdata_sections = ffunction_sections;
166 let code_model = to_llvm_code_model(sess.code_model());
168 let mut singlethread = sess.target.singlethread;
170 // On the wasm target once the `atomics` feature is enabled that means that
171 // we're no longer single-threaded, or otherwise we don't want LLVM to
172 // lower atomic operations to single-threaded operations.
174 && sess.target.llvm_target.contains("wasm32")
175 && sess.target_features.contains(&sym::atomics)
177 singlethread = false;
180 let triple = SmallCStr::new(&sess.target.llvm_target);
181 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
182 let features = llvm_util::llvm_global_features(sess).join(",");
183 let features = CString::new(features).unwrap();
184 let abi = SmallCStr::new(&sess.target.llvm_abiname);
185 let trap_unreachable =
186 sess.opts.debugging_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
187 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
189 let asm_comments = sess.asm_comments();
190 let relax_elf_relocations =
191 sess.opts.debugging_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
194 !sess.opts.debugging_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
196 Arc::new(move |config: TargetMachineFactoryConfig| {
197 let split_dwarf_file = config.split_dwarf_file.unwrap_or_default();
198 let split_dwarf_file = CString::new(split_dwarf_file.to_str().unwrap()).unwrap();
201 llvm::LLVMRustCreateTargetMachine(
215 emit_stack_size_section,
216 relax_elf_relocations,
218 split_dwarf_file.as_ptr(),
223 format!("Could not create LLVM TargetMachine for triple: {}", triple.to_str().unwrap())
228 pub(crate) fn save_temp_bitcode(
229 cgcx: &CodegenContext<LlvmCodegenBackend>,
230 module: &ModuleCodegen<ModuleLlvm>,
233 if !cgcx.save_temps {
237 let ext = format!("{}.bc", name);
238 let cgu = Some(&module.name[..]);
239 let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
240 let cstr = path_to_c_string(&path);
241 let llmod = module.module_llvm.llmod();
242 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
246 pub struct DiagnosticHandlers<'a> {
247 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
248 llcx: &'a llvm::Context,
251 impl<'a> DiagnosticHandlers<'a> {
253 cgcx: &'a CodegenContext<LlvmCodegenBackend>,
254 handler: &'a Handler,
255 llcx: &'a llvm::Context,
257 let data = Box::into_raw(Box::new((cgcx, handler)));
259 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data.cast());
260 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data.cast());
262 DiagnosticHandlers { data, llcx }
266 impl<'a> Drop for DiagnosticHandlers<'a> {
268 use std::ptr::null_mut;
270 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
271 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
272 drop(Box::from_raw(self.data));
277 fn report_inline_asm(
278 cgcx: &CodegenContext<LlvmCodegenBackend>,
280 level: llvm::DiagnosticLevel,
282 source: Option<(String, Vec<InnerSpan>)>,
284 // In LTO build we may get srcloc values from other crates which are invalid
285 // since they use a different source map. To be safe we just suppress these
287 if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
290 let level = match level {
291 llvm::DiagnosticLevel::Error => Level::Error,
292 llvm::DiagnosticLevel::Warning => Level::Warning,
293 llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
295 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg, level, source);
298 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, user: *const c_void, cookie: c_uint) {
302 let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
304 // Recover the post-substitution assembly code from LLVM for better
306 let mut have_source = false;
307 let mut buffer = String::new();
308 let mut level = llvm::DiagnosticLevel::Error;
310 let mut ranges = [0; 8];
311 let mut num_ranges = ranges.len() / 2;
312 let msg = llvm::build_string(|msg| {
313 buffer = llvm::build_string(|buffer| {
314 have_source = llvm::LLVMRustUnpackSMDiagnostic(
324 .expect("non-UTF8 inline asm");
326 .expect("non-UTF8 SMDiagnostic");
328 let source = have_source.then(|| {
329 let mut spans = vec![InnerSpan::new(loc as usize, loc as usize)];
330 for i in 0..num_ranges {
331 spans.push(InnerSpan::new(ranges[i * 2] as usize, ranges[i * 2 + 1] as usize));
336 report_inline_asm(cgcx, msg, level, cookie, source);
339 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
343 let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
345 match llvm::diagnostic::Diagnostic::unpack(info) {
346 llvm::diagnostic::InlineAsm(inline) => {
349 llvm::twine_to_string(inline.message),
356 llvm::diagnostic::Optimization(opt) => {
357 let enabled = match cgcx.remark {
359 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
363 diag_handler.note_without_error(&format!(
364 "optimization {} for {} at {}:{}:{}: {}",
374 llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
375 let msg = llvm::build_string(|s| {
376 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
378 .expect("non-UTF8 diagnostic");
379 diag_handler.warn(&msg);
381 llvm::diagnostic::Unsupported(diagnostic_ref) => {
382 let msg = llvm::build_string(|s| {
383 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
385 .expect("non-UTF8 diagnostic");
386 diag_handler.err(&msg);
388 llvm::diagnostic::UnknownDiagnostic(..) => {}
392 fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
393 match config.pgo_gen {
394 SwitchWithOptPath::Enabled(ref opt_dir_path) => {
395 let path = if let Some(dir_path) = opt_dir_path {
396 dir_path.join("default_%m.profraw")
398 PathBuf::from("default_%m.profraw")
401 Some(CString::new(format!("{}", path.display())).unwrap())
403 SwitchWithOptPath::Disabled => None,
407 fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
411 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
414 pub(crate) fn should_use_new_llvm_pass_manager(config: &ModuleConfig) -> bool {
415 // The new pass manager is disabled by default.
416 config.new_llvm_pass_manager
419 pub(crate) unsafe fn optimize_with_new_llvm_pass_manager(
420 cgcx: &CodegenContext<LlvmCodegenBackend>,
421 module: &ModuleCodegen<ModuleLlvm>,
422 config: &ModuleConfig,
423 opt_level: config::OptLevel,
424 opt_stage: llvm::OptStage,
427 opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
428 let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
429 let pgo_gen_path = get_pgo_gen_path(config);
430 let pgo_use_path = get_pgo_use_path(config);
431 let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
432 // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
433 let sanitizer_options = if !is_lto {
434 Some(llvm::SanitizerOptions {
435 sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
436 sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
437 sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
438 sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
439 sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
440 sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
441 sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
442 sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
448 let llvm_selfprofiler = if cgcx.prof.llvm_recording_enabled() {
449 let mut llvm_profiler = LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap());
450 &mut llvm_profiler as *mut _ as *mut c_void
455 // FIXME: NewPM doesn't provide a facility to pass custom InlineParams.
456 // We would have to add upstream support for this first, before we can support
457 // config.inline_threshold and our more aggressive default thresholds.
458 // FIXME: NewPM uses an different and more explicit way to textually represent
459 // pass pipelines. It would probably make sense to expose this, but it would
460 // require a different format than the current -C passes.
461 llvm::LLVMRustOptimizeWithNewPassManager(
462 module.module_llvm.llmod(),
463 &*module.module_llvm.tm,
464 to_pass_builder_opt_level(opt_level),
466 config.no_prepopulate_passes,
467 config.verify_llvm_ir,
469 config.merge_functions,
471 config.vectorize_slp,
472 config.vectorize_loop,
474 config.emit_lifetime_markers,
475 sanitizer_options.as_ref(),
476 pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
477 pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
479 selfprofile_before_pass_callback,
480 selfprofile_after_pass_callback,
484 // Unsafe due to LLVM calls.
485 pub(crate) unsafe fn optimize(
486 cgcx: &CodegenContext<LlvmCodegenBackend>,
487 diag_handler: &Handler,
488 module: &ModuleCodegen<ModuleLlvm>,
489 config: &ModuleConfig,
491 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &module.name[..]);
493 let llmod = module.module_llvm.llmod();
494 let llcx = &*module.module_llvm.llcx;
495 let tm = &*module.module_llvm.tm;
496 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
498 let module_name = module.name.clone();
499 let module_name = Some(&module_name[..]);
501 if config.emit_no_opt_bc {
502 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
503 let out = path_to_c_string(&out);
504 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
507 if let Some(opt_level) = config.opt_level {
508 if should_use_new_llvm_pass_manager(config) {
509 let opt_stage = match cgcx.lto {
510 Lto::Fat => llvm::OptStage::PreLinkFatLTO,
511 Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
512 _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
513 _ => llvm::OptStage::PreLinkNoLTO,
515 optimize_with_new_llvm_pass_manager(cgcx, module, config, opt_level, opt_stage);
519 if cgcx.prof.llvm_recording_enabled() {
521 .warn("`-Z self-profile-events = llvm` requires `-Z new-llvm-pass-manager`");
524 // Create the two optimizing pass managers. These mirror what clang
525 // does, and are by populated by LLVM's default PassManagerBuilder.
526 // Each manager has a different set of passes, but they also share
527 // some common passes.
528 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
529 let mpm = llvm::LLVMCreatePassManager();
532 let find_pass = |pass_name: &str| {
533 let pass_name = SmallCStr::new(pass_name);
534 llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr())
537 if config.verify_llvm_ir {
538 // Verification should run as the very first pass.
539 llvm::LLVMRustAddPass(fpm, find_pass("verify").unwrap());
542 let mut extra_passes = Vec::new();
543 let mut have_name_anon_globals_pass = false;
545 for pass_name in &config.passes {
546 if pass_name == "lint" {
547 // Linting should also be performed early, directly on the generated IR.
548 llvm::LLVMRustAddPass(fpm, find_pass("lint").unwrap());
551 if pass_name == "insert-gcov-profiling" || pass_name == "instrprof" {
552 // Instrumentation must be inserted before optimization,
553 // otherwise LLVM may optimize some functions away which
556 // This mirrors what Clang does in lib/CodeGen/BackendUtil.cpp.
557 llvm::LLVMRustAddPass(mpm, find_pass(pass_name).unwrap());
561 if let Some(pass) = find_pass(pass_name) {
562 extra_passes.push(pass);
564 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass_name));
567 if pass_name == "name-anon-globals" {
568 have_name_anon_globals_pass = true;
572 add_sanitizer_passes(config, &mut extra_passes);
574 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
575 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
576 // we'll get errors in LLVM.
577 let using_thin_buffers = config.bitcode_needed();
578 if !config.no_prepopulate_passes {
579 llvm::LLVMAddAnalysisPasses(tm, fpm);
580 llvm::LLVMAddAnalysisPasses(tm, mpm);
581 let opt_level = to_llvm_opt_settings(opt_level).0;
582 let prepare_for_thin_lto = cgcx.lto == Lto::Thin
583 || cgcx.lto == Lto::ThinLocal
584 || (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
585 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
586 llvm::LLVMRustAddLastExtensionPasses(
588 extra_passes.as_ptr(),
589 extra_passes.len() as size_t,
591 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
592 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
595 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
596 if using_thin_buffers && !prepare_for_thin_lto {
597 llvm::LLVMRustAddPass(mpm, find_pass("name-anon-globals").unwrap());
598 have_name_anon_globals_pass = true;
601 // If we don't use the standard pipeline, directly populate the MPM
602 // with the extra passes.
603 for pass in extra_passes {
604 llvm::LLVMRustAddPass(mpm, pass);
608 if using_thin_buffers && !have_name_anon_globals_pass {
609 // As described above, this will probably cause an error in LLVM
610 if config.no_prepopulate_passes {
612 "The current compilation is going to use thin LTO buffers \
613 without running LLVM's NameAnonGlobals pass. \
614 This will likely cause errors in LLVM. Consider adding \
615 -C passes=name-anon-globals to the compiler command line.",
619 "We are using thin LTO buffers without running the NameAnonGlobals pass. \
620 This will likely cause errors in LLVM and should never happen."
626 diag_handler.abort_if_errors();
628 // Finally, run the actual optimization passes
630 let _timer = cgcx.prof.extra_verbose_generic_activity(
631 "LLVM_module_optimize_function_passes",
634 llvm::LLVMRustRunFunctionPassManager(fpm, llmod);
637 let _timer = cgcx.prof.extra_verbose_generic_activity(
638 "LLVM_module_optimize_module_passes",
641 llvm::LLVMRunPassManager(mpm, llmod);
644 // Deallocate managers that we're now done with
645 llvm::LLVMDisposePassManager(fpm);
646 llvm::LLVMDisposePassManager(mpm);
650 unsafe fn add_sanitizer_passes(config: &ModuleConfig, passes: &mut Vec<&'static mut llvm::Pass>) {
651 if config.sanitizer.contains(SanitizerSet::ADDRESS) {
652 let recover = config.sanitizer_recover.contains(SanitizerSet::ADDRESS);
653 passes.push(llvm::LLVMRustCreateAddressSanitizerFunctionPass(recover));
654 passes.push(llvm::LLVMRustCreateModuleAddressSanitizerPass(recover));
656 if config.sanitizer.contains(SanitizerSet::MEMORY) {
657 let track_origins = config.sanitizer_memory_track_origins as c_int;
658 let recover = config.sanitizer_recover.contains(SanitizerSet::MEMORY);
659 passes.push(llvm::LLVMRustCreateMemorySanitizerPass(track_origins, recover));
661 if config.sanitizer.contains(SanitizerSet::THREAD) {
662 passes.push(llvm::LLVMRustCreateThreadSanitizerPass());
664 if config.sanitizer.contains(SanitizerSet::HWADDRESS) {
665 let recover = config.sanitizer_recover.contains(SanitizerSet::HWADDRESS);
666 passes.push(llvm::LLVMRustCreateHWAddressSanitizerPass(recover));
671 cgcx: &CodegenContext<LlvmCodegenBackend>,
672 diag_handler: &Handler,
673 mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
674 ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
675 use super::lto::{Linker, ModuleBuffer};
676 // Sort the modules by name to ensure to ensure deterministic behavior.
677 modules.sort_by(|a, b| a.name.cmp(&b.name));
678 let (first, elements) =
679 modules.split_first().expect("Bug! modules must contain at least one module.");
681 let mut linker = Linker::new(first.module_llvm.llmod());
682 for module in elements {
684 cgcx.prof.generic_activity_with_arg("LLVM_link_module", format!("{:?}", module.name));
685 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
686 linker.add(&buffer.data()).map_err(|()| {
687 let msg = format!("failed to serialize module {:?}", module.name);
688 llvm_err(&diag_handler, &msg)
692 Ok(modules.remove(0))
695 pub(crate) unsafe fn codegen(
696 cgcx: &CodegenContext<LlvmCodegenBackend>,
697 diag_handler: &Handler,
698 module: ModuleCodegen<ModuleLlvm>,
699 config: &ModuleConfig,
700 ) -> Result<CompiledModule, FatalError> {
701 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &module.name[..]);
703 let llmod = module.module_llvm.llmod();
704 let llcx = &*module.module_llvm.llcx;
705 let tm = &*module.module_llvm.tm;
706 let module_name = module.name.clone();
707 let module_name = Some(&module_name[..]);
708 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
710 if cgcx.msvc_imps_needed {
711 create_msvc_imps(cgcx, llcx, llmod);
714 // A codegen-specific pass manager is used to generate object
715 // files for an LLVM module.
717 // Apparently each of these pass managers is a one-shot kind of
718 // thing, so we create a new one for each type of output. The
719 // pass manager passed to the closure should be ensured to not
720 // escape the closure itself, and the manager should only be
722 unsafe fn with_codegen<'ll, F, R>(
723 tm: &'ll llvm::TargetMachine,
724 llmod: &'ll llvm::Module,
729 F: FnOnce(&'ll mut PassManager<'ll>) -> R,
731 let cpm = llvm::LLVMCreatePassManager();
732 llvm::LLVMAddAnalysisPasses(tm, cpm);
733 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
737 // Two things to note:
738 // - If object files are just LLVM bitcode we write bitcode, copy it to
739 // the .o file, and delete the bitcode if it wasn't otherwise
741 // - If we don't have the integrated assembler then we need to emit
742 // asm from LLVM and use `gcc` to create the object file.
744 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
745 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
747 if config.bitcode_needed() {
750 .generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &module.name[..]);
751 let thin = ThinBuffer::new(llmod);
752 let data = thin.data();
754 if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
755 let _timer = cgcx.prof.generic_activity_with_arg(
756 "LLVM_module_codegen_emit_bitcode",
759 if let Err(e) = fs::write(&bc_out, data) {
760 let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
761 diag_handler.err(&msg);
765 if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
766 let _timer = cgcx.prof.generic_activity_with_arg(
767 "LLVM_module_codegen_embed_bitcode",
770 embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
777 .generic_activity_with_arg("LLVM_module_codegen_emit_ir", &module.name[..]);
778 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
779 let out_c = path_to_c_string(&out);
781 extern "C" fn demangle_callback(
782 input_ptr: *const c_char,
784 output_ptr: *mut c_char,
788 unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
790 let input = match str::from_utf8(input) {
795 let output = unsafe {
796 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
798 let mut cursor = io::Cursor::new(output);
800 let demangled = match rustc_demangle::try_demangle(input) {
805 if write!(cursor, "{:#}", demangled).is_err() {
806 // Possible only if provided buffer is not big enough
810 cursor.position() as size_t
813 let result = llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback);
814 result.into_result().map_err(|()| {
815 let msg = format!("failed to write LLVM IR to {}", out.display());
816 llvm_err(diag_handler, &msg)
823 .generic_activity_with_arg("LLVM_module_codegen_emit_asm", &module.name[..]);
824 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
826 // We can't use the same module for asm and object code output,
827 // because that triggers various errors like invalid IR or broken
828 // binaries. So we must clone the module to produce the asm output
829 // if we are also producing object code.
830 let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
831 llvm::LLVMCloneModule(llmod)
835 with_codegen(tm, llmod, config.no_builtins, |cpm| {
843 llvm::FileType::AssemblyFile,
848 match config.emit_obj {
849 EmitObj::ObjectCode(_) => {
852 .generic_activity_with_arg("LLVM_module_codegen_emit_obj", &module.name[..]);
854 let dwo_out = cgcx.output_filenames.temp_path_dwo(module_name);
855 let dwo_out = match cgcx.split_debuginfo {
856 // Don't change how DWARF is emitted in single mode (or when disabled).
857 SplitDebuginfo::Off | SplitDebuginfo::Packed => None,
858 // Emit (a subset of the) DWARF into a separate file in split mode.
859 SplitDebuginfo::Unpacked => {
860 if cgcx.target_can_use_split_dwarf {
861 Some(dwo_out.as_path())
868 with_codegen(tm, llmod, config.no_builtins, |cpm| {
876 llvm::FileType::ObjectFile,
881 EmitObj::Bitcode => {
882 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
883 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
884 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
888 debug!("removing_bitcode {:?}", bc_out);
889 ensure_removed(diag_handler, &bc_out);
899 Ok(module.into_compiled_module(
900 config.emit_obj != EmitObj::None,
901 cgcx.target_can_use_split_dwarf && cgcx.split_debuginfo == SplitDebuginfo::Unpacked,
903 &cgcx.output_filenames,
907 /// Embed the bitcode of an LLVM module in the LLVM module itself.
909 /// This is done primarily for iOS where it appears to be standard to compile C
910 /// code at least with `-fembed-bitcode` which creates two sections in the
913 /// * __LLVM,__bitcode
914 /// * __LLVM,__cmdline
916 /// It appears *both* of these sections are necessary to get the linker to
917 /// recognize what's going on. A suitable cmdline value is taken from the
920 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
921 /// embed an empty section.
923 /// Basically all of this is us attempting to follow in the footsteps of clang
924 /// on iOS. See #35968 for lots more info.
925 unsafe fn embed_bitcode(
926 cgcx: &CodegenContext<LlvmCodegenBackend>,
927 llcx: &llvm::Context,
928 llmod: &llvm::Module,
932 let llconst = common::bytes_in_context(llcx, bitcode);
933 let llglobal = llvm::LLVMAddGlobal(
935 common::val_ty(llconst),
936 "rustc.embedded.module\0".as_ptr().cast(),
938 llvm::LLVMSetInitializer(llglobal, llconst);
940 let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
941 || cgcx.opts.target_triple.triple().contains("-darwin")
942 || cgcx.opts.target_triple.triple().contains("-tvos");
944 let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" };
945 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
946 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
947 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
949 let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
950 let llglobal = llvm::LLVMAddGlobal(
952 common::val_ty(llconst),
953 "rustc.embedded.cmdline\0".as_ptr().cast(),
955 llvm::LLVMSetInitializer(llglobal, llconst);
956 let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" };
957 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
958 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
960 // We're adding custom sections to the output object file, but we definitely
961 // do not want these custom sections to make their way into the final linked
962 // executable. The purpose of these custom sections is for tooling
963 // surrounding object files to work with the LLVM IR, if necessary. For
964 // example rustc's own LTO will look for LLVM IR inside of the object file
965 // in these sections by default.
967 // To handle this is a bit different depending on the object file format
968 // used by the backend, broken down into a few different categories:
970 // * Mach-O - this is for macOS. Inspecting the source code for the native
971 // linker here shows that the `.llvmbc` and `.llvmcmd` sections are
972 // automatically skipped by the linker. In that case there's nothing extra
973 // that we need to do here.
975 // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
976 // `.llvmcmd` sections, so there's nothing extra we need to do.
978 // * COFF - if we don't do anything the linker will by default copy all
979 // these sections to the output artifact, not what we want! To subvert
980 // this we want to flag the sections we inserted here as
981 // `IMAGE_SCN_LNK_REMOVE`. Unfortunately though LLVM has no native way to
982 // do this. Thankfully though we can do this with some inline assembly,
983 // which is easy enough to add via module-level global inline asm.
985 // * ELF - this is very similar to COFF above. One difference is that these
986 // sections are removed from the output linked artifact when
987 // `--gc-sections` is passed, which we pass by default. If that flag isn't
988 // passed though then these sections will show up in the final output.
989 // Additionally the flag that we need to set here is `SHF_EXCLUDE`.
991 || cgcx.opts.target_triple.triple().starts_with("wasm")
992 || cgcx.opts.target_triple.triple().starts_with("asmjs")
994 // nothing to do here
995 } else if cgcx.is_pe_coff {
997 .section .llvmbc,\"n\"
998 .section .llvmcmd,\"n\"
1000 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
1003 .section .llvmbc,\"e\"
1004 .section .llvmcmd,\"e\"
1006 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
1010 pub unsafe fn with_llvm_pmb(
1011 llmod: &llvm::Module,
1012 config: &ModuleConfig,
1013 opt_level: llvm::CodeGenOptLevel,
1014 prepare_for_thin_lto: bool,
1015 f: &mut dyn FnMut(&llvm::PassManagerBuilder),
1019 // Create the PassManagerBuilder for LLVM. We configure it with
1020 // reasonable defaults and prepare it to actually populate the pass
1022 let builder = llvm::LLVMPassManagerBuilderCreate();
1023 let opt_size = config.opt_size.map_or(llvm::CodeGenOptSizeNone, |x| to_llvm_opt_settings(x).1);
1024 let inline_threshold = config.inline_threshold;
1025 let pgo_gen_path = get_pgo_gen_path(config);
1026 let pgo_use_path = get_pgo_use_path(config);
1028 llvm::LLVMRustConfigurePassManagerBuilder(
1031 config.merge_functions,
1032 config.vectorize_slp,
1033 config.vectorize_loop,
1034 prepare_for_thin_lto,
1035 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1036 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1039 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
1041 if opt_size != llvm::CodeGenOptSizeNone {
1042 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
1045 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
1047 // Here we match what clang does (kinda). For O0 we only inline
1048 // always-inline functions (but don't add lifetime intrinsics), at O1 we
1049 // inline with lifetime intrinsics, and O2+ we add an inliner with a
1050 // thresholds copied from clang.
1051 match (opt_level, opt_size, inline_threshold) {
1053 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t as u32);
1055 (llvm::CodeGenOptLevel::Aggressive, ..) => {
1056 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1058 (_, llvm::CodeGenOptSizeDefault, _) => {
1059 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1061 (_, llvm::CodeGenOptSizeAggressive, _) => {
1062 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1064 (llvm::CodeGenOptLevel::None, ..) => {
1065 llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1067 (llvm::CodeGenOptLevel::Less, ..) => {
1068 llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1070 (llvm::CodeGenOptLevel::Default, ..) => {
1071 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1076 llvm::LLVMPassManagerBuilderDispose(builder);
1079 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1080 // This is required to satisfy `dllimport` references to static data in .rlibs
1081 // when using MSVC linker. We do this only for data, as linker can fix up
1082 // code references on its own.
1083 // See #26591, #27438
1084 fn create_msvc_imps(
1085 cgcx: &CodegenContext<LlvmCodegenBackend>,
1086 llcx: &llvm::Context,
1087 llmod: &llvm::Module,
1089 if !cgcx.msvc_imps_needed {
1092 // The x86 ABI seems to require that leading underscores are added to symbol
1093 // names, so we need an extra underscore on x86. There's also a leading
1094 // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
1095 // underscores added in front).
1096 let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
1099 let i8p_ty = Type::i8p_llcx(llcx);
1100 let globals = base::iter_globals(llmod)
1102 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
1103 && llvm::LLVMIsDeclaration(val) == 0
1106 // Exclude some symbols that we know are not Rust symbols.
1107 let name = llvm::get_value_name(val);
1108 if ignored(name) { None } else { Some((val, name)) }
1110 .map(move |(val, name)| {
1111 let mut imp_name = prefix.as_bytes().to_vec();
1112 imp_name.extend(name);
1113 let imp_name = CString::new(imp_name).unwrap();
1116 .collect::<Vec<_>>();
1118 for (imp_name, val) in globals {
1119 let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast());
1120 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
1121 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
1125 // Use this function to exclude certain symbols from `__imp` generation.
1126 fn ignored(symbol_name: &[u8]) -> bool {
1127 // These are symbols generated by LLVM's profiling instrumentation
1128 symbol_name.starts_with(b"__llvm_profile_")