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