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