Skip to main content

rustc_codegen_llvm/back/
write.rs

1use std::ffi::{CStr, CString};
2use std::io::{self, Write};
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::{fs, slice, str};
6
7use libc::{c_char, c_int, c_void, size_t};
8use rustc_codegen_ssa::back::link::ensure_removed;
9use rustc_codegen_ssa::back::versioned_llvm_target;
10use rustc_codegen_ssa::back::write::{
11    BitcodeSection, CodegenContext, EmitObj, InlineAsmError, ModuleConfig, SharedEmitter,
12    TargetMachineFactoryConfig, TargetMachineFactoryFn,
13};
14use rustc_codegen_ssa::base::wants_wasm_eh;
15use rustc_codegen_ssa::common::TypeKind;
16use rustc_codegen_ssa::traits::*;
17use rustc_codegen_ssa::{CompiledModule, ModuleCodegen, ModuleKind};
18use rustc_data_structures::profiling::SelfProfilerRef;
19use rustc_data_structures::small_c_str::SmallCStr;
20use rustc_errors::{DiagCtxt, DiagCtxtHandle, Level};
21use rustc_fs_util::{link_or_copy, path_to_c_string};
22use rustc_middle::ty::TyCtxt;
23use rustc_session::Session;
24use rustc_session::config::{self, Lto, OutputType, Passes, SplitDwarfKind, SwitchWithOptPath};
25use rustc_span::{BytePos, InnerSpan, Pos, RemapPathScopeComponents, SpanData, SyntaxContext, sym};
26use rustc_target::spec::{
27    Arch, CodeModel, FloatAbi, RelocModel, SanitizerSet, SplitDebuginfo, TlsModel,
28};
29use tracing::{debug, trace};
30
31use crate::back::lto::{Buffer, ModuleBuffer};
32use crate::back::owned_target_machine::OwnedTargetMachine;
33use crate::back::profiling::{
34    LlvmSelfProfiler, selfprofile_after_pass_callback, selfprofile_before_pass_callback,
35};
36use crate::builder::SBuilder;
37use crate::builder::gpu_offload::scalar_width;
38use crate::common::AsCCharPtr;
39use crate::errors::{
40    CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, ParseTargetMachineConfig,
41    UnknownCompression, WithLlvmError, WriteBytecode,
42};
43use crate::llvm::diagnostic::OptimizationDiagnosticKind::*;
44use crate::llvm::{self, DiagnosticInfo};
45use crate::type_::llvm_type_ptr;
46use crate::{LlvmCodegenBackend, ModuleLlvm, SimpleCx, attributes, base, common, llvm_util};
47
48pub(crate) fn llvm_err<'a>(dcx: DiagCtxtHandle<'_>, err: LlvmError<'a>) -> ! {
49    match llvm::last_error() {
50        Some(llvm_err) => dcx.emit_fatal(WithLlvmError(err, llvm_err)),
51        None => dcx.emit_fatal(err),
52    }
53}
54
55fn write_output_file<'ll>(
56    dcx: DiagCtxtHandle<'_>,
57    target: &'ll llvm::TargetMachine,
58    no_builtins: bool,
59    m: &'ll llvm::Module,
60    output: &Path,
61    dwo_output: Option<&Path>,
62    file_type: llvm::FileType,
63    self_profiler_ref: &SelfProfilerRef,
64    verify_llvm_ir: bool,
65) {
66    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/write.rs:66",
                        "rustc_codegen_llvm::back::write", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/write.rs"),
                        ::tracing_core::__macro_support::Option::Some(66u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::write"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("write_output_file output={0:?} dwo_output={1:?}",
                                                    output, dwo_output) as &dyn Value))])
            });
    } else { ; }
};debug!("write_output_file output={:?} dwo_output={:?}", output, dwo_output);
67    let output_c = path_to_c_string(output);
68    let dwo_output_c;
69    let dwo_output_ptr = if let Some(dwo_output) = dwo_output {
70        dwo_output_c = path_to_c_string(dwo_output);
71        dwo_output_c.as_ptr()
72    } else {
73        std::ptr::null()
74    };
75    let result = unsafe {
76        let pm = llvm::LLVMCreatePassManager();
77        llvm::LLVMAddAnalysisPasses(target, pm);
78        llvm::LLVMRustAddLibraryInfo(target, pm, m, no_builtins);
79        llvm::LLVMRustWriteOutputFile(
80            target,
81            pm,
82            m,
83            output_c.as_ptr(),
84            dwo_output_ptr,
85            file_type,
86            verify_llvm_ir,
87        )
88    };
89
90    // Record artifact sizes for self-profiling
91    if result == llvm::LLVMRustResult::Success {
92        let artifact_kind = match file_type {
93            llvm::FileType::ObjectFile => "object_file",
94            llvm::FileType::AssemblyFile => "assembly_file",
95        };
96        record_artifact_size(self_profiler_ref, artifact_kind, output);
97        if let Some(dwo_file) = dwo_output {
98            record_artifact_size(self_profiler_ref, "dwo_file", dwo_file);
99        }
100    }
101
102    result.into_result().unwrap_or_else(|()| llvm_err(dcx, LlvmError::WriteOutput { path: output }))
103}
104
105pub(crate) fn create_informational_target_machine(
106    sess: &Session,
107    only_base_features: bool,
108) -> OwnedTargetMachine {
109    let config = TargetMachineFactoryConfig { split_dwarf_file: None, output_obj_file: None };
110    // Can't use query system here quite yet because this function is invoked before the query
111    // system/tcx is set up.
112    let features = llvm_util::global_llvm_features(sess, only_base_features);
113    target_machine_factory(sess, config::OptLevel::No, &features)(sess.dcx(), config)
114}
115
116pub(crate) fn create_target_machine(tcx: TyCtxt<'_>, mod_name: &str) -> OwnedTargetMachine {
117    let split_dwarf_file = if tcx.sess.target_can_use_split_dwarf() {
118        tcx.output_filenames(()).split_dwarf_path(
119            tcx.sess.split_debuginfo(),
120            tcx.sess.opts.unstable_opts.split_dwarf_kind,
121            mod_name,
122            tcx.sess.invocation_temp.as_deref(),
123        )
124    } else {
125        None
126    };
127
128    let output_obj_file = Some(tcx.output_filenames(()).temp_path_for_cgu(
129        OutputType::Object,
130        mod_name,
131        tcx.sess.invocation_temp.as_deref(),
132    ));
133    let config = TargetMachineFactoryConfig { split_dwarf_file, output_obj_file };
134
135    target_machine_factory(
136        tcx.sess,
137        tcx.backend_optimization_level(()),
138        tcx.global_backend_features(()),
139    )(tcx.dcx(), config)
140}
141
142fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) {
143    use self::config::OptLevel::*;
144    match cfg {
145        No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
146        Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
147        More => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeNone),
148        Aggressive => (llvm::CodeGenOptLevel::Aggressive, llvm::CodeGenOptSizeNone),
149        Size => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeDefault),
150        SizeMin => (llvm::CodeGenOptLevel::Default, llvm::CodeGenOptSizeAggressive),
151    }
152}
153
154fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel {
155    use config::OptLevel::*;
156    match cfg {
157        No => llvm::PassBuilderOptLevel::O0,
158        Less => llvm::PassBuilderOptLevel::O1,
159        More => llvm::PassBuilderOptLevel::O2,
160        Aggressive => llvm::PassBuilderOptLevel::O3,
161        Size => llvm::PassBuilderOptLevel::Os,
162        SizeMin => llvm::PassBuilderOptLevel::Oz,
163    }
164}
165
166fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocModel {
167    match relocation_model {
168        RelocModel::Static => llvm::RelocModel::Static,
169        // LLVM doesn't have a PIE relocation model, it represents PIE as PIC with an extra
170        // attribute.
171        RelocModel::Pic | RelocModel::Pie => llvm::RelocModel::PIC,
172        RelocModel::DynamicNoPic => llvm::RelocModel::DynamicNoPic,
173        RelocModel::Ropi => llvm::RelocModel::ROPI,
174        RelocModel::Rwpi => llvm::RelocModel::RWPI,
175        RelocModel::RopiRwpi => llvm::RelocModel::ROPI_RWPI,
176    }
177}
178
179pub(crate) fn to_llvm_code_model(code_model: Option<CodeModel>) -> llvm::CodeModel {
180    match code_model {
181        Some(CodeModel::Tiny) => llvm::CodeModel::Tiny,
182        Some(CodeModel::Small) => llvm::CodeModel::Small,
183        Some(CodeModel::Kernel) => llvm::CodeModel::Kernel,
184        Some(CodeModel::Medium) => llvm::CodeModel::Medium,
185        Some(CodeModel::Large) => llvm::CodeModel::Large,
186        None => llvm::CodeModel::None,
187    }
188}
189
190fn to_llvm_float_abi(float_abi: Option<FloatAbi>) -> llvm::FloatAbi {
191    match float_abi {
192        None => llvm::FloatAbi::Default,
193        Some(FloatAbi::Soft) => llvm::FloatAbi::Soft,
194        Some(FloatAbi::Hard) => llvm::FloatAbi::Hard,
195    }
196}
197
198pub(crate) fn target_machine_factory(
199    sess: &Session,
200    optlvl: config::OptLevel,
201    target_features: &[String],
202) -> TargetMachineFactoryFn<LlvmCodegenBackend> {
203    // Self-profile timer for creating a _factory_.
204    let _prof_timer = sess.prof.generic_activity("target_machine_factory");
205
206    let reloc_model = to_llvm_relocation_model(sess.relocation_model());
207
208    let (opt_level, _) = to_llvm_opt_settings(optlvl);
209    let float_abi = if sess.target.arch == Arch::Arm && sess.opts.cg.soft_float {
210        llvm::FloatAbi::Soft
211    } else {
212        // `validate_commandline_args_with_session_available` has already warned about this being
213        // ignored. Let's make sure LLVM doesn't suddenly start using this flag on more targets.
214        to_llvm_float_abi(sess.target.llvm_floatabi)
215    };
216
217    let ffunction_sections =
218        sess.opts.unstable_opts.function_sections.unwrap_or(sess.target.function_sections);
219    let fdata_sections = ffunction_sections;
220    let funique_section_names = !sess.opts.unstable_opts.no_unique_section_names;
221
222    let code_model = to_llvm_code_model(sess.code_model());
223
224    let mut singlethread = sess.target.singlethread;
225
226    // On the wasm target once the `atomics` feature is enabled that means that
227    // we're no longer single-threaded, or otherwise we don't want LLVM to
228    // lower atomic operations to single-threaded operations.
229    if singlethread && sess.target.is_like_wasm && sess.target_features.contains(&sym::atomics) {
230        singlethread = false;
231    }
232
233    let triple = SmallCStr::new(&versioned_llvm_target(sess));
234    let cpu = SmallCStr::new(llvm_util::target_cpu(sess));
235    let features = CString::new(target_features.join(",")).unwrap();
236    let abi = SmallCStr::new(&sess.target.llvm_abiname);
237    let trap_unreachable =
238        sess.opts.unstable_opts.trap_unreachable.unwrap_or(sess.target.trap_unreachable);
239    let emit_stack_size_section = sess.opts.unstable_opts.emit_stack_sizes;
240
241    let verbose_asm = sess.opts.unstable_opts.verbose_asm;
242    let relax_elf_relocations =
243        sess.opts.unstable_opts.relax_elf_relocations.unwrap_or(sess.target.relax_elf_relocations);
244
245    let use_init_array =
246        !sess.opts.unstable_opts.use_ctors_section.unwrap_or(sess.target.use_ctors_section);
247
248    let path_mapping = sess.source_map().path_mapping().clone();
249    let working_dir = sess.source_map().working_dir().clone();
250
251    let use_emulated_tls = #[allow(non_exhaustive_omitted_patterns)] match sess.tls_model() {
    TlsModel::Emulated => true,
    _ => false,
}matches!(sess.tls_model(), TlsModel::Emulated);
252
253    let debuginfo_compression = match sess.opts.unstable_opts.debuginfo_compression {
254        config::DebugInfoCompression::None => llvm::CompressionKind::None,
255        config::DebugInfoCompression::Zlib => {
256            if llvm::LLVMRustLLVMHasZlibCompression() {
257                llvm::CompressionKind::Zlib
258            } else {
259                sess.dcx().emit_warn(UnknownCompression { algorithm: "zlib" });
260                llvm::CompressionKind::None
261            }
262        }
263        config::DebugInfoCompression::Zstd => {
264            if llvm::LLVMRustLLVMHasZstdCompression() {
265                llvm::CompressionKind::Zstd
266            } else {
267                sess.dcx().emit_warn(UnknownCompression { algorithm: "zstd" });
268                llvm::CompressionKind::None
269            }
270        }
271    };
272
273    let use_wasm_eh = wants_wasm_eh(sess);
274
275    let large_data_threshold = sess.opts.unstable_opts.large_data_threshold.unwrap_or(0);
276
277    let prof = SelfProfilerRef::clone(&sess.prof);
278    Arc::new(move |dcx: DiagCtxtHandle<'_>, config: TargetMachineFactoryConfig| {
279        // Self-profile timer for invoking a factory to create a target machine.
280        let _prof_timer = prof.generic_activity("target_machine_factory_inner");
281
282        let path_to_cstring_helper = |path: Option<PathBuf>| -> CString {
283            let path = path.unwrap_or_default();
284            let path = path_mapping
285                .to_real_filename(&working_dir, path)
286                .path(RemapPathScopeComponents::DEBUGINFO)
287                .to_string_lossy()
288                .into_owned();
289            CString::new(path).unwrap()
290        };
291
292        let split_dwarf_file = path_to_cstring_helper(config.split_dwarf_file);
293        let output_obj_file = path_to_cstring_helper(config.output_obj_file);
294
295        OwnedTargetMachine::new(
296            &triple,
297            &cpu,
298            &features,
299            &abi,
300            code_model,
301            reloc_model,
302            opt_level,
303            float_abi,
304            ffunction_sections,
305            fdata_sections,
306            funique_section_names,
307            trap_unreachable,
308            singlethread,
309            verbose_asm,
310            emit_stack_size_section,
311            relax_elf_relocations,
312            use_init_array,
313            &split_dwarf_file,
314            &output_obj_file,
315            debuginfo_compression,
316            use_emulated_tls,
317            use_wasm_eh,
318            large_data_threshold,
319        )
320        .unwrap_or_else(|err| dcx.emit_fatal(ParseTargetMachineConfig(err)))
321    })
322}
323
324pub(crate) fn save_temp_bitcode(
325    cgcx: &CodegenContext,
326    module: &ModuleCodegen<ModuleLlvm>,
327    name: &str,
328) {
329    if !cgcx.save_temps {
330        return;
331    }
332    let ext = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.bc", name))
    })format!("{name}.bc");
