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_middle::bug;
24 use rustc_middle::ty::TyCtxt;
25 use rustc_session::config::{self, Lto, OutputType, Passes, SwitchWithOptPath};
26 use rustc_session::Session;
27 use rustc_span::symbol::sym;
28 use rustc_span::InnerSpan;
29 use rustc_target::spec::{CodeModel, RelocModel, SanitizerSet, SplitDebuginfo};
32 use libc::{c_char, c_int, c_uint, c_void, size_t};
33 use std::ffi::CString;
35 use std::io::{self, Write};
36 use std::path::{Path, PathBuf};
41 pub fn llvm_err(handler: &rustc_errors::Handler, msg: &str) -> FatalError {
42 match llvm::last_error() {
43 Some(err) => handler.fatal(&format!("{}: {}", msg, err)),
44 None => handler.fatal(&msg),
48 pub fn write_output_file(
49 handler: &rustc_errors::Handler,
50 target: &'ll llvm::TargetMachine,
51 pm: &llvm::PassManager<'ll>,
54 dwo_output: Option<&Path>,
55 file_type: llvm::FileType,
56 ) -> Result<(), FatalError> {
58 let output_c = path_to_c_string(output);
59 let result = if let Some(dwo_output) = dwo_output {
60 let dwo_output_c = path_to_c_string(dwo_output);
61 llvm::LLVMRustWriteOutputFile(
66 dwo_output_c.as_ptr(),
70 llvm::LLVMRustWriteOutputFile(
79 result.into_result().map_err(|()| {
80 let msg = format!("could not write output to {}", output.display());
81 llvm_err(handler, &msg)
86 pub fn create_informational_target_machine(sess: &Session) -> &'static mut llvm::TargetMachine {
87 let config = TargetMachineFactoryConfig { split_dwarf_file: None };
88 target_machine_factory(sess, config::OptLevel::No)(config)
89 .unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise())
92 pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> &'static mut llvm::TargetMachine {
93 let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
94 tcx.output_filenames(()).split_dwarf_path(tcx.sess.split_debuginfo(), Some(mod_name))
98 let config = TargetMachineFactoryConfig { split_dwarf_file };
99 target_machine_factory(&tcx.sess, tcx.backend_optimization_level(()))(config)
100 .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise())
103 pub fn to_llvm_opt_settings(
104 cfg: config::OptLevel,
105 ) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
106 use self::config::OptLevel::*;
108 No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
109 Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
110 Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
111 Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
112 Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
113 SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
117 fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
118 use config::OptLevel::*;
120 No => llvm::PassBuilderOptLevel::O0,
121 Less => llvm::PassBuilderOptLevel::O1,
122 Default => llvm::PassBuilderOptLevel::O2,
123 Aggressive => llvm::PassBuilderOptLevel::O3,
124 Size => llvm::PassBuilderOptLevel::Os,
125 SizeMin => llvm::PassBuilderOptLevel::Oz,
129 fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
130 match relocation_model {
131 RelocModel::Static => llvm::RelocModel::Static,
132 // LLVM doesn't have a PIE relocation model, it represents PIE as PIC with an extra attribute.
133 RelocModel::Pic | RelocModel::Pie => llvm::RelocModel::PIC,
134 RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
135 RelocModel::Ropi => llvm::RelocModel::ROPI,
136 RelocModel::Rwpi => llvm::RelocModel::RWPI,
137 RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
141 pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
143 Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
144 Some(CodeModel::Small) => llvm::CodeModel::Small,
145 Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
146 Some(CodeModel::Medium) => llvm::CodeModel::Medium,
147 Some(CodeModel::Large) => llvm::CodeModel::Large,
148 None => llvm::CodeModel::None,
152 pub fn target_machine_factory(
154 optlvl: config::OptLevel,
155 ) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
156 let reloc_model = to_llvm_relocation_model(sess.relocation_model());
158 let (opt_level, _) = to_llvm_opt_settings(optlvl);
159 let use_softfp = sess.opts.cg.soft_float;
161 let ffunction_sections =
162 sess.opts.debugging_opts.function_sections.unwrap_or(sess.target.function_sections);
163 let fdata_sections = ffunction_sections;
165 let code_model = to_llvm_code_model(sess.code_model());
167 let mut singlethread = sess.target.singlethread;
169 // On the wasm target once the `atomics` feature is enabled that means that
170 // we're no longer single-threaded, or otherwise we don't want LLVM to
171 // lower atomic operations to single-threaded operations.
172 if singlethread && sess.target.is_like_wasm && sess.target_features.contains(&sym::atomics) {
173 singlethread = false;
176 let triple = SmallCStr::new(&sess.target.llvm_target);
177 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
178 let features = llvm_util::llvm_global_features(sess).join(",");
179 let features = CString::new(features).unwrap();
180 let abi = SmallCStr::new(&sess.target.llvm_abiname);
181 let trap_unreachable =
182 sess.opts.debugging_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
183 let emit_stack_size_section = sess.opts.debugging_opts.emit_stack_sizes;
185 let asm_comments = sess.asm_comments();
186 let relax_elf_relocations =
187 sess.opts.debugging_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
190 !sess.opts.debugging_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
192 Arc::new(move |config: TargetMachineFactoryConfig| {
193 let split_dwarf_file = config.split_dwarf_file.unwrap_or_default();
194 let split_dwarf_file = CString::new(split_dwarf_file.to_str().unwrap()).unwrap();
197 llvm::LLVMRustCreateTargetMachine(
211 emit_stack_size_section,
212 relax_elf_relocations,
214 split_dwarf_file.as_ptr(),
219 format!("Could not create LLVM TargetMachine for triple: {}", triple.to_str().unwrap())
224 pub(crate) fn save_temp_bitcode(
225 cgcx: &CodegenContext<LlvmCodegenBackend>,
226 module: &ModuleCodegen<ModuleLlvm>,
229 if !cgcx.save_temps {
233 let ext = format!("{}.bc", name);
234 let cgu = Some(&module.name[..]);
235 let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
236 let cstr = path_to_c_string(&path);
237 let llmod = module.module_llvm.llmod();
238 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
242 pub struct DiagnosticHandlers<'a> {
243 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
244 llcx: &'a llvm::Context,
247 impl<'a> DiagnosticHandlers<'a> {
249 cgcx: &'a CodegenContext<LlvmCodegenBackend>,
250 handler: &'a Handler,
251 llcx: &'a llvm::Context,
253 let data = Box::into_raw(Box::new((cgcx, handler)));
255 llvm::LLVMRustSetInlineAsmDiagnosticHandler(llcx, inline_asm_handler, data.cast());
256 llvm::LLVMContextSetDiagnosticHandler(llcx, diagnostic_handler, data.cast());
258 DiagnosticHandlers { data, llcx }
262 impl<'a> Drop for DiagnosticHandlers<'a> {
264 use std::ptr::null_mut;
266 llvm::LLVMRustSetInlineAsmDiagnosticHandler(self.llcx, inline_asm_handler, null_mut());
267 llvm::LLVMContextSetDiagnosticHandler(self.llcx, diagnostic_handler, null_mut());
268 drop(Box::from_raw(self.data));
273 fn report_inline_asm(
274 cgcx: &CodegenContext<LlvmCodegenBackend>,
276 level: llvm::DiagnosticLevel,
278 source: Option<(String, Vec<InnerSpan>)>,
280 // In LTO build we may get srcloc values from other crates which are invalid
281 // since they use a different source map. To be safe we just suppress these
283 if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
286 let level = match level {
287 llvm::DiagnosticLevel::Error => Level::Error,
288 llvm::DiagnosticLevel::Warning => Level::Warning,
289 llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
291 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg, level, source);
294 unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, user: *const c_void, cookie: c_uint) {
298 let (cgcx, _) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
300 let smdiag = llvm::diagnostic::SrcMgrDiagnostic::unpack(diag);
301 report_inline_asm(cgcx, smdiag.message, smdiag.level, cookie, smdiag.source);
304 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
308 let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
310 match llvm::diagnostic::Diagnostic::unpack(info) {
311 llvm::diagnostic::InlineAsm(inline) => {
312 report_inline_asm(cgcx, inline.message, inline.level, inline.cookie, inline.source);
315 llvm::diagnostic::Optimization(opt) => {
316 let enabled = match cgcx.remark {
318 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
322 diag_handler.note_without_error(&format!(
323 "optimization {} for {} at {}:{}:{}: {}",
333 llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
334 let msg = llvm::build_string(|s| {
335 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
337 .expect("non-UTF8 diagnostic");
338 diag_handler.warn(&msg);
340 llvm::diagnostic::Unsupported(diagnostic_ref) => {
341 let msg = llvm::build_string(|s| {
342 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
344 .expect("non-UTF8 diagnostic");
345 diag_handler.err(&msg);
347 llvm::diagnostic::UnknownDiagnostic(..) => {}
351 fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
352 match config.pgo_gen {
353 SwitchWithOptPath::Enabled(ref opt_dir_path) => {
354 let path = if let Some(dir_path) = opt_dir_path {
355 dir_path.join("default_%m.profraw")
357 PathBuf::from("default_%m.profraw")
360 Some(CString::new(format!("{}", path.display())).unwrap())
362 SwitchWithOptPath::Disabled => None,
366 fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
370 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
373 pub(crate) fn should_use_new_llvm_pass_manager(config: &ModuleConfig) -> bool {
374 // The new pass manager is enabled by default for LLVM >= 13.
375 // This matches Clang, which also enables it since Clang 13.
376 config.new_llvm_pass_manager.unwrap_or_else(|| llvm_util::get_version() >= (13, 0, 0))
379 pub(crate) unsafe fn optimize_with_new_llvm_pass_manager(
380 cgcx: &CodegenContext<LlvmCodegenBackend>,
381 diag_handler: &Handler,
382 module: &ModuleCodegen<ModuleLlvm>,
383 config: &ModuleConfig,
384 opt_level: config::OptLevel,
385 opt_stage: llvm::OptStage,
386 ) -> Result<(), FatalError> {
388 opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
389 let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
390 let pgo_gen_path = get_pgo_gen_path(config);
391 let pgo_use_path = get_pgo_use_path(config);
392 let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
393 // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
394 let sanitizer_options = if !is_lto {
395 Some(llvm::SanitizerOptions {
396 sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
397 sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
398 sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
399 sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
400 sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
401 sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
402 sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
403 sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
409 let mut llvm_profiler = if cgcx.prof.llvm_recording_enabled() {
410 Some(LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()))
415 let llvm_selfprofiler =
416 llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
418 let extra_passes = config.passes.join(",");
420 // FIXME: NewPM doesn't provide a facility to pass custom InlineParams.
421 // We would have to add upstream support for this first, before we can support
422 // config.inline_threshold and our more aggressive default thresholds.
423 let result = llvm::LLVMRustOptimizeWithNewPassManager(
424 module.module_llvm.llmod(),
425 &*module.module_llvm.tm,
426 to_pass_builder_opt_level(opt_level),
428 config.no_prepopulate_passes,
429 config.verify_llvm_ir,
431 config.merge_functions,
433 config.vectorize_slp,
434 config.vectorize_loop,
436 config.emit_lifetime_markers,
437 sanitizer_options.as_ref(),
438 pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
439 pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
440 config.instrument_coverage,
441 config.instrument_gcov,
443 selfprofile_before_pass_callback,
444 selfprofile_after_pass_callback,
445 extra_passes.as_ptr().cast(),
448 result.into_result().map_err(|()| llvm_err(diag_handler, "failed to run LLVM passes"))
451 // Unsafe due to LLVM calls.
452 pub(crate) unsafe fn optimize(
453 cgcx: &CodegenContext<LlvmCodegenBackend>,
454 diag_handler: &Handler,
455 module: &ModuleCodegen<ModuleLlvm>,
456 config: &ModuleConfig,
457 ) -> Result<(), FatalError> {
458 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &module.name[..]);
460 let llmod = module.module_llvm.llmod();
461 let llcx = &*module.module_llvm.llcx;
462 let tm = &*module.module_llvm.tm;
463 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
465 let module_name = module.name.clone();
466 let module_name = Some(&module_name[..]);
468 if config.emit_no_opt_bc {
469 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
470 let out = path_to_c_string(&out);
471 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
474 if let Some(opt_level) = config.opt_level {
475 if should_use_new_llvm_pass_manager(config) {
476 let opt_stage = match cgcx.lto {
477 Lto::Fat => llvm::OptStage::PreLinkFatLTO,
478 Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
479 _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
480 _ => llvm::OptStage::PreLinkNoLTO,
482 return optimize_with_new_llvm_pass_manager(
492 if cgcx.prof.llvm_recording_enabled() {
494 .warn("`-Z self-profile-events = llvm` requires `-Z new-llvm-pass-manager`");
497 // Create the two optimizing pass managers. These mirror what clang
498 // does, and are by populated by LLVM's default PassManagerBuilder.
499 // Each manager has a different set of passes, but they also share
500 // some common passes.
501 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
502 let mpm = llvm::LLVMCreatePassManager();
505 let find_pass = |pass_name: &str| {
506 let pass_name = SmallCStr::new(pass_name);
507 llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr())
510 if config.verify_llvm_ir {
511 // Verification should run as the very first pass.
512 llvm::LLVMRustAddPass(fpm, find_pass("verify").unwrap());
515 let mut extra_passes = Vec::new();
516 let mut have_name_anon_globals_pass = false;
518 for pass_name in &config.passes {
519 if pass_name == "lint" {
520 // Linting should also be performed early, directly on the generated IR.
521 llvm::LLVMRustAddPass(fpm, find_pass("lint").unwrap());
525 if let Some(pass) = find_pass(pass_name) {
526 extra_passes.push(pass);
528 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass_name));
531 if pass_name == "name-anon-globals" {
532 have_name_anon_globals_pass = true;
536 // Instrumentation must be inserted before optimization,
537 // otherwise LLVM may optimize some functions away which
540 // This mirrors what Clang does in lib/CodeGen/BackendUtil.cpp.
541 if config.instrument_gcov {
542 llvm::LLVMRustAddPass(mpm, find_pass("insert-gcov-profiling").unwrap());
544 if config.instrument_coverage {
545 llvm::LLVMRustAddPass(mpm, find_pass("instrprof").unwrap());
548 add_sanitizer_passes(config, &mut extra_passes);
550 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
551 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
552 // we'll get errors in LLVM.
553 let using_thin_buffers = config.bitcode_needed();
554 if !config.no_prepopulate_passes {
555 llvm::LLVMAddAnalysisPasses(tm, fpm);
556 llvm::LLVMAddAnalysisPasses(tm, mpm);
557 let opt_level = to_llvm_opt_settings(opt_level).0;
558 let prepare_for_thin_lto = cgcx.lto == Lto::Thin
559 || cgcx.lto == Lto::ThinLocal
560 || (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
561 with_llvm_pmb(llmod, &config, opt_level, prepare_for_thin_lto, &mut |b| {
562 llvm::LLVMRustAddLastExtensionPasses(
564 extra_passes.as_ptr(),
565 extra_passes.len() as size_t,
567 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(b, fpm);
568 llvm::LLVMPassManagerBuilderPopulateModulePassManager(b, mpm);
571 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
572 if using_thin_buffers && !prepare_for_thin_lto {
573 llvm::LLVMRustAddPass(mpm, find_pass("name-anon-globals").unwrap());
574 have_name_anon_globals_pass = true;
577 // If we don't use the standard pipeline, directly populate the MPM
578 // with the extra passes.
579 for pass in extra_passes {
580 llvm::LLVMRustAddPass(mpm, pass);
584 if using_thin_buffers && !have_name_anon_globals_pass {
585 // As described above, this will probably cause an error in LLVM
586 if config.no_prepopulate_passes {
588 "The current compilation is going to use thin LTO buffers \
589 without running LLVM's NameAnonGlobals pass. \
590 This will likely cause errors in LLVM. Consider adding \
591 -C passes=name-anon-globals to the compiler command line.",
595 "We are using thin LTO buffers without running the NameAnonGlobals pass. \
596 This will likely cause errors in LLVM and should never happen."
602 diag_handler.abort_if_errors();
604 // Finally, run the actual optimization passes
606 let _timer = cgcx.prof.extra_verbose_generic_activity(
607 "LLVM_module_optimize_function_passes",
610 llvm::LLVMRustRunFunctionPassManager(fpm, llmod);
613 let _timer = cgcx.prof.extra_verbose_generic_activity(
614 "LLVM_module_optimize_module_passes",
617 llvm::LLVMRunPassManager(mpm, llmod);
620 // Deallocate managers that we're now done with
621 llvm::LLVMDisposePassManager(fpm);
622 llvm::LLVMDisposePassManager(mpm);
627 unsafe fn add_sanitizer_passes(config: &ModuleConfig, passes: &mut Vec<&'static mut llvm::Pass>) {
628 if config.sanitizer.contains(SanitizerSet::ADDRESS) {
629 let recover = config.sanitizer_recover.contains(SanitizerSet::ADDRESS);
630 passes.push(llvm::LLVMRustCreateAddressSanitizerFunctionPass(recover));
631 passes.push(llvm::LLVMRustCreateModuleAddressSanitizerPass(recover));
633 if config.sanitizer.contains(SanitizerSet::MEMORY) {
634 let track_origins = config.sanitizer_memory_track_origins as c_int;
635 let recover = config.sanitizer_recover.contains(SanitizerSet::MEMORY);
636 passes.push(llvm::LLVMRustCreateMemorySanitizerPass(track_origins, recover));
638 if config.sanitizer.contains(SanitizerSet::THREAD) {
639 passes.push(llvm::LLVMRustCreateThreadSanitizerPass());
641 if config.sanitizer.contains(SanitizerSet::HWADDRESS) {
642 let recover = config.sanitizer_recover.contains(SanitizerSet::HWADDRESS);
643 passes.push(llvm::LLVMRustCreateHWAddressSanitizerPass(recover));
648 cgcx: &CodegenContext<LlvmCodegenBackend>,
649 diag_handler: &Handler,
650 mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
651 ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
652 use super::lto::{Linker, ModuleBuffer};
653 // Sort the modules by name to ensure to ensure deterministic behavior.
654 modules.sort_by(|a, b| a.name.cmp(&b.name));
655 let (first, elements) =
656 modules.split_first().expect("Bug! modules must contain at least one module.");
658 let mut linker = Linker::new(first.module_llvm.llmod());
659 for module in elements {
661 cgcx.prof.generic_activity_with_arg("LLVM_link_module", format!("{:?}", module.name));
662 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
663 linker.add(&buffer.data()).map_err(|()| {
664 let msg = format!("failed to serialize module {:?}", module.name);
665 llvm_err(&diag_handler, &msg)
669 Ok(modules.remove(0))
672 pub(crate) unsafe fn codegen(
673 cgcx: &CodegenContext<LlvmCodegenBackend>,
674 diag_handler: &Handler,
675 module: ModuleCodegen<ModuleLlvm>,
676 config: &ModuleConfig,
677 ) -> Result<CompiledModule, FatalError> {
678 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &module.name[..]);
680 let llmod = module.module_llvm.llmod();
681 let llcx = &*module.module_llvm.llcx;
682 let tm = &*module.module_llvm.tm;
683 let module_name = module.name.clone();
684 let module_name = Some(&module_name[..]);
685 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
687 if cgcx.msvc_imps_needed {
688 create_msvc_imps(cgcx, llcx, llmod);
691 // A codegen-specific pass manager is used to generate object
692 // files for an LLVM module.
694 // Apparently each of these pass managers is a one-shot kind of
695 // thing, so we create a new one for each type of output. The
696 // pass manager passed to the closure should be ensured to not
697 // escape the closure itself, and the manager should only be
699 unsafe fn with_codegen<'ll, F, R>(
700 tm: &'ll llvm::TargetMachine,
701 llmod: &'ll llvm::Module,
706 F: FnOnce(&'ll mut PassManager<'ll>) -> R,
708 let cpm = llvm::LLVMCreatePassManager();
709 llvm::LLVMAddAnalysisPasses(tm, cpm);
710 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
714 // Two things to note:
715 // - If object files are just LLVM bitcode we write bitcode, copy it to
716 // the .o file, and delete the bitcode if it wasn't otherwise
718 // - If we don't have the integrated assembler then we need to emit
719 // asm from LLVM and use `gcc` to create the object file.
721 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
722 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
724 if config.bitcode_needed() {
727 .generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &module.name[..]);
728 let thin = ThinBuffer::new(llmod);
729 let data = thin.data();
731 if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
732 let _timer = cgcx.prof.generic_activity_with_arg(
733 "LLVM_module_codegen_emit_bitcode",
736 if let Err(e) = fs::write(&bc_out, data) {
737 let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
738 diag_handler.err(&msg);
742 if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
743 let _timer = cgcx.prof.generic_activity_with_arg(
744 "LLVM_module_codegen_embed_bitcode",
747 embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
754 .generic_activity_with_arg("LLVM_module_codegen_emit_ir", &module.name[..]);
755 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
756 let out_c = path_to_c_string(&out);
758 extern "C" fn demangle_callback(
759 input_ptr: *const c_char,
761 output_ptr: *mut c_char,
765 unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
767 let input = match str::from_utf8(input) {
772 let output = unsafe {
773 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
775 let mut cursor = io::Cursor::new(output);
777 let demangled = match rustc_demangle::try_demangle(input) {
782 if write!(cursor, "{:#}", demangled).is_err() {
783 // Possible only if provided buffer is not big enough
787 cursor.position() as size_t
790 let result = llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback);
791 result.into_result().map_err(|()| {
792 let msg = format!("failed to write LLVM IR to {}", out.display());
793 llvm_err(diag_handler, &msg)
800 .generic_activity_with_arg("LLVM_module_codegen_emit_asm", &module.name[..]);
801 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
803 // We can't use the same module for asm and object code output,
804 // because that triggers various errors like invalid IR or broken
805 // binaries. So we must clone the module to produce the asm output
806 // if we are also producing object code.
807 let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
808 llvm::LLVMCloneModule(llmod)
812 with_codegen(tm, llmod, config.no_builtins, |cpm| {
820 llvm::FileType::AssemblyFile,
825 match config.emit_obj {
826 EmitObj::ObjectCode(_) => {
829 .generic_activity_with_arg("LLVM_module_codegen_emit_obj", &module.name[..]);
831 let dwo_out = cgcx.output_filenames.temp_path_dwo(module_name);
832 let dwo_out = match cgcx.split_debuginfo {
833 // Don't change how DWARF is emitted in single mode (or when disabled).
834 SplitDebuginfo::Off | SplitDebuginfo::Packed => None,
835 // Emit (a subset of the) DWARF into a separate file in split mode.
836 SplitDebuginfo::Unpacked => {
837 if cgcx.target_can_use_split_dwarf {
838 Some(dwo_out.as_path())
845 with_codegen(tm, llmod, config.no_builtins, |cpm| {
853 llvm::FileType::ObjectFile,
858 EmitObj::Bitcode => {
859 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
860 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
861 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
865 debug!("removing_bitcode {:?}", bc_out);
866 ensure_removed(diag_handler, &bc_out);
876 Ok(module.into_compiled_module(
877 config.emit_obj != EmitObj::None,
878 cgcx.target_can_use_split_dwarf && cgcx.split_debuginfo == SplitDebuginfo::Unpacked,
880 &cgcx.output_filenames,
884 /// Embed the bitcode of an LLVM module in the LLVM module itself.
886 /// This is done primarily for iOS where it appears to be standard to compile C
887 /// code at least with `-fembed-bitcode` which creates two sections in the
890 /// * __LLVM,__bitcode
891 /// * __LLVM,__cmdline
893 /// It appears *both* of these sections are necessary to get the linker to
894 /// recognize what's going on. A suitable cmdline value is taken from the
897 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
898 /// embed an empty section.
900 /// Basically all of this is us attempting to follow in the footsteps of clang
901 /// on iOS. See #35968 for lots more info.
902 unsafe fn embed_bitcode(
903 cgcx: &CodegenContext<LlvmCodegenBackend>,
904 llcx: &llvm::Context,
905 llmod: &llvm::Module,
909 let llconst = common::bytes_in_context(llcx, bitcode);
910 let llglobal = llvm::LLVMAddGlobal(
912 common::val_ty(llconst),
913 "rustc.embedded.module\0".as_ptr().cast(),
915 llvm::LLVMSetInitializer(llglobal, llconst);
917 let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
918 || cgcx.opts.target_triple.triple().contains("-darwin")
919 || cgcx.opts.target_triple.triple().contains("-tvos");
921 let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" };
922 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
923 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
924 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
926 let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
927 let llglobal = llvm::LLVMAddGlobal(
929 common::val_ty(llconst),
930 "rustc.embedded.cmdline\0".as_ptr().cast(),
932 llvm::LLVMSetInitializer(llglobal, llconst);
933 let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" };
934 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
935 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
937 // We're adding custom sections to the output object file, but we definitely
938 // do not want these custom sections to make their way into the final linked
939 // executable. The purpose of these custom sections is for tooling
940 // surrounding object files to work with the LLVM IR, if necessary. For
941 // example rustc's own LTO will look for LLVM IR inside of the object file
942 // in these sections by default.
944 // To handle this is a bit different depending on the object file format
945 // used by the backend, broken down into a few different categories:
947 // * Mach-O - this is for macOS. Inspecting the source code for the native
948 // linker here shows that the `.llvmbc` and `.llvmcmd` sections are
949 // automatically skipped by the linker. In that case there's nothing extra
950 // that we need to do here.
952 // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
953 // `.llvmcmd` sections, so there's nothing extra we need to do.
955 // * COFF - if we don't do anything the linker will by default copy all
956 // these sections to the output artifact, not what we want! To subvert
957 // this we want to flag the sections we inserted here as
958 // `IMAGE_SCN_LNK_REMOVE`. Unfortunately though LLVM has no native way to
959 // do this. Thankfully though we can do this with some inline assembly,
960 // which is easy enough to add via module-level global inline asm.
962 // * ELF - this is very similar to COFF above. One difference is that these
963 // sections are removed from the output linked artifact when
964 // `--gc-sections` is passed, which we pass by default. If that flag isn't
965 // passed though then these sections will show up in the final output.
966 // Additionally the flag that we need to set here is `SHF_EXCLUDE`.
968 || cgcx.opts.target_triple.triple().starts_with("wasm")
969 || cgcx.opts.target_triple.triple().starts_with("asmjs")
971 // nothing to do here
972 } else if cgcx.is_pe_coff {
974 .section .llvmbc,\"n\"
975 .section .llvmcmd,\"n\"
977 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
980 .section .llvmbc,\"e\"
981 .section .llvmcmd,\"e\"
983 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
987 pub unsafe fn with_llvm_pmb(
988 llmod: &llvm::Module,
989 config: &ModuleConfig,
990 opt_level: llvm::CodeGenOptLevel,
991 prepare_for_thin_lto: bool,
992 f: &mut dyn FnMut(&llvm::PassManagerBuilder),
996 // Create the PassManagerBuilder for LLVM. We configure it with
997 // reasonable defaults and prepare it to actually populate the pass
999 let builder = llvm::LLVMPassManagerBuilderCreate();
1000 let opt_size = config.opt_size.map_or(llvm::CodeGenOptSizeNone, |x| to_llvm_opt_settings(x).1);
1001 let inline_threshold = config.inline_threshold;
1002 let pgo_gen_path = get_pgo_gen_path(config);
1003 let pgo_use_path = get_pgo_use_path(config);
1005 llvm::LLVMRustConfigurePassManagerBuilder(
1008 config.merge_functions,
1009 config.vectorize_slp,
1010 config.vectorize_loop,
1011 prepare_for_thin_lto,
1012 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1013 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1016 llvm::LLVMPassManagerBuilderSetSizeLevel(builder, opt_size as u32);
1018 if opt_size != llvm::CodeGenOptSizeNone {
1019 llvm::LLVMPassManagerBuilderSetDisableUnrollLoops(builder, 1);
1022 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
1024 // Here we match what clang does (kinda). For O0 we only inline
1025 // always-inline functions (but don't add lifetime intrinsics), at O1 we
1026 // inline with lifetime intrinsics, and O2+ we add an inliner with a
1027 // thresholds copied from clang.
1028 match (opt_level, opt_size, inline_threshold) {
1030 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, t);
1032 (llvm::CodeGenOptLevel::Aggressive, ..) => {
1033 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1035 (_, llvm::CodeGenOptSizeDefault, _) => {
1036 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1038 (_, llvm::CodeGenOptSizeAggressive, _) => {
1039 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1041 (llvm::CodeGenOptLevel::None, ..) => {
1042 llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1044 (llvm::CodeGenOptLevel::Less, ..) => {
1045 llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1047 (llvm::CodeGenOptLevel::Default, ..) => {
1048 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1053 llvm::LLVMPassManagerBuilderDispose(builder);
1056 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1057 // This is required to satisfy `dllimport` references to static data in .rlibs
1058 // when using MSVC linker. We do this only for data, as linker can fix up
1059 // code references on its own.
1060 // See #26591, #27438
1061 fn create_msvc_imps(
1062 cgcx: &CodegenContext<LlvmCodegenBackend>,
1063 llcx: &llvm::Context,
1064 llmod: &llvm::Module,
1066 if !cgcx.msvc_imps_needed {
1069 // The x86 ABI seems to require that leading underscores are added to symbol
1070 // names, so we need an extra underscore on x86. There's also a leading
1071 // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
1072 // underscores added in front).
1073 let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
1076 let i8p_ty = Type::i8p_llcx(llcx);
1077 let globals = base::iter_globals(llmod)
1079 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
1080 && llvm::LLVMIsDeclaration(val) == 0
1083 // Exclude some symbols that we know are not Rust symbols.
1084 let name = llvm::get_value_name(val);
1085 if ignored(name) { None } else { Some((val, name)) }
1087 .map(move |(val, name)| {
1088 let mut imp_name = prefix.as_bytes().to_vec();
1089 imp_name.extend(name);
1090 let imp_name = CString::new(imp_name).unwrap();
1093 .collect::<Vec<_>>();
1095 for (imp_name, val) in globals {
1096 let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast());
1097 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
1098 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
1102 // Use this function to exclude certain symbols from `__imp` generation.
1103 fn ignored(symbol_name: &[u8]) -> bool {
1104 // These are symbols generated by LLVM's profiling instrumentation
1105 symbol_name.starts_with(b"__llvm_profile_")