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