333    let path = cgcx.output_filenames.temp_path_ext_for_cgu(
334        &ext,
335        &module.name,
336        cgcx.invocation_temp.as_deref(),
337    );
338    write_bitcode_to_file(module, &path)
339}
340
341fn write_bitcode_to_file(module: &ModuleCodegen<ModuleLlvm>, path: &Path) {
342    unsafe {
343        let path = path_to_c_string(&path);
344        let llmod = module.module_llvm.llmod();
345        llvm::LLVMWriteBitcodeToFile(llmod, path.as_ptr());
346    }
347}
348
349/// In what context is a diagnostic handler being attached to a codegen unit?
350pub(crate) enum CodegenDiagnosticsStage {
351    /// Prelink optimization stage.
352    Opt,
353    /// LTO/ThinLTO postlink optimization stage.
354    LTO,
355    /// Code generation.
356    Codegen,
357}
358
359pub(crate) struct DiagnosticHandlers<'a> {
360    data: *mut (&'a CodegenContext, &'a SharedEmitter),
361    llcx: &'a llvm::Context,
362    old_handler: Option<&'a llvm::DiagnosticHandler>,
363}
364
365impl<'a> DiagnosticHandlers<'a> {
366    pub(crate) fn new(
367        cgcx: &'a CodegenContext,
368        shared_emitter: &'a SharedEmitter,
369        llcx: &'a llvm::Context,
370        module: &ModuleCodegen<ModuleLlvm>,
371        stage: CodegenDiagnosticsStage,
372    ) -> Self {
373        let remark_passes_all: bool;
374        let remark_passes: Vec<CString>;
375        match &cgcx.remark {
376            Passes::All => {
377                remark_passes_all = true;
378                remark_passes = Vec::new();
379            }
380            Passes::Some(passes) => {
381                remark_passes_all = false;
382                remark_passes =
383                    passes.iter().map(|name| CString::new(name.as_str()).unwrap()).collect();
384            }
385        };
386        let remark_passes: Vec<*const c_char> =
387            remark_passes.iter().map(|name: &CString| name.as_ptr()).collect();
388        let remark_file = cgcx
389            .remark_dir
390            .as_ref()
391            // Use the .opt.yaml file suffix, which is supported by LLVM's opt-viewer.
392            .map(|dir| {
393                let stage_suffix = match stage {
394                    CodegenDiagnosticsStage::Codegen => "codegen",
395                    CodegenDiagnosticsStage::Opt => "opt",
396                    CodegenDiagnosticsStage::LTO => "lto",
397                };
398                dir.join(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.{1}.opt.yaml", module.name,
                stage_suffix))
    })format!("{}.{stage_suffix}.opt.yaml", module.name))
