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};
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::profiling::SelfProfilerRef;
21 use rustc_data_structures::small_c_str::SmallCStr;
22 use rustc_errors::{FatalError, Handler, Level};
23 use rustc_fs_util::{link_or_copy, path_to_c_string};
24 use rustc_middle::bug;
25 use rustc_middle::ty::TyCtxt;
26 use rustc_session::config::{self, Lto, OutputType, Passes, SplitDwarfKind, 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<'ll>(
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 self_profiler_ref: &SelfProfilerRef,
58 ) -> Result<(), FatalError> {
59 debug!("write_output_file output={:?} dwo_output={:?}", output, dwo_output);
61 let output_c = path_to_c_string(output);
63 let dwo_output_ptr = if let Some(dwo_output) = dwo_output {
64 dwo_output_c = path_to_c_string(dwo_output);
69 let result = llvm::LLVMRustWriteOutputFile(
78 // Record artifact sizes for self-profiling
79 if result == llvm::LLVMRustResult::Success {
80 let artifact_kind = match file_type {
81 llvm::FileType::ObjectFile => "object_file",
82 llvm::FileType::AssemblyFile => "assembly_file",
84 record_artifact_size(self_profiler_ref, artifact_kind, output);
85 if let Some(dwo_file) = dwo_output {
86 record_artifact_size(self_profiler_ref, "dwo_file", dwo_file);
90 result.into_result().map_err(|()| {
91 let msg = format!("could not write output to {}", output.display());
92 llvm_err(handler, &msg)
97 pub fn create_informational_target_machine(sess: &Session) -> &'static mut llvm::TargetMachine {
98 let config = TargetMachineFactoryConfig { split_dwarf_file: None };
99 // Can't use query system here quite yet because this function is invoked before the query
100 // system/tcx is set up.
101 let features = llvm_util::global_llvm_features(sess, false);
102 target_machine_factory(sess, config::OptLevel::No, &features)(config)
103 .unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise())
106 pub fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> &'static mut llvm::TargetMachine {
107 let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
108 tcx.output_filenames(()).split_dwarf_path(
109 tcx.sess.split_debuginfo(),
110 tcx.sess.opts.unstable_opts.split_dwarf_kind,
116 let config = TargetMachineFactoryConfig { split_dwarf_file };
117 target_machine_factory(
119 tcx.backend_optimization_level(()),
120 tcx.global_backend_features(()),
122 .unwrap_or_else(|err| llvm_err(tcx.sess.diagnostic(), &err).raise())
125 pub fn to_llvm_opt_settings(
126 cfg: config::OptLevel,
127 ) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
128 use self::config::OptLevel::*;
130 No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
131 Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
132 Default => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
133 Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
134 Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
135 SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
139 fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
140 use config::OptLevel::*;
142 No => llvm::PassBuilderOptLevel::O0,
143 Less => llvm::PassBuilderOptLevel::O1,
144 Default => llvm::PassBuilderOptLevel::O2,
145 Aggressive => llvm::PassBuilderOptLevel::O3,
146 Size => llvm::PassBuilderOptLevel::Os,
147 SizeMin => llvm::PassBuilderOptLevel::Oz,
151 fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
152 match relocation_model {
153 RelocModel::Static => llvm::RelocModel::Static,
154 // LLVM doesn't have a PIE relocation model, it represents PIE as PIC with an extra attribute.
155 RelocModel::Pic | RelocModel::Pie => llvm::RelocModel::PIC,
156 RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
157 RelocModel::Ropi => llvm::RelocModel::ROPI,
158 RelocModel::Rwpi => llvm::RelocModel::RWPI,
159 RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
163 pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
165 Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
166 Some(CodeModel::Small) => llvm::CodeModel::Small,
167 Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
168 Some(CodeModel::Medium) => llvm::CodeModel::Medium,
169 Some(CodeModel::Large) => llvm::CodeModel::Large,
170 None => llvm::CodeModel::None,
174 pub fn target_machine_factory(
176 optlvl: config::OptLevel,
177 target_features: &[String],
178 ) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
179 let reloc_model = to_llvm_relocation_model(sess.relocation_model());
181 let (opt_level, _) = to_llvm_opt_settings(optlvl);
182 let use_softfp = sess.opts.cg.soft_float;
184 let ffunction_sections =
185 sess.opts.unstable_opts.function_sections.unwrap_or(sess.target.function_sections);
186 let fdata_sections = ffunction_sections;
187 let funique_section_names = !sess.opts.unstable_opts.no_unique_section_names;
189 let code_model = to_llvm_code_model(sess.code_model());
191 let mut singlethread = sess.target.singlethread;
193 // On the wasm target once the `atomics` feature is enabled that means that
194 // we're no longer single-threaded, or otherwise we don't want LLVM to
195 // lower atomic operations to single-threaded operations.
196 if singlethread && sess.target.is_like_wasm && sess.target_features.contains(&sym::atomics) {
197 singlethread = false;
200 let triple = SmallCStr::new(&sess.target.llvm_target);
201 let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
202 let features = CString::new(target_features.join(",")).unwrap();
203 let abi = SmallCStr::new(&sess.target.llvm_abiname);
204 let trap_unreachable =
205 sess.opts.unstable_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
206 let emit_stack_size_section = sess.opts.unstable_opts.emit_stack_sizes;
208 let asm_comments = sess.asm_comments();
209 let relax_elf_relocations =
210 sess.opts.unstable_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
213 !sess.opts.unstable_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
215 let path_mapping = sess.source_map().path_mapping().clone();
217 Arc::new(move |config: TargetMachineFactoryConfig| {
218 let split_dwarf_file =
219 path_mapping.map_prefix(config.split_dwarf_file.unwrap_or_default()).0;
220 let split_dwarf_file = CString::new(split_dwarf_file.to_str().unwrap()).unwrap();
223 llvm::LLVMRustCreateTargetMachine(
234 funique_section_names,
238 emit_stack_size_section,
239 relax_elf_relocations,
241 split_dwarf_file.as_ptr(),
246 format!("Could not create LLVM TargetMachine for triple: {}", triple.to_str().unwrap())
251 pub(crate) fn save_temp_bitcode(
252 cgcx: &CodegenContext<LlvmCodegenBackend>,
253 module: &ModuleCodegen<ModuleLlvm>,
256 if !cgcx.save_temps {
260 let ext = format!("{}.bc", name);
261 let cgu = Some(&module.name[..]);
262 let path = cgcx.output_filenames.temp_path_ext(&ext, cgu);
263 let cstr = path_to_c_string(&path);
264 let llmod = module.module_llvm.llmod();
265 llvm::LLVMWriteBitcodeToFile(llmod, cstr.as_ptr());
269 pub struct DiagnosticHandlers<'a> {
270 data: *mut (&'a CodegenContext<LlvmCodegenBackend>, &'a Handler),
271 llcx: &'a llvm::Context,
272 old_handler: Option<&'a llvm::DiagnosticHandler>,
275 impl<'a> DiagnosticHandlers<'a> {
277 cgcx: &'a CodegenContext<LlvmCodegenBackend>,
278 handler: &'a Handler,
279 llcx: &'a llvm::Context,
281 let remark_passes_all: bool;
282 let remark_passes: Vec<CString>;
285 remark_passes_all = true;
286 remark_passes = Vec::new();
288 Passes::Some(passes) => {
289 remark_passes_all = false;
291 passes.iter().map(|name| CString::new(name.as_str()).unwrap()).collect();
294 let remark_passes: Vec<*const c_char> =
295 remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
296 let data = Box::into_raw(Box::new((cgcx, handler)));
298 let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
299 llvm::LLVMRustContextConfigureDiagnosticHandler(
304 remark_passes.as_ptr(),
307 DiagnosticHandlers { data, llcx, old_handler }
312 impl<'a> Drop for DiagnosticHandlers<'a> {
315 llvm::LLVMRustContextSetDiagnosticHandler(self.llcx, self.old_handler);
316 drop(Box::from_raw(self.data));
321 fn report_inline_asm(
322 cgcx: &CodegenContext<LlvmCodegenBackend>,
324 level: llvm::DiagnosticLevel,
326 source: Option<(String, Vec<InnerSpan>)>,
328 // In LTO build we may get srcloc values from other crates which are invalid
329 // since they use a different source map. To be safe we just suppress these
331 if matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
334 let level = match level {
335 llvm::DiagnosticLevel::Error => Level::Error { lint: false },
336 llvm::DiagnosticLevel::Warning => Level::Warning(None),
337 llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
339 cgcx.diag_emitter.inline_asm_error(cookie as u32, msg, level, source);
342 unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
346 let (cgcx, diag_handler) = *(user as *const (&CodegenContext<LlvmCodegenBackend>, &Handler));
348 match llvm::diagnostic::Diagnostic::unpack(info) {
349 llvm::diagnostic::InlineAsm(inline) => {
350 report_inline_asm(cgcx, inline.message, inline.level, inline.cookie, inline.source);
353 llvm::diagnostic::Optimization(opt) => {
354 let enabled = match cgcx.remark {
356 Passes::Some(ref v) => v.iter().any(|s| *s == opt.pass_name),
360 diag_handler.note_without_error(&format!(
362 opt.filename, opt.line, opt.column, opt.pass_name, opt.message,
366 llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
367 let msg = llvm::build_string(|s| {
368 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
370 .expect("non-UTF8 diagnostic");
371 diag_handler.warn(&msg);
373 llvm::diagnostic::Unsupported(diagnostic_ref) => {
374 let msg = llvm::build_string(|s| {
375 llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
377 .expect("non-UTF8 diagnostic");
378 diag_handler.err(&msg);
380 llvm::diagnostic::UnknownDiagnostic(..) => {}
384 fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
385 match config.pgo_gen {
386 SwitchWithOptPath::Enabled(ref opt_dir_path) => {
387 let path = if let Some(dir_path) = opt_dir_path {
388 dir_path.join("default_%m.profraw")
390 PathBuf::from("default_%m.profraw")
393 Some(CString::new(format!("{}", path.display())).unwrap())
395 SwitchWithOptPath::Disabled => None,
399 fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
403 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
406 fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
410 .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
413 pub(crate) unsafe fn optimize_with_new_llvm_pass_manager(
414 cgcx: &CodegenContext<LlvmCodegenBackend>,
415 diag_handler: &Handler,
416 module: &ModuleCodegen<ModuleLlvm>,
417 config: &ModuleConfig,
418 opt_level: config::OptLevel,
419 opt_stage: llvm::OptStage,
420 ) -> Result<(), FatalError> {
422 opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
423 let using_thin_buffers = opt_stage == llvm::OptStage::PreLinkThinLTO || config.bitcode_needed();
424 let pgo_gen_path = get_pgo_gen_path(config);
425 let pgo_use_path = get_pgo_use_path(config);
426 let pgo_sample_use_path = get_pgo_sample_use_path(config);
427 let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
428 // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
429 let sanitizer_options = if !is_lto {
430 Some(llvm::SanitizerOptions {
431 sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
432 sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
433 sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
434 sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
435 sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
436 sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
437 sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
438 sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
444 let mut llvm_profiler = if cgcx.prof.llvm_recording_enabled() {
445 Some(LlvmSelfProfiler::new(cgcx.prof.get_self_profiler().unwrap()))
450 let llvm_selfprofiler =
451 llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
453 let extra_passes = if !is_lto { config.passes.join(",") } else { "".to_string() };
455 let llvm_plugins = config.llvm_plugins.join(",");
457 // FIXME: NewPM doesn't provide a facility to pass custom InlineParams.
458 // We would have to add upstream support for this first, before we can support
459 // config.inline_threshold and our more aggressive default thresholds.
460 let result = llvm::LLVMRustOptimizeWithNewPassManager(
461 module.module_llvm.llmod(),
462 &*module.module_llvm.tm,
463 to_pass_builder_opt_level(opt_level),
465 config.no_prepopulate_passes,
466 config.verify_llvm_ir,
468 config.merge_functions,
470 config.vectorize_slp,
471 config.vectorize_loop,
473 config.emit_lifetime_markers,
474 sanitizer_options.as_ref(),
475 pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
476 pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
477 config.instrument_coverage,
478 config.instrument_gcov,
479 pgo_sample_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
480 config.debug_info_for_profiling,
482 selfprofile_before_pass_callback,
483 selfprofile_after_pass_callback,
484 extra_passes.as_ptr().cast(),
486 llvm_plugins.as_ptr().cast(),
489 result.into_result().map_err(|()| llvm_err(diag_handler, "failed to run LLVM passes"))
492 // Unsafe due to LLVM calls.
493 pub(crate) unsafe fn optimize(
494 cgcx: &CodegenContext<LlvmCodegenBackend>,
495 diag_handler: &Handler,
496 module: &ModuleCodegen<ModuleLlvm>,
497 config: &ModuleConfig,
498 ) -> Result<(), FatalError> {
499 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_optimize", &*module.name);
501 let llmod = module.module_llvm.llmod();
502 let llcx = &*module.module_llvm.llcx;
503 let tm = &*module.module_llvm.tm;
504 let _handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
506 let module_name = module.name.clone();
507 let module_name = Some(&module_name[..]);
509 if let Some(false) = config.new_llvm_pass_manager && llvm_util::get_version() >= (15, 0, 0) {
511 "ignoring `-Z new-llvm-pass-manager=no`, which is no longer supported with LLVM 15",
515 if config.emit_no_opt_bc {
516 let out = cgcx.output_filenames.temp_path_ext("no-opt.bc", module_name);
517 let out = path_to_c_string(&out);
518 llvm::LLVMWriteBitcodeToFile(llmod, out.as_ptr());
521 if let Some(opt_level) = config.opt_level {
522 if llvm_util::should_use_new_llvm_pass_manager(
523 &config.new_llvm_pass_manager,
526 let opt_stage = match cgcx.lto {
527 Lto::Fat => llvm::OptStage::PreLinkFatLTO,
528 Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
529 _ if cgcx.opts.cg.linker_plugin_lto.enabled() => llvm::OptStage::PreLinkThinLTO,
530 _ => llvm::OptStage::PreLinkNoLTO,
532 return optimize_with_new_llvm_pass_manager(
542 if cgcx.prof.llvm_recording_enabled() {
544 .warn("`-Z self-profile-events = llvm` requires `-Z new-llvm-pass-manager`");
547 // Create the two optimizing pass managers. These mirror what clang
548 // does, and are by populated by LLVM's default PassManagerBuilder.
549 // Each manager has a different set of passes, but they also share
550 // some common passes.
551 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
552 let mpm = llvm::LLVMCreatePassManager();
555 let find_pass = |pass_name: &str| {
556 let pass_name = SmallCStr::new(pass_name);
557 llvm::LLVMRustFindAndCreatePass(pass_name.as_ptr())
560 if config.verify_llvm_ir {
561 // Verification should run as the very first pass.
562 llvm::LLVMRustAddPass(fpm, find_pass("verify").unwrap());
565 let mut extra_passes = Vec::new();
566 let mut have_name_anon_globals_pass = false;
568 for pass_name in &config.passes {
569 if pass_name == "lint" {
570 // Linting should also be performed early, directly on the generated IR.
571 llvm::LLVMRustAddPass(fpm, find_pass("lint").unwrap());
575 if let Some(pass) = find_pass(pass_name) {
576 extra_passes.push(pass);
578 diag_handler.warn(&format!("unknown pass `{}`, ignoring", pass_name));
581 if pass_name == "name-anon-globals" {
582 have_name_anon_globals_pass = true;
586 // Instrumentation must be inserted before optimization,
587 // otherwise LLVM may optimize some functions away which
590 // This mirrors what Clang does in lib/CodeGen/BackendUtil.cpp.
591 if config.instrument_gcov {
592 llvm::LLVMRustAddPass(mpm, find_pass("insert-gcov-profiling").unwrap());
594 if config.instrument_coverage {
595 llvm::LLVMRustAddPass(mpm, find_pass("instrprof").unwrap());
597 if config.debug_info_for_profiling {
598 llvm::LLVMRustAddPass(mpm, find_pass("add-discriminators").unwrap());
601 add_sanitizer_passes(config, &mut extra_passes);
603 // Some options cause LLVM bitcode to be emitted, which uses ThinLTOBuffers, so we need
604 // to make sure we run LLVM's NameAnonGlobals pass when emitting bitcode; otherwise
605 // we'll get errors in LLVM.
606 let using_thin_buffers = config.bitcode_needed();
607 if !config.no_prepopulate_passes {
608 llvm::LLVMAddAnalysisPasses(tm, fpm);
609 llvm::LLVMAddAnalysisPasses(tm, mpm);
610 let opt_level = to_llvm_opt_settings(opt_level).0;
611 let prepare_for_thin_lto = cgcx.lto == Lto::Thin
612 || cgcx.lto == Lto::ThinLocal
613 || (cgcx.lto != Lto::Fat && cgcx.opts.cg.linker_plugin_lto.enabled());
614 with_llvm_pmb(llmod, config, opt_level, prepare_for_thin_lto, &mut |b| {
615 llvm::LLVMRustAddLastExtensionPasses(
617 extra_passes.as_ptr(),
618 extra_passes.len() as size_t,
620 llvm::LLVMRustPassManagerBuilderPopulateFunctionPassManager(b, fpm);
621 llvm::LLVMRustPassManagerBuilderPopulateModulePassManager(b, mpm);
624 have_name_anon_globals_pass = have_name_anon_globals_pass || prepare_for_thin_lto;
625 if using_thin_buffers && !prepare_for_thin_lto {
626 llvm::LLVMRustAddPass(mpm, find_pass("name-anon-globals").unwrap());
627 have_name_anon_globals_pass = true;
630 // If we don't use the standard pipeline, directly populate the MPM
631 // with the extra passes.
632 for pass in extra_passes {
633 llvm::LLVMRustAddPass(mpm, pass);
637 if using_thin_buffers && !have_name_anon_globals_pass {
638 // As described above, this will probably cause an error in LLVM
639 if config.no_prepopulate_passes {
641 "The current compilation is going to use thin LTO buffers \
642 without running LLVM's NameAnonGlobals pass. \
643 This will likely cause errors in LLVM. Consider adding \
644 -C passes=name-anon-globals to the compiler command line.",
648 "We are using thin LTO buffers without running the NameAnonGlobals pass. \
649 This will likely cause errors in LLVM and should never happen."
655 diag_handler.abort_if_errors();
657 // Finally, run the actual optimization passes
659 let _timer = cgcx.prof.extra_verbose_generic_activity(
660 "LLVM_module_optimize_function_passes",
663 llvm::LLVMRustRunFunctionPassManager(fpm, llmod);
666 let _timer = cgcx.prof.extra_verbose_generic_activity(
667 "LLVM_module_optimize_module_passes",
670 llvm::LLVMRunPassManager(mpm, llmod);
673 // Deallocate managers that we're now done with
674 llvm::LLVMDisposePassManager(fpm);
675 llvm::LLVMDisposePassManager(mpm);
680 unsafe fn add_sanitizer_passes(config: &ModuleConfig, passes: &mut Vec<&'static mut llvm::Pass>) {
681 if config.sanitizer.contains(SanitizerSet::ADDRESS) {
682 let recover = config.sanitizer_recover.contains(SanitizerSet::ADDRESS);
683 passes.push(llvm::LLVMRustCreateAddressSanitizerFunctionPass(recover));
684 passes.push(llvm::LLVMRustCreateModuleAddressSanitizerPass(recover));
686 if config.sanitizer.contains(SanitizerSet::MEMORY) {
687 let track_origins = config.sanitizer_memory_track_origins as c_int;
688 let recover = config.sanitizer_recover.contains(SanitizerSet::MEMORY);
689 passes.push(llvm::LLVMRustCreateMemorySanitizerPass(track_origins, recover));
691 if config.sanitizer.contains(SanitizerSet::THREAD) {
692 passes.push(llvm::LLVMRustCreateThreadSanitizerPass());
694 if config.sanitizer.contains(SanitizerSet::HWADDRESS) {
695 let recover = config.sanitizer_recover.contains(SanitizerSet::HWADDRESS);
696 passes.push(llvm::LLVMRustCreateHWAddressSanitizerPass(recover));
701 cgcx: &CodegenContext<LlvmCodegenBackend>,
702 diag_handler: &Handler,
703 mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
704 ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
705 use super::lto::{Linker, ModuleBuffer};
706 // Sort the modules by name to ensure to ensure deterministic behavior.
707 modules.sort_by(|a, b| a.name.cmp(&b.name));
708 let (first, elements) =
709 modules.split_first().expect("Bug! modules must contain at least one module.");
711 let mut linker = Linker::new(first.module_llvm.llmod());
712 for module in elements {
713 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_link_module", &*module.name);
714 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
715 linker.add(buffer.data()).map_err(|()| {
716 let msg = format!("failed to serialize module {:?}", module.name);
717 llvm_err(diag_handler, &msg)
721 Ok(modules.remove(0))
724 pub(crate) unsafe fn codegen(
725 cgcx: &CodegenContext<LlvmCodegenBackend>,
726 diag_handler: &Handler,
727 module: ModuleCodegen<ModuleLlvm>,
728 config: &ModuleConfig,
729 ) -> Result<CompiledModule, FatalError> {
730 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_module_codegen", &*module.name);
732 let llmod = module.module_llvm.llmod();
733 let llcx = &*module.module_llvm.llcx;
734 let tm = &*module.module_llvm.tm;
735 let module_name = module.name.clone();
736 let module_name = Some(&module_name[..]);
737 let handlers = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
739 if cgcx.msvc_imps_needed {
740 create_msvc_imps(cgcx, llcx, llmod);
743 // A codegen-specific pass manager is used to generate object
744 // files for an LLVM module.
746 // Apparently each of these pass managers is a one-shot kind of
747 // thing, so we create a new one for each type of output. The
748 // pass manager passed to the closure should be ensured to not
749 // escape the closure itself, and the manager should only be
751 unsafe fn with_codegen<'ll, F, R>(
752 tm: &'ll llvm::TargetMachine,
753 llmod: &'ll llvm::Module,
758 F: FnOnce(&'ll mut PassManager<'ll>) -> R,
760 let cpm = llvm::LLVMCreatePassManager();
761 llvm::LLVMAddAnalysisPasses(tm, cpm);
762 llvm::LLVMRustAddLibraryInfo(cpm, llmod, no_builtins);
766 // Two things to note:
767 // - If object files are just LLVM bitcode we write bitcode, copy it to
768 // the .o file, and delete the bitcode if it wasn't otherwise
770 // - If we don't have the integrated assembler then we need to emit
771 // asm from LLVM and use `gcc` to create the object file.
773 let bc_out = cgcx.output_filenames.temp_path(OutputType::Bitcode, module_name);
774 let obj_out = cgcx.output_filenames.temp_path(OutputType::Object, module_name);
776 if config.bitcode_needed() {
779 .generic_activity_with_arg("LLVM_module_codegen_make_bitcode", &*module.name);
780 let thin = ThinBuffer::new(llmod, config.emit_thin_lto);
781 let data = thin.data();
783 if let Some(bitcode_filename) = bc_out.file_name() {
784 cgcx.prof.artifact_size(
786 bitcode_filename.to_string_lossy(),
791 if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
794 .generic_activity_with_arg("LLVM_module_codegen_emit_bitcode", &*module.name);
795 if let Err(e) = fs::write(&bc_out, data) {
796 let msg = format!("failed to write bytecode to {}: {}", bc_out.display(), e);
797 diag_handler.err(&msg);
801 if config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full) {
804 .generic_activity_with_arg("LLVM_module_codegen_embed_bitcode", &*module.name);
805 embed_bitcode(cgcx, llcx, llmod, &config.bc_cmdline, data);
811 cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_ir", &*module.name);
812 let out = cgcx.output_filenames.temp_path(OutputType::LlvmAssembly, module_name);
813 let out_c = path_to_c_string(&out);
815 extern "C" fn demangle_callback(
816 input_ptr: *const c_char,
818 output_ptr: *mut c_char,
822 unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
824 let Ok(input) = str::from_utf8(input) else { return 0 };
826 let output = unsafe {
827 slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
829 let mut cursor = io::Cursor::new(output);
831 let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 };
833 if write!(cursor, "{:#}", demangled).is_err() {
834 // Possible only if provided buffer is not big enough
838 cursor.position() as size_t
841 let result = llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback);
843 if result == llvm::LLVMRustResult::Success {
844 record_artifact_size(&cgcx.prof, "llvm_ir", &out);
847 result.into_result().map_err(|()| {
848 let msg = format!("failed to write LLVM IR to {}", out.display());
849 llvm_err(diag_handler, &msg)
855 cgcx.prof.generic_activity_with_arg("LLVM_module_codegen_emit_asm", &*module.name);
856 let path = cgcx.output_filenames.temp_path(OutputType::Assembly, module_name);
858 // We can't use the same module for asm and object code output,
859 // because that triggers various errors like invalid IR or broken
860 // binaries. So we must clone the module to produce the asm output
861 // if we are also producing object code.
862 let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
863 llvm::LLVMCloneModule(llmod)
867 with_codegen(tm, llmod, config.no_builtins, |cpm| {
875 llvm::FileType::AssemblyFile,
881 match config.emit_obj {
882 EmitObj::ObjectCode(_) => {
885 .generic_activity_with_arg("LLVM_module_codegen_emit_obj", &*module.name);
887 let dwo_out = cgcx.output_filenames.temp_path_dwo(module_name);
888 let dwo_out = match (cgcx.split_debuginfo, cgcx.split_dwarf_kind) {
889 // Don't change how DWARF is emitted when disabled.
890 (SplitDebuginfo::Off, _) => None,
891 // Don't provide a DWARF object path if split debuginfo is enabled but this is
892 // a platform that doesn't support Split DWARF.
893 _ if !cgcx.target_can_use_split_dwarf => None,
894 // Don't provide a DWARF object path in single mode, sections will be written
895 // into the object as normal but ignored by linker.
896 (_, SplitDwarfKind::Single) => None,
897 // Emit (a subset of the) DWARF into a separate dwarf object file in split
899 (_, SplitDwarfKind::Split) => Some(dwo_out.as_path()),
902 with_codegen(tm, llmod, config.no_builtins, |cpm| {
910 llvm::FileType::ObjectFile,
916 EmitObj::Bitcode => {
917 debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
918 if let Err(e) = link_or_copy(&bc_out, &obj_out) {
919 diag_handler.err(&format!("failed to copy bitcode to object file: {}", e));
923 debug!("removing_bitcode {:?}", bc_out);
924 ensure_removed(diag_handler, &bc_out);
934 Ok(module.into_compiled_module(
935 config.emit_obj != EmitObj::None,
936 cgcx.target_can_use_split_dwarf
937 && cgcx.split_debuginfo != SplitDebuginfo::Off
938 && cgcx.split_dwarf_kind == SplitDwarfKind::Split,
940 &cgcx.output_filenames,
944 fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: &[u8]) -> Vec<u8> {
945 let mut asm = format!(".section {},\"{}\"\n", section_name, section_flags).into_bytes();
946 asm.extend_from_slice(b".ascii \"");
947 asm.reserve(data.len());
949 if byte == b'\\' || byte == b'"' {
952 } else if byte < 0x20 || byte >= 0x80 {
953 // Avoid non UTF-8 inline assembly. Use octal escape sequence, because it is fixed
954 // width, while hex escapes will consume following characters.
956 asm.push(b'0' + ((byte >> 6) & 0x7));
957 asm.push(b'0' + ((byte >> 3) & 0x7));
958 asm.push(b'0' + ((byte >> 0) & 0x7));
963 asm.extend_from_slice(b"\"\n");
967 /// Embed the bitcode of an LLVM module in the LLVM module itself.
969 /// This is done primarily for iOS where it appears to be standard to compile C
970 /// code at least with `-fembed-bitcode` which creates two sections in the
973 /// * __LLVM,__bitcode
974 /// * __LLVM,__cmdline
976 /// It appears *both* of these sections are necessary to get the linker to
977 /// recognize what's going on. A suitable cmdline value is taken from the
980 /// Furthermore debug/O1 builds don't actually embed bitcode but rather just
981 /// embed an empty section.
983 /// Basically all of this is us attempting to follow in the footsteps of clang
984 /// on iOS. See #35968 for lots more info.
985 unsafe fn embed_bitcode(
986 cgcx: &CodegenContext<LlvmCodegenBackend>,
987 llcx: &llvm::Context,
988 llmod: &llvm::Module,
992 // We're adding custom sections to the output object file, but we definitely
993 // do not want these custom sections to make their way into the final linked
994 // executable. The purpose of these custom sections is for tooling
995 // surrounding object files to work with the LLVM IR, if necessary. For
996 // example rustc's own LTO will look for LLVM IR inside of the object file
997 // in these sections by default.
999 // To handle this is a bit different depending on the object file format
1000 // used by the backend, broken down into a few different categories:
1002 // * Mach-O - this is for macOS. Inspecting the source code for the native
1003 // linker here shows that the `.llvmbc` and `.llvmcmd` sections are
1004 // automatically skipped by the linker. In that case there's nothing extra
1005 // that we need to do here.
1007 // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
1008 // `.llvmcmd` sections, so there's nothing extra we need to do.
1010 // * COFF - if we don't do anything the linker will by default copy all
1011 // these sections to the output artifact, not what we want! To subvert
1012 // this we want to flag the sections we inserted here as
1013 // `IMAGE_SCN_LNK_REMOVE`.
1015 // * ELF - this is very similar to COFF above. One difference is that these
1016 // sections are removed from the output linked artifact when
1017 // `--gc-sections` is passed, which we pass by default. If that flag isn't
1018 // passed though then these sections will show up in the final output.
1019 // Additionally the flag that we need to set here is `SHF_EXCLUDE`.
1021 // Unfortunately, LLVM provides no way to set custom section flags. For ELF
1022 // and COFF we emit the sections using module level inline assembly for that
1023 // reason (see issue #90326 for historical background).
1024 let is_apple = cgcx.opts.target_triple.triple().contains("-ios")
1025 || cgcx.opts.target_triple.triple().contains("-darwin")
1026 || cgcx.opts.target_triple.triple().contains("-tvos")
1027 || cgcx.opts.target_triple.triple().contains("-watchos");
1029 || cgcx.opts.target_triple.triple().starts_with("wasm")
1030 || cgcx.opts.target_triple.triple().starts_with("asmjs")
1032 // We don't need custom section flags, create LLVM globals.
1033 let llconst = common::bytes_in_context(llcx, bitcode);
1034 let llglobal = llvm::LLVMAddGlobal(
1036 common::val_ty(llconst),
1037 "rustc.embedded.module\0".as_ptr().cast(),
1039 llvm::LLVMSetInitializer(llglobal, llconst);
1041 let section = if is_apple { "__LLVM,__bitcode\0" } else { ".llvmbc\0" };
1042 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
1043 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
1044 llvm::LLVMSetGlobalConstant(llglobal, llvm::True);
1046 let llconst = common::bytes_in_context(llcx, cmdline.as_bytes());
1047 let llglobal = llvm::LLVMAddGlobal(
1049 common::val_ty(llconst),
1050 "rustc.embedded.cmdline\0".as_ptr().cast(),
1052 llvm::LLVMSetInitializer(llglobal, llconst);
1053 let section = if is_apple { "__LLVM,__cmdline\0" } else { ".llvmcmd\0" };
1054 llvm::LLVMSetSection(llglobal, section.as_ptr().cast());
1055 llvm::LLVMRustSetLinkage(llglobal, llvm::Linkage::PrivateLinkage);
1057 // We need custom section flags, so emit module-level inline assembly.
1058 let section_flags = if cgcx.is_pe_coff { "n" } else { "e" };
1059 let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode);
1060 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
1061 let asm = create_section_with_flags_asm(".llvmcmd", section_flags, cmdline.as_bytes());
1062 llvm::LLVMRustAppendModuleInlineAsm(llmod, asm.as_ptr().cast(), asm.len());
1066 pub unsafe fn with_llvm_pmb(
1067 llmod: &llvm::Module,
1068 config: &ModuleConfig,
1069 opt_level: llvm::CodeGenOptLevel,
1070 prepare_for_thin_lto: bool,
1071 f: &mut dyn FnMut(&llvm::PassManagerBuilder),
1075 // Create the PassManagerBuilder for LLVM. We configure it with
1076 // reasonable defaults and prepare it to actually populate the pass
1078 let builder = llvm::LLVMRustPassManagerBuilderCreate();
1079 let opt_size = config.opt_size.map_or(llvm::CodeGenOptSizeNone, |x| to_llvm_opt_settings(x).1);
1080 let inline_threshold = config.inline_threshold;
1081 let pgo_gen_path = get_pgo_gen_path(config);
1082 let pgo_use_path = get_pgo_use_path(config);
1083 let pgo_sample_use_path = get_pgo_sample_use_path(config);
1085 llvm::LLVMRustConfigurePassManagerBuilder(
1088 config.merge_functions,
1089 config.vectorize_slp,
1090 config.vectorize_loop,
1091 prepare_for_thin_lto,
1092 pgo_gen_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1093 pgo_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1094 pgo_sample_use_path.as_ref().map_or(ptr::null(), |s| s.as_ptr()),
1098 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod, config.no_builtins);
1100 // Here we match what clang does (kinda). For O0 we only inline
1101 // always-inline functions (but don't add lifetime intrinsics), at O1 we
1102 // inline with lifetime intrinsics, and O2+ we add an inliner with a
1103 // thresholds copied from clang.
1104 match (opt_level, opt_size, inline_threshold) {
1106 llvm::LLVMRustPassManagerBuilderUseInlinerWithThreshold(builder, t);
1108 (llvm::CodeGenOptLevel::Aggressive, ..) => {
1109 llvm::LLVMRustPassManagerBuilderUseInlinerWithThreshold(builder, 275);
1111 (_, llvm::CodeGenOptSizeDefault, _) => {
1112 llvm::LLVMRustPassManagerBuilderUseInlinerWithThreshold(builder, 75);
1114 (_, llvm::CodeGenOptSizeAggressive, _) => {
1115 llvm::LLVMRustPassManagerBuilderUseInlinerWithThreshold(builder, 25);
1117 (llvm::CodeGenOptLevel::None, ..) => {
1118 llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1120 (llvm::CodeGenOptLevel::Less, ..) => {
1121 llvm::LLVMRustAddAlwaysInlinePass(builder, config.emit_lifetime_markers);
1123 (llvm::CodeGenOptLevel::Default, ..) => {
1124 llvm::LLVMRustPassManagerBuilderUseInlinerWithThreshold(builder, 225);
1129 llvm::LLVMRustPassManagerBuilderDispose(builder);
1132 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1133 // This is required to satisfy `dllimport` references to static data in .rlibs
1134 // when using MSVC linker. We do this only for data, as linker can fix up
1135 // code references on its own.
1136 // See #26591, #27438
1137 fn create_msvc_imps(
1138 cgcx: &CodegenContext<LlvmCodegenBackend>,
1139 llcx: &llvm::Context,
1140 llmod: &llvm::Module,
1142 if !cgcx.msvc_imps_needed {
1145 // The x86 ABI seems to require that leading underscores are added to symbol
1146 // names, so we need an extra underscore on x86. There's also a leading
1147 // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
1148 // underscores added in front).
1149 let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
1152 let i8p_ty = Type::i8p_llcx(llcx);
1153 let globals = base::iter_globals(llmod)
1155 llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage
1156 && llvm::LLVMIsDeclaration(val) == 0
1159 // Exclude some symbols that we know are not Rust symbols.
1160 let name = llvm::get_value_name(val);
1161 if ignored(name) { None } else { Some((val, name)) }
1163 .map(move |(val, name)| {
1164 let mut imp_name = prefix.as_bytes().to_vec();
1165 imp_name.extend(name);
1166 let imp_name = CString::new(imp_name).unwrap();
1169 .collect::<Vec<_>>();
1171 for (imp_name, val) in globals {
1172 let imp = llvm::LLVMAddGlobal(llmod, i8p_ty, imp_name.as_ptr().cast());
1173 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
1174 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
1178 // Use this function to exclude certain symbols from `__imp` generation.
1179 fn ignored(symbol_name: &[u8]) -> bool {
1180 // These are symbols generated by LLVM's profiling instrumentation
1181 symbol_name.starts_with(b"__llvm_profile_")
1185 fn record_artifact_size(
1186 self_profiler_ref: &SelfProfilerRef,
1187 artifact_kind: &'static str,
1190 // Don't stat the file if we are not going to record its size.
1191 if !self_profiler_ref.enabled() {
1195 if let Some(artifact_name) = path.file_name() {
1196 let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
1197 self_profiler_ref.artifact_size(artifact_kind, artifact_name.to_string_lossy(), file_size);