rustc_codegen_llvm/back/
write.rs

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