399            })
400            .and_then(|dir| dir.to_str().and_then(|p| CString::new(p).ok()));
401
402        let pgo_available = cgcx.module_config.pgo_use.is_some();
403        let data = Box::into_raw(Box::new((cgcx, shared_emitter)));
404        unsafe {
405            let old_handler = llvm::LLVMRustContextGetDiagnosticHandler(llcx);
406            llvm::LLVMRustContextConfigureDiagnosticHandler(
407                llcx,
408                diagnostic_handler,
409                data.cast(),
410                remark_passes_all,
411                remark_passes.as_ptr(),
412                remark_passes.len(),
413                // The `as_ref()` is important here, otherwise the `CString` will be dropped
414                // too soon!
415                remark_file.as_ref().map(|dir| dir.as_ptr()).unwrap_or(std::ptr::null()),
416                pgo_available,
417            );
418            DiagnosticHandlers { data, llcx, old_handler }
419        }
420    }
421}
422
423impl<'a> Drop for DiagnosticHandlers<'a> {
424    fn drop(&mut self) {
425        unsafe {
426            llvm::LLVMRustContextSetDiagnosticHandler(self.llcx, self.old_handler);
427            drop(Box::from_raw(self.data));
428        }
429    }
430}
431
432fn report_inline_asm(
433    cgcx: &CodegenContext,
434    msg: String,
435    level: llvm::DiagnosticLevel,
436    cookie: u64,
437    source: Option<(String, Vec<InnerSpan>)>,
438) -> InlineAsmError {
439    // In LTO build we may get srcloc values from other crates which are invalid
440    // since they use a different source map. To be safe we just suppress these
441    // in LTO builds.
442    let span = if cookie == 0 || #[allow(non_exhaustive_omitted_patterns)] match cgcx.lto {
    Lto::Fat | Lto::Thin => true,
    _ => false,
}matches!(cgcx.lto, Lto::Fat | Lto::Thin) {
443        SpanData::default()
444    } else {
445        SpanData {
446            lo: BytePos::from_u32(cookie as u32),
447            hi: BytePos::from_u32((cookie >> 32) as u32),
448            ctxt: SyntaxContext::root(),
449            parent: None,
450        }
451    };
452    let level = match level {
453        llvm::DiagnosticLevel::Error => Level::Error,
454        llvm::DiagnosticLevel::Warning => Level::Warning,
455        llvm::DiagnosticLevel::Note | llvm::DiagnosticLevel::Remark => Level::Note,
456    };
457    let msg = msg.trim_prefix("error: ").to_string();
458    InlineAsmError { span, msg, level, source }
459}
460
461unsafe extern "C" fn diagnostic_handler(info: &DiagnosticInfo, user: *mut c_void) {
462    if user.is_null() {
463        return;
464    }
465    let (cgcx, shared_emitter) = unsafe { *(user as *const (&CodegenContext, &SharedEmitter)) };
466
467    let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
468    let dcx = dcx.handle();
469
470    match unsafe { llvm::diagnostic::Diagnostic::unpack(info) } {
471        llvm::diagnostic::InlineAsm(inline) => {
472            // FIXME use dcx
473            shared_emitter.inline_asm_error(report_inline_asm(
474                cgcx,
475                inline.message,
476                inline.level,
477                inline.cookie,
478                inline.source,
479            ));
480        }
481
482        llvm::diagnostic::Optimization(opt) => {
483            dcx.emit_note(FromLlvmOptimizationDiag {
484                filename: &opt.filename,
485                line: opt.line,
486                column: opt.column,
487                pass_name: &opt.pass_name,
488                kind: match opt.kind {
489                    OptimizationRemark => "success",
490                    OptimizationMissed | OptimizationFailure => "missed",
491                    OptimizationAnalysis
492                    | OptimizationAnalysisFPCommute
493                    | OptimizationAnalysisAliasing => "analysis",
494                    OptimizationRemarkOther => "other",
495                },
496                message: &opt.message,
497            });
498        }
499        llvm::diagnostic::PGO(diagnostic_ref) | llvm::diagnostic::Linker(diagnostic_ref) => {
500            let message = llvm::build_string(|s| unsafe {
501                llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
502            })
503            .expect("non-UTF8 diagnostic");
504            dcx.emit_warn(FromLlvmDiag { message });
505        }
506        llvm::diagnostic::Unsupported(diagnostic_ref) => {
507            let message = llvm::build_string(|s| unsafe {
508                llvm::LLVMRustWriteDiagnosticInfoToString(diagnostic_ref, s)
509            })
510            .expect("non-UTF8 diagnostic");
511            dcx.emit_err(FromLlvmDiag { message });
512        }
513        llvm::diagnostic::UnknownDiagnostic(..) => {}
514    }
515}
516
517fn get_pgo_gen_path(config: &ModuleConfig) -> Option<CString> {
518    match config.pgo_gen {
519        SwitchWithOptPath::Enabled(ref opt_dir_path) => {
520            let path = if let Some(dir_path) = opt_dir_path {
521                dir_path.join("default_%m.profraw")
522            } else {
523                PathBuf::from("default_%m.profraw")
524            };
525
526            Some(CString::new(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", path.display()))
    })format!("{}", path.display())).unwrap())
527        }
528        SwitchWithOptPath::Disabled => None,
529    }
530}
531
532fn get_pgo_use_path(config: &ModuleConfig) -> Option<CString> {
533    config
534        .pgo_use
535        .as_ref()
536        .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
537}
538
539fn get_pgo_sample_use_path(config: &ModuleConfig) -> Option<CString> {
540    config
541        .pgo_sample_use
542        .as_ref()
543        .map(|path_buf| CString::new(path_buf.to_string_lossy().as_bytes()).unwrap())
544}
545
546fn get_instr_profile_output_path(config: &ModuleConfig) -> Option<CString> {
547    config.instrument_coverage.then(|| c"default_%m_%p.profraw".to_owned())
548}
549
550// PreAD will run llvm opts but disable size increasing opts (vectorization, loop unrolling)
551// DuringAD is the same as above, but also runs the enzyme opt and autodiff passes.
552// PostAD will run all opts, including size increasing opts.
553#[derive(#[automatically_derived]
impl ::core::fmt::Debug for AutodiffStage {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                AutodiffStage::PreAD => "PreAD",
                AutodiffStage::DuringAD => "DuringAD",
                AutodiffStage::PostAD => "PostAD",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for AutodiffStage {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for AutodiffStage {
    #[inline]
    fn eq(&self, other: &AutodiffStage) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
554pub(crate) enum AutodiffStage {
555    PreAD,
556    DuringAD,
557    PostAD,
558}
559
560pub(crate) unsafe fn llvm_optimize(
561    cgcx: &CodegenContext,
562    prof: &SelfProfilerRef,
563    dcx: DiagCtxtHandle<'_>,
564    module: &ModuleCodegen<ModuleLlvm>,
565    thin_lto_buffer: Option<&mut Option<Buffer>>,
566    thin_lto_summary_buffer: Option<&mut Option<Buffer>>,
567    config: &ModuleConfig,
568    opt_level: config::OptLevel,
569    opt_stage: llvm::OptStage,
570    autodiff_stage: AutodiffStage,
571) {
572    // Enzyme:
573    // The whole point of compiler based AD is to differentiate optimized IR instead of unoptimized
574    // source code. However, benchmarks show that optimizations increasing the code size
575    // tend to reduce AD performance. Therefore deactivate them before AD, then differentiate the code
576    // and finally re-optimize the module, now with all optimizations available.
577    // FIXME(ZuseZ4): In a future update we could figure out how to only optimize individual functions getting
578    // differentiated.
579
580    let consider_ad = config.autodiff.contains(&config::AutoDiff::Enable);
581    let run_enzyme = autodiff_stage == AutodiffStage::DuringAD;
582    let print_before_enzyme = config.autodiff.contains(&config::AutoDiff::PrintModBefore);
583    let print_after_enzyme = config.autodiff.contains(&config::AutoDiff::PrintModAfter);
584    let print_passes = config.autodiff.contains(&config::AutoDiff::PrintPasses);
585    let merge_functions;
586    let unroll_loops;
587    let vectorize_slp;
588    let vectorize_loop;
589
590    // When we build rustc with enzyme/autodiff support, we want to postpone size-increasing
591    // optimizations until after differentiation. Our pipeline is thus: (opt + enzyme), (full opt).
592    // We therefore have two calls to llvm_optimize, if autodiff is used.
593    //
594    // We also must disable merge_functions, since autodiff placeholder/dummy bodies tend to be
595    // identical. We run opts before AD, so there is a chance that LLVM will merge our dummies.
596    // In that case, we lack some dummy bodies and can't replace them with the real AD code anymore.
597    // We then would need to abort compilation. This was especially common in test cases.
598    if consider_ad && autodiff_stage != AutodiffStage::PostAD {
599        merge_functions = false;
600        unroll_loops = false;
601        vectorize_slp = false;
602        vectorize_loop = false;
603    } else {
604        unroll_loops =
605            opt_level != config::OptLevel::Size && opt_level != config::OptLevel::SizeMin;
606        merge_functions = config.merge_functions;
607        vectorize_slp = config.vectorize_slp;
608        vectorize_loop = config.vectorize_loop;
609    }
610    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/write.rs:610",
                        "rustc_codegen_llvm::back::write", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/write.rs"),
                        ::tracing_core::__macro_support::Option::Some(610u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::write"),
                        ::tracing_core::field::FieldSet::new(&["unroll_loops",
                                        "vectorize_slp", "vectorize_loop", "run_enzyme"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&unroll_loops)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&vectorize_slp)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&vectorize_loop)
                                            as &dyn Value)),
                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&run_enzyme)
                                            as &dyn Value))])
            });
    } else { ; }
};trace!(?unroll_loops, ?vectorize_slp, ?vectorize_loop, ?run_enzyme);
611    if thin_lto_buffer.is_some() {
612        if !#[allow(non_exhaustive_omitted_patterns)] match opt_stage {
            llvm::OptStage::PreLinkNoLTO | llvm::OptStage::PreLinkFatLTO |
                llvm::OptStage::PreLinkThinLTO => true,
            _ => false,
        } {
    {
        ::core::panicking::panic_fmt(format_args!("the bitcode for LTO can only be obtained at the pre-link stage"));
    }
};assert!(
613            matches!(
614                opt_stage,
615                llvm::OptStage::PreLinkNoLTO
616                    | llvm::OptStage::PreLinkFatLTO
617                    | llvm::OptStage::PreLinkThinLTO
618            ),
619            "the bitcode for LTO can only be obtained at the pre-link stage"
620        );
621    }
622    let pgo_gen_path = get_pgo_gen_path(config);
623    let pgo_use_path = get_pgo_use_path(config);
624    let pgo_sample_use_path = get_pgo_sample_use_path(config);
625    let is_lto = opt_stage == llvm::OptStage::ThinLTO || opt_stage == llvm::OptStage::FatLTO;
626    let instr_profile_output_path = get_instr_profile_output_path(config);
627    let sanitize_dataflow_abilist: Vec<_> = config
628        .sanitizer_dataflow_abilist
629        .iter()
630        .map(|file| CString::new(file.as_str()).unwrap())
631        .collect();
632    let sanitize_dataflow_abilist_ptrs: Vec<_> =
633        sanitize_dataflow_abilist.iter().map(|file| file.as_ptr()).collect();
634    // Sanitizer instrumentation is only inserted during the pre-link optimization stage.
635    let sanitizer_options = if !is_lto {
636        Some(llvm::SanitizerOptions {
637            sanitize_address: config.sanitizer.contains(SanitizerSet::ADDRESS),
638            sanitize_address_recover: config.sanitizer_recover.contains(SanitizerSet::ADDRESS),
639            sanitize_cfi: config.sanitizer.contains(SanitizerSet::CFI),
640            sanitize_dataflow: config.sanitizer.contains(SanitizerSet::DATAFLOW),
641            sanitize_dataflow_abilist: sanitize_dataflow_abilist_ptrs.as_ptr(),
642            sanitize_dataflow_abilist_len: sanitize_dataflow_abilist_ptrs.len(),
643            sanitize_kcfi: config.sanitizer.contains(SanitizerSet::KCFI),
644            sanitize_memory: config.sanitizer.contains(SanitizerSet::MEMORY),
645            sanitize_memory_recover: config.sanitizer_recover.contains(SanitizerSet::MEMORY),
646            sanitize_memory_track_origins: config.sanitizer_memory_track_origins as c_int,
647            sanitize_realtime: config.sanitizer.contains(SanitizerSet::REALTIME),
648            sanitize_thread: config.sanitizer.contains(SanitizerSet::THREAD),
649            sanitize_hwaddress: config.sanitizer.contains(SanitizerSet::HWADDRESS),
650            sanitize_hwaddress_recover: config.sanitizer_recover.contains(SanitizerSet::HWADDRESS),
651            sanitize_kernel_address: config.sanitizer.contains(SanitizerSet::KERNELADDRESS),
652            sanitize_kernel_address_recover: config
653                .sanitizer_recover
654                .contains(SanitizerSet::KERNELADDRESS),
655        })
656    } else {
657        None
658    };
659
660    fn handle_offload<'ll>(cx: &'ll SimpleCx<'_>, old_fn: &llvm::Value) {
661        let old_fn_ty = cx.get_type_of_global(old_fn);
662        let old_param_types = cx.func_params_types(old_fn_ty);
663        let old_param_count = old_param_types.len();
664        if old_param_count == 0 {
665            return;
666        }
667
668        let first_param = llvm::get_param(old_fn, 0);
669        let c_name = llvm::get_value_name(first_param);
670        let first_arg_name = str::from_utf8(&c_name).unwrap();
671        // We might call llvm_optimize (and thus this code) multiple times on the same IR,
672        // but we shouldn't add this helper ptr multiple times.
673        // FIXME(offload): This could break if the user calls his first argument `dyn_ptr`.
674        if first_arg_name == "dyn_ptr" {
675            return;
676        }
677
678        // Create the new parameter list, with ptr as the first argument
679        let mut new_param_types = Vec::with_capacity(old_param_count as usize + 1);
680        new_param_types.push(cx.type_ptr());
681
682        // This relies on undocumented LLVM knowledge that scalars must be passed as i64
683        for &old_ty in &old_param_types {
684            let new_ty = match cx.type_kind(old_ty) {
685                TypeKind::Half | TypeKind::Float | TypeKind::Double | TypeKind::Integer => {
686                    cx.type_i64()
687                }
688                _ => old_ty,
689            };
690            new_param_types.push(new_ty);
691        }
692
693        // Create the new function type
694        let ret_ty = unsafe { llvm::LLVMGetReturnType(old_fn_ty) };
695        let new_fn_ty = cx.type_func(&new_param_types, ret_ty);
696
697        // Create the new function, with a temporary .offload name to avoid a name collision.
698        let old_fn_name = String::from_utf8(llvm::get_value_name(old_fn)).unwrap();
699        let new_fn_name = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}.offload", &old_fn_name))
    })format!("{}.offload", &old_fn_name);
700        let new_fn = cx.add_func(&new_fn_name, new_fn_ty);
701        let a0 = llvm::get_param(new_fn, 0);
702        llvm::set_value_name(a0, CString::new("dyn_ptr").unwrap().as_bytes());
703
704        let bb = SBuilder::append_block(cx, new_fn, "entry");
705        let mut builder = SBuilder::build(cx, bb);
706
707        let mut old_args_rebuilt = Vec::with_capacity(old_param_types.len());
708
709        for (i, &old_ty) in old_param_types.iter().enumerate() {
710            let new_arg = llvm::get_param(new_fn, (i + 1) as u32);
711
712            let rebuilt = match cx.type_kind(old_ty) {
713                TypeKind::Half | TypeKind::Float | TypeKind::Double | TypeKind::Integer => {
714                    let num_bits = scalar_width(cx, old_ty);
715
716                    let trunc = builder.trunc(new_arg, cx.type_ix(num_bits));
717                    builder.bitcast(trunc, old_ty)
718                }
719                _ => new_arg,
720            };
721
722            old_args_rebuilt.push(rebuilt);
723        }
724
725        builder.ret_void();
726
727        // Here we map the old arguments to the new arguments, with an offset of 1 to make sure
728        // that we don't use the newly added `%dyn_ptr`.
729        unsafe {
730            llvm::LLVMRustOffloadMapper(old_fn, new_fn, old_args_rebuilt.as_ptr());
731        }
732
733        llvm::set_linkage(new_fn, llvm::get_linkage(old_fn));
734        llvm::set_visibility(new_fn, llvm::get_visibility(old_fn));
735
736        // Replace all uses of old_fn with new_fn (RAUW)
737        unsafe {
738            llvm::LLVMReplaceAllUsesWith(old_fn, new_fn);
739        }
740        let name = llvm::get_value_name(old_fn);
741        unsafe {
742            llvm::LLVMDeleteFunction(old_fn);
743        }
744        // Now we can re-use the old name, without name collision.
745        llvm::set_value_name(new_fn, &name);
746    }
747
748    if cgcx.target_is_like_gpu && config.offload.contains(&config::Offload::Device) {
749        let cx =
750            SimpleCx::new(module.module_llvm.llmod(), module.module_llvm.llcx, cgcx.pointer_size);
751        for func in cx.get_functions() {
752            let offload_kernel = "offload-kernel";
753            if attributes::has_string_attr(func, offload_kernel) {
754                handle_offload(&cx, func);
755            }
756            attributes::remove_string_attr_from_llfn(func, offload_kernel);
757        }
758    }
759
760    let mut llvm_profiler = prof
761        .llvm_recording_enabled()
762        .then(|| LlvmSelfProfiler::new(prof.get_self_profiler().unwrap()));
763
764    let llvm_selfprofiler =
765        llvm_profiler.as_mut().map(|s| s as *mut _ as *mut c_void).unwrap_or(std::ptr::null_mut());
766
767    let extra_passes = if !is_lto { config.passes.join(",") } else { "".to_string() };
768
769    let llvm_plugins = config.llvm_plugins.join(",");
770
771    let enzyme_fn = if consider_ad {
772        let wrapper = llvm::EnzymeWrapper::get_instance();
773        wrapper.registerEnzymeAndPassPipeline
774    } else {
775        std::ptr::null()
776    };
777
778    let result = unsafe {
779        llvm::LLVMRustOptimize(
780            module.module_llvm.llmod(),
781            &*module.module_llvm.tm.raw(),
782            to_pass_builder_opt_level(opt_level),
783            opt_stage,
784            cgcx.use_linker_plugin_lto,
785            config.no_prepopulate_passes,
786            config.verify_llvm_ir,
787            config.lint_llvm_ir,
788            thin_lto_buffer,
789            thin_lto_summary_buffer,
790            merge_functions,
791            unroll_loops,
792            vectorize_slp,
793            vectorize_loop,
794            config.no_builtins,
795            config.emit_lifetime_markers,
796            enzyme_fn,
797            print_before_enzyme,
798            print_after_enzyme,
799            print_passes,
800            sanitizer_options.as_ref(),
801            pgo_gen_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
802            pgo_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
803            config.instrument_coverage,
804            instr_profile_output_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
805            pgo_sample_use_path.as_ref().map_or(std::ptr::null(), |s| s.as_ptr()),
806            config.debug_info_for_profiling,
807            llvm_selfprofiler,
808            selfprofile_before_pass_callback,
809            selfprofile_after_pass_callback,
810            extra_passes.as_c_char_ptr(),
811            extra_passes.len(),
812            llvm_plugins.as_c_char_ptr(),
813            llvm_plugins.len(),
814        )
815    };
816
817    if cgcx.target_is_like_gpu && config.offload.contains(&config::Offload::Device) {
818        let device_path = cgcx.output_filenames.path(OutputType::Object);
819        let device_dir = device_path.parent().unwrap();
820        let device_out = device_dir.join("host.out");
821        let device_out_c = path_to_c_string(device_out.as_path());
822        unsafe {
823            // 1) Bundle device module into offload image host.out (device TM)
824            let ok = llvm::LLVMRustBundleImages(
825                module.module_llvm.llmod(),
826                module.module_llvm.tm.raw(),
827                device_out_c.as_ptr(),
828            );
829            if !ok || !device_out.exists() {
830                dcx.emit_err(crate::errors::OffloadBundleImagesFailed);
831            }
832        }
833    }
834
835    // This assumes that we previously compiled our kernels for a gpu target, which created a
836    // `host.out` artifact. The user is supposed to provide us with a path to this artifact, we
837    // don't need any other artifacts from the previous run. We will embed this artifact into our
838    // LLVM-IR host module, to create a `host.o` ObjectFile, which we will write to disk.
839    // The last, not yet automated steps uses the `clang-linker-wrapper` to process `host.o`.
840    if !cgcx.target_is_like_gpu {
841        if let Some(device_path) = config
842            .offload
843            .iter()
844            .find_map(|o| if let config::Offload::Host(path) = o { Some(path) } else { None })
845        {
846            let device_pathbuf = PathBuf::from(device_path);
847            if device_pathbuf.is_relative() {
848                dcx.emit_err(crate::errors::OffloadWithoutAbsPath);
849            } else if device_pathbuf
850                .file_name()
851                .and_then(|n| n.to_str())
852                .is_some_and(|n| n != "host.out")
853            {
854                dcx.emit_err(crate::errors::OffloadWrongFileName);
855            } else if !device_pathbuf.exists() {
856                dcx.emit_err(crate::errors::OffloadNonexistingPath);
857            }
858            let host_path = cgcx.output_filenames.path(OutputType::Object);
859            let host_dir = host_path.parent().unwrap();
860            let out_obj = host_dir.join("host.o");
861            let host_out_c = path_to_c_string(device_pathbuf.as_path());
862
863            // 2) Finalize host: lib.bc + host.out -> host.o (host TM)
864            // We create a full clone of our LLVM host module, since we will embed the device IR
865            // into it, and this might break caching or incremental compilation otherwise.
866            let llmod2 = llvm::LLVMCloneModule(module.module_llvm.llmod());
867            let ok =
868                unsafe { llvm::LLVMRustOffloadEmbedBufferInModule(llmod2, host_out_c.as_ptr()) };
869            if !ok {
870                dcx.emit_err(crate::errors::OffloadEmbedFailed);
871            }
872            write_output_file(
873                dcx,
874                module.module_llvm.tm.raw(),
875                config.no_builtins,
876                llmod2,
877                &out_obj,
878                None,
879                llvm::FileType::ObjectFile,
880                prof,
881                true,
882            );
883            // We ignore cgcx.save_temps here and unconditionally always keep our `host.out` artifact.
884            // Otherwise, recompiling the host code would fail since we deleted that device artifact
885            // in the previous host compilation, which would be confusing at best.
886        }
887    }
888    result.into_result().unwrap_or_else(|()| llvm_err(dcx, LlvmError::RunLlvmPasses))
889}
890
891// Unsafe due to LLVM calls.
892pub(crate) fn optimize(
893    cgcx: &CodegenContext,
894    prof: &SelfProfilerRef,
895    shared_emitter: &SharedEmitter,
896    module: &mut ModuleCodegen<ModuleLlvm>,
897    config: &ModuleConfig,
898) {
899    let _timer = prof.generic_activity_with_arg("LLVM_module_optimize", &*module.name);
900
901    let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
902    let dcx = dcx.handle();
903
904    let llcx = &*module.module_llvm.llcx;
905    let _handlers =
906        DiagnosticHandlers::new(cgcx, shared_emitter, llcx, module, CodegenDiagnosticsStage::Opt);
907
908    if config.emit_no_opt_bc {
909        let out = cgcx.output_filenames.temp_path_ext_for_cgu(
910            "no-opt.bc",
911            &module.name,
912            cgcx.invocation_temp.as_deref(),
913        );
914        write_bitcode_to_file(module, &out)
915    }
916
917    // FIXME(ZuseZ4): support SanitizeHWAddress and prevent illegal/unsupported opts
918
919    if let Some(opt_level) = config.opt_level {
920        let opt_stage = match cgcx.lto {
921            Lto::Fat => llvm::OptStage::PreLinkFatLTO,
922            Lto::Thin | Lto::ThinLocal => llvm::OptStage::PreLinkThinLTO,
923            _ if cgcx.use_linker_plugin_lto => llvm::OptStage::PreLinkThinLTO,
924            _ => llvm::OptStage::PreLinkNoLTO,
925        };
926
927        // If we know that we will later run AD, then we disable vectorization and loop unrolling.
928        // Otherwise we pretend AD is already done and run the normal opt pipeline (=PostAD).
929        let consider_ad = config.autodiff.contains(&config::AutoDiff::Enable);
930        let autodiff_stage = if consider_ad { AutodiffStage::PreAD } else { AutodiffStage::PostAD };
931        // The embedded bitcode is used to run LTO/ThinLTO.
932        // The bitcode obtained during the `codegen` phase is no longer suitable for performing LTO.
933        // It may have undergone LTO due to ThinLocal, so we need to obtain the embedded bitcode at
934        // this point.
935        let (mut thin_lto_buffer, mut thin_lto_summary_buffer) = if (module.kind
936            == ModuleKind::Regular
937            && config.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full))
938            || config.emit_thin_lto_summary
939        {
940            (Some(None), config.emit_thin_lto_summary.then_some(None))
941        } else {
942            (None, None)
943        };
944        unsafe {
945            llvm_optimize(
946                cgcx,
947                prof,
948                dcx,
949                module,
950                thin_lto_buffer.as_mut(),
951                thin_lto_summary_buffer.as_mut(),
952                config,
953                opt_level,
954                opt_stage,
955                autodiff_stage,
956            )
957        };
958        if let Some(thin_lto_buffer) = thin_lto_buffer {
959            let thin_lto_buffer = thin_lto_buffer.unwrap();
960            module.thin_lto_buffer = Some(thin_lto_buffer.data().to_vec());
961            let bc_summary_out = cgcx.output_filenames.temp_path_for_cgu(
962                OutputType::ThinLinkBitcode,
963                &module.name,
964                cgcx.invocation_temp.as_deref(),
965            );
966            if let Some(thin_lto_summary_buffer) = thin_lto_summary_buffer
967                && let Some(thin_link_bitcode_filename) = bc_summary_out.file_name()
968            {
969                let thin_lto_summary_buffer = thin_lto_summary_buffer.unwrap();
970                let summary_data = thin_lto_summary_buffer.data();
971                prof.artifact_size(
972                    "llvm_bitcode_summary",
973                    thin_link_bitcode_filename.to_string_lossy(),
974                    summary_data.len() as u64,
975                );
976                let _timer = prof.generic_activity_with_arg(
977                    "LLVM_module_codegen_emit_bitcode_summary",
978                    &*module.name,
979                );
980                if let Err(err) = fs::write(&bc_summary_out, summary_data) {
981                    dcx.emit_err(WriteBytecode { path: &bc_summary_out, err });
982                }
983            }
984        }
985    }
986}
987
988pub(crate) fn codegen(
989    cgcx: &CodegenContext,
990    prof: &SelfProfilerRef,
991    shared_emitter: &SharedEmitter,
992    module: ModuleCodegen<ModuleLlvm>,
993    config: &ModuleConfig,
994) -> CompiledModule {
995    let _timer = prof.generic_activity_with_arg("LLVM_module_codegen", &*module.name);
996
997    let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
998    let dcx = dcx.handle();
999
1000    {
1001        let llmod = module.module_llvm.llmod();
1002        let llcx = &*module.module_llvm.llcx;
1003        let tm = &*module.module_llvm.tm;
1004        let _handlers = DiagnosticHandlers::new(
1005            cgcx,
1006            shared_emitter,
1007            llcx,
1008            &module,
1009            CodegenDiagnosticsStage::Codegen,
1010        );
1011
1012        if cgcx.msvc_imps_needed {
1013            create_msvc_imps(cgcx, llcx, llmod);
1014        }
1015
1016        // Note that if object files are just LLVM bitcode we write bitcode,
1017        // copy it to the .o file, and delete the bitcode if it wasn't
1018        // otherwise requested.
1019
1020        let bc_out = cgcx.output_filenames.temp_path_for_cgu(
1021            OutputType::Bitcode,
1022            &module.name,
1023            cgcx.invocation_temp.as_deref(),
1024        );
1025        let obj_out = cgcx.output_filenames.temp_path_for_cgu(
1026            OutputType::Object,
1027            &module.name,
1028            cgcx.invocation_temp.as_deref(),
1029        );
1030
1031        if config.bitcode_needed() {
1032            if config.emit_bc || config.emit_obj == EmitObj::Bitcode {
1033                let thin = {
1034                    let _timer = prof.generic_activity_with_arg(
1035                        "LLVM_module_codegen_make_bitcode",
1036                        &*module.name,
1037                    );
1038                    ModuleBuffer::new(llmod, cgcx.lto != Lto::Fat)
1039                };
1040                let data = thin.data();
1041                let _timer = prof
1042                    .generic_activity_with_arg("LLVM_module_codegen_emit_bitcode", &*module.name);
1043                if let Some(bitcode_filename) = bc_out.file_name() {
1044                    prof.artifact_size(
1045                        "llvm_bitcode",
1046                        bitcode_filename.to_string_lossy(),
1047                        data.len() as u64,
1048                    );
1049                }
1050                if let Err(err) = fs::write(&bc_out, data) {
1051                    dcx.emit_err(WriteBytecode { path: &bc_out, err });
1052                }
1053            }
1054
1055            if config.embed_bitcode() && module.kind == ModuleKind::Regular {
1056                let _timer = prof
1057                    .generic_activity_with_arg("LLVM_module_codegen_embed_bitcode", &*module.name);
1058                let thin_bc =
1059                    module.thin_lto_buffer.as_deref().expect("cannot find embedded bitcode");
1060                embed_bitcode(cgcx, llcx, llmod, &thin_bc);
1061            }
1062        }
1063
1064        if config.emit_ir {
1065            let _timer =
1066                prof.generic_activity_with_arg("LLVM_module_codegen_emit_ir", &*module.name);
1067            let out = cgcx.output_filenames.temp_path_for_cgu(
1068                OutputType::LlvmAssembly,
1069                &module.name,
1070                cgcx.invocation_temp.as_deref(),
1071            );
1072            let out_c = path_to_c_string(&out);
1073
1074            extern "C" fn demangle_callback(
1075                input_ptr: *const c_char,
1076                input_len: size_t,
1077                output_ptr: *mut c_char,
1078                output_len: size_t,
1079            ) -> size_t {
1080                let input =
1081                    unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) };
1082
1083                let Ok(input) = str::from_utf8(input) else { return 0 };
1084
1085                let output = unsafe {
1086                    slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize)
1087                };
1088                let mut cursor = io::Cursor::new(output);
1089
1090                let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 };
1091
1092                if cursor.write_fmt(format_args!("{0:#}", demangled))write!(cursor, "{demangled:#}").is_err() {
1093                    // Possible only if provided buffer is not big enough
1094                    return 0;
1095                }
1096
1097                cursor.position() as size_t
1098            }
1099
1100            let result =
1101                unsafe { llvm::LLVMRustPrintModule(llmod, out_c.as_ptr(), demangle_callback) };
1102
1103            if result == llvm::LLVMRustResult::Success {
1104                record_artifact_size(prof, "llvm_ir", &out);
1105            }
1106
1107            result
1108                .into_result()
1109                .unwrap_or_else(|()| llvm_err(dcx, LlvmError::WriteIr { path: &out }));
1110        }
1111
1112        if config.emit_asm {
1113            let _timer =
1114                prof.generic_activity_with_arg("LLVM_module_codegen_emit_asm", &*module.name);
1115            let path = cgcx.output_filenames.temp_path_for_cgu(
1116                OutputType::Assembly,
1117                &module.name,
1118                cgcx.invocation_temp.as_deref(),
1119            );
1120
1121            // We can't use the same module for asm and object code output,
1122            // because that triggers various errors like invalid IR or broken
1123            // binaries. So we must clone the module to produce the asm output
1124            // if we are also producing object code.
1125            let llmod = if let EmitObj::ObjectCode(_) = config.emit_obj {
1126                llvm::LLVMCloneModule(llmod)
1127            } else {
1128                llmod
1129            };
1130            write_output_file(
1131                dcx,
1132                tm.raw(),
1133                config.no_builtins,
1134                llmod,
1135                &path,
1136                None,
1137                llvm::FileType::AssemblyFile,
1138                prof,
1139                config.verify_llvm_ir,
1140            );
1141        }
1142
1143        match config.emit_obj {
1144            EmitObj::ObjectCode(_) => {
1145                let _timer =
1146                    prof.generic_activity_with_arg("LLVM_module_codegen_emit_obj", &*module.name);
1147
1148                let dwo_out = cgcx
1149                    .output_filenames
1150                    .temp_path_dwo_for_cgu(&module.name, cgcx.invocation_temp.as_deref());
1151                let dwo_out = match (cgcx.split_debuginfo, cgcx.split_dwarf_kind) {
1152                    // Don't change how DWARF is emitted when disabled.
1153                    (SplitDebuginfo::Off, _) => None,
1154                    // Don't provide a DWARF object path if split debuginfo is enabled but this is
1155                    // a platform that doesn't support Split DWARF.
1156                    _ if !cgcx.target_can_use_split_dwarf => None,
1157                    // Don't provide a DWARF object path in single mode, sections will be written
1158                    // into the object as normal but ignored by linker.
1159                    (_, SplitDwarfKind::Single) => None,
1160                    // Emit (a subset of the) DWARF into a separate dwarf object file in split
1161                    // mode.
1162                    (_, SplitDwarfKind::Split) => Some(dwo_out.as_path()),
1163                };
1164
1165                write_output_file(
1166                    dcx,
1167                    tm.raw(),
1168                    config.no_builtins,
1169                    llmod,
1170                    &obj_out,
1171                    dwo_out,
1172                    llvm::FileType::ObjectFile,
1173                    prof,
1174                    config.verify_llvm_ir,
1175                );
1176            }
1177
1178            EmitObj::Bitcode => {
1179                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/write.rs:1179",
                        "rustc_codegen_llvm::back::write", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/write.rs"),
                        ::tracing_core::__macro_support::Option::Some(1179u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::write"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("copying bitcode {0:?} to obj {1:?}",
                                                    bc_out, obj_out) as &dyn Value))])
            });
    } else { ; }
};debug!("copying bitcode {:?} to obj {:?}", bc_out, obj_out);
1180                if let Err(err) = link_or_copy(&bc_out, &obj_out) {
1181                    dcx.emit_err(CopyBitcode { err });
1182                }
1183
1184                if !config.emit_bc {
1185                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/back/write.rs:1185",
                        "rustc_codegen_llvm::back::write", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/write.rs"),
                        ::tracing_core::__macro_support::Option::Some(1185u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::write"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("removing_bitcode {0:?}",
                                                    bc_out) as &dyn Value))])
            });
    } else { ; }
};debug!("removing_bitcode {:?}", bc_out);
1186                    ensure_removed(dcx, &bc_out);
1187                }
1188            }
1189
1190            EmitObj::None => {}
1191        }
1192
1193        record_llvm_cgu_instructions_stats(prof, &module.name, llmod);
1194    }
1195
1196    // `.dwo` files are only emitted if:
1197    //
1198    // - Object files are being emitted (i.e. bitcode only or metadata only compilations will not
1199    //   produce dwarf objects, even if otherwise enabled)
1200    // - Target supports Split DWARF
1201    // - Split debuginfo is enabled
1202    // - Split DWARF kind is `split` (i.e. debuginfo is split into `.dwo` files, not different
1203    //   sections in the `.o` files).
1204    let dwarf_object_emitted = #[allow(non_exhaustive_omitted_patterns)] match config.emit_obj {
    EmitObj::ObjectCode(_) => true,
    _ => false,
}matches!(config.emit_obj, EmitObj::ObjectCode(_))
1205        && cgcx.target_can_use_split_dwarf
1206        && cgcx.split_debuginfo != SplitDebuginfo::Off
1207        && cgcx.split_dwarf_kind == SplitDwarfKind::Split;
1208    module.into_compiled_module(
1209        config.emit_obj != EmitObj::None,
1210        dwarf_object_emitted,
1211        config.emit_bc,
1212        config.emit_asm,
1213        config.emit_ir,
1214        &cgcx.output_filenames,
1215        cgcx.invocation_temp.as_deref(),
1216    )
1217}
1218
1219fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: &[u8]) -> Vec<u8> {
1220    let mut asm = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".section {0},\"{1}\"\n",
                section_name, section_flags))
    })format!(".section {section_name},\"{section_flags}\"\n").into_bytes();
1221    asm.extend_from_slice(b".ascii \"");
1222    asm.reserve(data.len());
1223    for &byte in data {
1224        if byte == b'\\' || byte == b'"' {
1225            asm.push(b'\\');
1226            asm.push(byte);
1227        } else if byte < 0x20 || byte >= 0x80 {
1228            // Avoid non UTF-8 inline assembly. Use octal escape sequence, because it is fixed
1229            // width, while hex escapes will consume following characters.
1230            asm.push(b'\\');
1231            asm.push(b'0' + ((byte >> 6) & 0x7));
1232            asm.push(b'0' + ((byte >> 3) & 0x7));
1233            asm.push(b'0' + ((byte >> 0) & 0x7));
1234        } else {
1235            asm.push(byte);
1236        }
1237    }
1238    asm.extend_from_slice(b"\"\n");
1239    asm
1240}
1241
1242pub(crate) fn bitcode_section_name(cgcx: &CodegenContext) -> &'static CStr {
1243    if cgcx.target_is_like_darwin {
1244        c"__LLVM,__bitcode"
1245    } else if cgcx.target_is_like_aix {
1246        c".ipa"
1247    } else {
1248        c".llvmbc"
1249    }
1250}
1251
1252/// Embed the bitcode of an LLVM module for LTO in the LLVM module itself.
1253fn embed_bitcode(
1254    cgcx: &CodegenContext,
1255    llcx: &llvm::Context,
1256    llmod: &llvm::Module,
1257    bitcode: &[u8],
1258) {
1259    // We're adding custom sections to the output object file, but we definitely
1260    // do not want these custom sections to make their way into the final linked
1261    // executable. The purpose of these custom sections is for tooling
1262    // surrounding object files to work with the LLVM IR, if necessary. For
1263    // example rustc's own LTO will look for LLVM IR inside of the object file
1264    // in these sections by default.
1265    //
1266    // To handle this is a bit different depending on the object file format
1267    // used by the backend, broken down into a few different categories:
1268    //
1269    // * Mach-O - this is for macOS. Inspecting the source code for the native
1270    //   linker here shows that the `.llvmbc` and `.llvmcmd` sections are
1271    //   automatically skipped by the linker. In that case there's nothing extra
1272    //   that we need to do here. We do need to make sure that the
1273    //   `__LLVM,__cmdline` section exists even though it is empty as otherwise
1274    //   ld64 rejects the object file.
1275    //
1276    // * Wasm - the native LLD linker is hard-coded to skip `.llvmbc` and
1277    //   `.llvmcmd` sections, so there's nothing extra we need to do.
1278    //
1279    // * COFF - if we don't do anything the linker will by default copy all
1280    //   these sections to the output artifact, not what we want! To subvert
1281    //   this we want to flag the sections we inserted here as
1282    //   `IMAGE_SCN_LNK_REMOVE`.
1283    //
1284    // * ELF - this is very similar to COFF above. One difference is that these
1285    //   sections are removed from the output linked artifact when
1286    //   `--gc-sections` is passed, which we pass by default. If that flag isn't
1287    //   passed though then these sections will show up in the final output.
1288    //   Additionally the flag that we need to set here is `SHF_EXCLUDE`.
1289    //
1290    // * XCOFF - AIX linker ignores content in .ipa and .info if no auxiliary
1291    //   symbol associated with these sections.
1292    //
1293    // Unfortunately, LLVM provides no way to set custom section flags. For ELF
1294    // and COFF we emit the sections using module level inline assembly for that
1295    // reason (see issue #90326 for historical background).
1296
1297    if cgcx.target_is_like_darwin
1298        || cgcx.target_is_like_aix
1299        || cgcx.target_arch == "wasm32"
1300        || cgcx.target_arch == "wasm64"
1301    {
1302        // We don't need custom section flags, create LLVM globals.
1303        let llconst = common::bytes_in_context(llcx, bitcode);
1304        let llglobal = llvm::add_global(llmod, common::val_ty(llconst), c"rustc.embedded.module");
1305        llvm::set_initializer(llglobal, llconst);
1306
1307        llvm::set_section(llglobal, bitcode_section_name(cgcx));
1308        llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage);
1309        llvm::LLVMSetGlobalConstant(llglobal, llvm::TRUE);
1310
1311        let llconst = common::bytes_in_context(llcx, &[]);
1312        let llglobal = llvm::add_global(llmod, common::val_ty(llconst), c"rustc.embedded.cmdline");
1313        llvm::set_initializer(llglobal, llconst);
1314        let section = if cgcx.target_is_like_darwin {
1315            c"__LLVM,__cmdline"
1316        } else if cgcx.target_is_like_aix {
1317            c".info"
1318        } else {
1319            c".llvmcmd"
1320        };
1321        llvm::set_section(llglobal, section);
1322        llvm::set_linkage(llglobal, llvm::Linkage::PrivateLinkage);
1323    } else {
1324        // We need custom section flags, so emit module-level inline assembly.
1325        let section_flags = if cgcx.is_pe_coff { "n" } else { "e" };
1326        let asm = create_section_with_flags_asm(".llvmbc", section_flags, bitcode);
1327        llvm::append_module_inline_asm(llmod, &asm);
1328        let asm = create_section_with_flags_asm(".llvmcmd", section_flags, &[]);
1329        llvm::append_module_inline_asm(llmod, &asm);
1330    }
1331}
1332
1333// Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1334// This is required to satisfy `dllimport` references to static data in .rlibs
1335// when using MSVC linker. We do this only for data, as linker can fix up
1336// code references on its own.
1337// See #26591, #27438
1338fn create_msvc_imps(cgcx: &CodegenContext, llcx: &llvm::Context, llmod: &llvm::Module) {
1339    if !cgcx.msvc_imps_needed {
1340        return;
1341    }
1342    // The x86 ABI seems to require that leading underscores are added to symbol
1343    // names, so we need an extra underscore on x86. There's also a leading
1344    // '\x01' here which disables LLVM's symbol mangling (e.g., no extra
1345    // underscores added in front).
1346    let prefix = if cgcx.target_arch == "x86" { "\x01__imp__" } else { "\x01__imp_" };
1347
1348    let ptr_ty = llvm_type_ptr(llcx);
1349    let globals = base::iter_globals(llmod)
1350        .filter(|&val| {
1351            llvm::get_linkage(val) == llvm::Linkage::ExternalLinkage && !llvm::is_declaration(val)
1352        })
1353        .filter_map(|val| {
1354            // Exclude some symbols that we know are not Rust symbols.
1355            let name = llvm::get_value_name(val);
1356            if ignored(&name) { None } else { Some((val, name)) }
1357        })
1358        .map(move |(val, name)| {
1359            let mut imp_name = prefix.as_bytes().to_vec();
1360            imp_name.extend(name);
1361            let imp_name = CString::new(imp_name).unwrap();
1362            (imp_name, val)
1363        })
1364        .collect::<Vec<_>>();
1365
1366    for (imp_name, val) in globals {
1367        let imp = llvm::add_global(llmod, ptr_ty, &imp_name);
1368
1369        llvm::set_initializer(imp, val);
1370        llvm::set_linkage(imp, llvm::Linkage::ExternalLinkage);
1371    }
1372
1373    // Use this function to exclude certain symbols from `__imp` generation.
1374    fn ignored(symbol_name: &[u8]) -> bool {
1375        // These are symbols generated by LLVM's profiling instrumentation
1376        symbol_name.starts_with(b"__llvm_profile_")
1377    }
1378}
1379
1380fn record_artifact_size(
1381    self_profiler_ref: &SelfProfilerRef,
1382    artifact_kind: &'static str,
1383    path: &Path,
1384) {
1385    // Don't stat the file if we are not going to record its size.
1386    if !self_profiler_ref.enabled() {
1387        return;
1388    }
1389
1390    if let Some(artifact_name) = path.file_name() {
1391        let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
1392        self_profiler_ref.artifact_size(artifact_kind, artifact_name.to_string_lossy(), file_size);
1393    }
1394}
1395
1396fn record_llvm_cgu_instructions_stats(prof: &SelfProfilerRef, name: &str, llmod: &llvm::Module) {
1397    if !prof.enabled() {
1398        return;
1399    }
1400
1401    let total = unsafe { llvm::LLVMRustModuleInstructionStats(llmod) };
1402    prof.artifact_size("cgu_instructions", name, total);
1403}