Skip to main content

rustc_codegen_llvm/
context.rs

1use std::borrow::{Borrow, Cow};
2use std::cell::{Cell, RefCell};
3use std::ffi::{CStr, c_char, c_uint};
4use std::marker::PhantomData;
5use std::ops::{Deref, DerefMut};
6use std::str;
7
8use rustc_abi::{HasDataLayout, Size, TargetDataLayout, VariantIdx};
9use rustc_codegen_ssa::back::versioned_llvm_target;
10use rustc_codegen_ssa::base::{wants_msvc_seh, wants_wasm_eh};
11use rustc_codegen_ssa::diagnostics as ssa_errors;
12use rustc_codegen_ssa::traits::*;
13use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, ToBaseN};
14use rustc_data_structures::fx::FxHashMap;
15use rustc_data_structures::small_c_str::SmallCStr;
16use rustc_hir::def_id::DefId;
17use rustc_middle::mono::CodegenUnit;
18use rustc_middle::ty::layout::{
19    FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
20    codegen_handle_fn_abi_err,
21};
22use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
23use rustc_sanitizers::ignorelist::{SanitizerIgnoreList, typename_for_ignore_list};
24use rustc_session::config::{
25    BranchProtection, CFGuard, CFProtection, DebugInfo, FunctionReturn, PAuthKey, PacRet,
26};
27use rustc_session::{PointerAuthSchema, Session};
28use rustc_span::{DUMMY_SP, Span, Symbol, bug, sym};
29use rustc_structures::CrateType;
30use rustc_target::spec::{
31    Arch, CfgAbi, Env, FramePointer, HasTargetSpec, Os, RelocModel, SmallDataThresholdSupport,
32    Target, TlsModel,
33};
34use smallvec::SmallVec;
35
36use crate::abi::to_llvm_calling_convention;
37use crate::back::write::to_llvm_code_model;
38use crate::builder::gpu_offload::{OffloadGlobals, OffloadKernelGlobals};
39use crate::callee::get_fn;
40use crate::debuginfo::metadata::apply_vcall_visibility_metadata;
41use crate::llvm::{self, Metadata, MetadataKindId, Module, Type, Value};
42use crate::{attributes, common, coverageinfo, debuginfo, llvm_util};
43
44/// `TyCtxt` (and related cache datastructures) can't be move between threads.
45/// However, there are various cx related functions which we want to be available to the builder and
46/// other compiler pieces. Here we define a small subset which has enough information and can be
47/// moved around more freely.
48pub(crate) struct SCx<'ll> {
49    pub llmod: &'ll llvm::Module,
50    pub llcx: &'ll llvm::Context,
51    pub isize_ty: &'ll Type,
52}
53
54impl<'ll> Borrow<SCx<'ll>> for FullCx<'ll, '_> {
55    fn borrow(&self) -> &SCx<'ll> {
56        &self.scx
57    }
58}
59
60impl<'ll, 'tcx> Deref for FullCx<'ll, 'tcx> {
61    type Target = SimpleCx<'ll>;
62
63    #[inline]
64    fn deref(&self) -> &Self::Target {
65        &self.scx
66    }
67}
68
69pub(crate) struct GenericCx<'ll, T: Borrow<SCx<'ll>>>(T, PhantomData<SCx<'ll>>);
70
71impl<'ll, T: Borrow<SCx<'ll>>> Deref for GenericCx<'ll, T> {
72    type Target = T;
73
74    #[inline]
75    fn deref(&self) -> &Self::Target {
76        &self.0
77    }
78}
79
80impl<'ll, T: Borrow<SCx<'ll>>> DerefMut for GenericCx<'ll, T> {
81    #[inline]
82    fn deref_mut(&mut self) -> &mut Self::Target {
83        &mut self.0
84    }
85}
86
87pub(crate) type SimpleCx<'ll> = GenericCx<'ll, SCx<'ll>>;
88
89/// There is one `CodegenCx` per codegen unit. Each one has its own LLVM
90/// `llvm::Context` so that several codegen units may be processed in parallel.
91/// All other LLVM data structures in the `CodegenCx` are tied to that `llvm::Context`.
92pub(crate) type CodegenCx<'ll, 'tcx> = GenericCx<'ll, FullCx<'ll, 'tcx>>;
93
94pub(crate) struct FullCx<'ll, 'tcx> {
95    pub tcx: TyCtxt<'tcx>,
96    pub bitcode_needed: bool,
97    pub scx: SimpleCx<'ll>,
98    pub use_dll_storage_attrs: bool,
99    pub tls_model: llvm::ThreadLocalMode,
100
101    pub codegen_unit: &'tcx CodegenUnit<'tcx>,
102
103    /// Cache instances of monomorphic and polymorphic items
104    pub instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
105    /// Cache instances of intrinsics
106    pub intrinsic_instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
107    /// Cache generated vtables
108    pub vtables: RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>>,
109    /// Cache of constant strings,
110    pub const_str_cache: RefCell<FxHashMap<String, &'ll Value>>,
111
112    /// Cache of emitted const globals (value -> global)
113    pub const_globals: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
114
115    /// List of globals for static variables which need to be passed to the
116    /// LLVM function ReplaceAllUsesWith (RAUW) when codegen is complete.
117    /// (We have to make sure we don't invalidate any Values referring
118    /// to constants.)
119    pub statics_to_rauw: RefCell<Vec<(&'ll Value, &'ll Value)>>,
120
121    /// Statics that will be placed in the llvm.used variable
122    /// See <https://llvm.org/docs/LangRef.html#the-llvm-used-global-variable> for details
123    pub used_statics: Vec<&'ll Value>,
124
125    /// Statics that will be placed in the llvm.compiler.used variable
126    /// See <https://llvm.org/docs/LangRef.html#the-llvm-compiler-used-global-variable> for details
127    pub compiler_used_statics: RefCell<Vec<&'ll Value>>,
128
129    /// Mapping of non-scalar types to llvm types.
130    pub type_lowering: RefCell<FxHashMap<(Ty<'tcx>, Option<VariantIdx>), &'ll Type>>,
131
132    /// Mapping of scalar types to llvm types.
133    pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'ll Type>>,
134
135    /// Extra per-CGU codegen state needed when coverage instrumentation is enabled.
136    pub coverage_cx: Option<coverageinfo::CguCoverageContext<'ll, 'tcx>>,
137    pub dbg_cx: Option<debuginfo::CodegenUnitDebugContext<'ll, 'tcx>>,
138    pub sanitizer_ignorelist: Option<SanitizerIgnoreList>,
139
140    eh_personality: Cell<Option<&'ll Value>>,
141    pub rust_try_fn: Cell<Option<(&'ll Type, &'ll Value)>>,
142
143    intrinsics:
144        RefCell<FxHashMap<(Cow<'static, str>, SmallVec<[&'ll Type; 2]>), (&'ll Type, &'ll Value)>>,
145
146    /// A counter that is used for generating local symbol names
147    local_gen_sym_counter: Cell<usize>,
148
149    /// A counter that is used for generating global symbol names
150    global_gen_sym_counter: Cell<usize>,
151
152    /// `codegen_static` will sometimes create a second global variable with a
153    /// different type and clear the symbol name of the original global.
154    /// `global_asm!` needs to be able to find this new global so that it can
155    /// compute the correct mangled symbol name to insert into the asm.
156    pub renamed_statics: RefCell<FxHashMap<DefId, &'ll Value>>,
157
158    /// Cached Objective-C class type
159    pub objc_class_t: Cell<Option<&'ll Type>>,
160
161    /// Cache of Objective-C class references
162    pub objc_classrefs: RefCell<FxHashMap<Symbol, &'ll Value>>,
163
164    /// Cache of Objective-C selector references
165    pub objc_selrefs: RefCell<FxHashMap<Symbol, &'ll Value>>,
166
167    /// Globals shared by the offloading runtime
168    pub offload_globals: RefCell<Option<OffloadGlobals<'ll>>>,
169
170    /// Cache of kernel-specific globals
171    pub offload_kernel_cache: RefCell<FxHashMap<String, OffloadKernelGlobals<'ll>>>,
172}
173
174fn to_llvm_tls_model(tls_model: TlsModel) -> llvm::ThreadLocalMode {
175    match tls_model {
176        TlsModel::GeneralDynamic => llvm::ThreadLocalMode::GeneralDynamic,
177        TlsModel::LocalDynamic => llvm::ThreadLocalMode::LocalDynamic,
178        TlsModel::InitialExec => llvm::ThreadLocalMode::InitialExec,
179        TlsModel::LocalExec => llvm::ThreadLocalMode::LocalExec,
180        TlsModel::Emulated => llvm::ThreadLocalMode::GeneralDynamic,
181    }
182}
183
184pub(crate) unsafe fn create_module<'ll>(
185    tcx: TyCtxt<'_>,
186    llcx: &'ll llvm::Context,
187    mod_name: &str,
188) -> &'ll llvm::Module {
189    let sess = tcx.sess;
190    let mod_name = SmallCStr::new(mod_name);
191    let llmod = unsafe { llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx) };
192
193    let cx = SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size());
194
195    let mut target_data_layout = sess.target.data_layout.to_string();
196    let llvm_version = llvm_util::get_version();
197
198    if llvm_version < (22, 0, 0) {
199        if sess.target.arch == Arch::Avr {
200            // LLVM 22.0 updated the default layout on avr: https://github.com/llvm/llvm-project/pull/153010
201            target_data_layout = target_data_layout.replace("n8:16", "n8")
202        }
203        if sess.target.arch == Arch::Nvptx64 {
204            // LLVM 22 updated the NVPTX layout to indicate 256-bit vector load/store: https://github.com/llvm/llvm-project/pull/155198
205            target_data_layout = target_data_layout.replace("-i256:256", "");
206        }
207        if sess.target.arch == Arch::PowerPC64 {
208            // LLVM 22 updated the ABI alignment for double on AIX: https://github.com/llvm/llvm-project/pull/144673
209            target_data_layout = target_data_layout.replace("-f64:32:64", "");
210
211            // LLVM 22 fixed the data layout calculation for targets that default to ELFv1
212            // when the ABI is set to ELFv2. With LLVM 21, the ELFv1 datalayout must be used,
213            // which will overalign function entries.
214            // https://github.com/llvm/llvm-project/pull/149725
215            if sess.target.llvm_target == "powerpc64-unknown-linux-gnu" {
216                target_data_layout = target_data_layout.replace("-Fn32", "-Fi64");
217            }
218        }
219        if sess.target.arch == Arch::AmdGpu {
220            // LLVM 22 specified ELF mangling in the amdgpu data layout:
221            // https://github.com/llvm/llvm-project/pull/163011
222            target_data_layout = target_data_layout.replace("-m:e", "");
223        }
224    }
225    if llvm_version < (23, 0, 0) {
226        if sess.target.arch == Arch::S390x {
227            // LLVM 23 updated the s390x layout to specify the stack alignment: https://github.com/llvm/llvm-project/pull/176041
228            target_data_layout = target_data_layout.replace("-S64", "");
229        }
230    }
231
232    // Ensure the data-layout values hardcoded remain the defaults.
233    {
234        let tm = crate::back::write::create_informational_target_machine(sess);
235        unsafe {
236            llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, tm.raw());
237        }
238
239        let llvm_data_layout = unsafe { llvm::LLVMGetDataLayoutStr(llmod) };
240        let llvm_data_layout =
241            str::from_utf8(unsafe { CStr::from_ptr(llvm_data_layout) }.to_bytes())
242                .expect("got a non-UTF8 data-layout from LLVM");
243
244        if target_data_layout != llvm_data_layout {
245            tcx.dcx().emit_err(crate::diagnostics::MismatchedDataLayout {
246                rustc_target: sess.opts.target_triple.to_string().as_str(),
247                rustc_layout: target_data_layout.as_str(),
248                llvm_target: sess.target.llvm_target.borrow(),
249                llvm_layout: llvm_data_layout,
250            });
251        }
252    }
253
254    let data_layout = SmallCStr::new(&target_data_layout);
255    unsafe {
256        llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
257    }
258
259    let llvm_target = SmallCStr::new(&versioned_llvm_target(sess));
260    unsafe {
261        llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
262    }
263
264    let reloc_model = sess.relocation_model();
265    if #[allow(non_exhaustive_omitted_patterns)] match reloc_model {
    RelocModel::Pic | RelocModel::Pie => true,
    _ => false,
}matches!(reloc_model, RelocModel::Pic | RelocModel::Pie) {
266        unsafe {
267            llvm::LLVMRustSetModulePICLevel(llmod);
268        }
269        // PIE is potentially more effective than PIC, but can only be used in executables.
270        // If all our outputs are executables, then we can relax PIC to PIE.
271        if reloc_model == RelocModel::Pie
272            || tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable)
273        {
274            unsafe {
275                llvm::LLVMRustSetModulePIELevel(llmod);
276            }
277        }
278    }
279
280    // Linking object files with different code models is undefined behavior
281    // because the compiler would have to generate additional code (to span
282    // longer jumps) if a larger code model is used with a smaller one.
283    //
284    // See https://reviews.llvm.org/D52322 and https://reviews.llvm.org/D52323.
285    unsafe {
286        llvm::LLVMRustSetModuleCodeModel(llmod, to_llvm_code_model(sess.code_model()));
287    }
288
289    if let Some(large_data_threshold) = sess.opts.unstable_opts.large_data_threshold {
290        unsafe {
291            llvm::LLVMRustSetModuleLargeDataThreshold(llmod, large_data_threshold);
292        }
293    }
294
295    // If skipping the PLT is enabled, we need to add some module metadata
296    // to ensure intrinsic calls don't use it.
297    if !sess.needs_plt() {
298        llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "RtLibUseGOT", 1);
299    }
300
301    // Enable canonical jump tables if CFI is enabled. (See https://reviews.llvm.org/D65629.)
302    if sess.is_sanitizer_cfi_canonical_jump_tables_enabled() && sess.is_sanitizer_cfi_enabled() {
303        llvm::add_module_flag_u32(
304            llmod,
305            llvm::ModuleFlagMergeBehavior::Override,
306            "CFI Canonical Jump Tables",
307            1,
308        );
309    }
310
311    // If we're normalizing integers with CFI, ensure LLVM generated functions do the same.
312    // See https://github.com/llvm/llvm-project/pull/104826
313    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
314        llvm::add_module_flag_u32(
315            llmod,
316            llvm::ModuleFlagMergeBehavior::Override,
317            "cfi-normalize-integers",
318            1,
319        );
320    }
321
322    // Enable LTO unit splitting if specified or if CFI is enabled. (See
323    // https://reviews.llvm.org/D53891.)
324    if sess.is_split_lto_unit_enabled() || sess.is_sanitizer_cfi_enabled() {
325        llvm::add_module_flag_u32(
326            llmod,
327            llvm::ModuleFlagMergeBehavior::Override,
328            "EnableSplitLTOUnit",
329            1,
330        );
331    }
332
333    if sess.must_emit_unwind_tables() {
334        // This assertion checks that Max is the correct merge behavior.
335        // Async unwind tables are strictly more useful than sync uwtables.
336        const {
337            if !((llvm::UWTableKind::None as u32) < (llvm::UWTableKind::Sync as u32)) {
    ::core::panicking::panic("assertion failed: (llvm::UWTableKind::None as u32) < (llvm::UWTableKind::Sync as u32)")
};assert!((llvm::UWTableKind::None as u32) < (llvm::UWTableKind::Sync as u32));
338            if !((llvm::UWTableKind::Sync as u32) < (llvm::UWTableKind::Async as u32)) {
    ::core::panicking::panic("assertion failed: (llvm::UWTableKind::Sync as u32) < (llvm::UWTableKind::Async as u32)")
};assert!((llvm::UWTableKind::Sync as u32) < (llvm::UWTableKind::Async as u32));
339        }
340
341        llvm::add_module_flag_u32(
342            llmod,
343            llvm::ModuleFlagMergeBehavior::Max,
344            "uwtable",
345            match sess.opts.unstable_opts.use_sync_unwind {
346                Some(true) => llvm::UWTableKind::Sync as u32,
347                Some(false) | None => llvm::UWTableKind::Async as u32,
348            },
349        );
350    }
351
352    // Add "kcfi" module flag if KCFI is enabled. (See https://reviews.llvm.org/D119296.)
353    if sess.is_sanitizer_kcfi_enabled() {
354        llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Override, "kcfi", 1);
355
356        // Add "kcfi-offset" module flag with -Z patchable-function-entry (See
357        // https://reviews.llvm.org/D141172).
358        let patchable_prefix_nops = sess.opts.unstable_opts.patchable_function_entry.prefix();
359        if patchable_prefix_nops > 0 {
360            llvm::add_module_flag_u32(
361                llmod,
362                llvm::ModuleFlagMergeBehavior::Override,
363                "kcfi-offset",
364                patchable_prefix_nops.into(),
365            );
366        }
367
368        // Add "kcfi-arity" module flag if KCFI arity indicator is enabled. (See
369        // https://github.com/llvm/llvm-project/pull/117121.)
370        if sess.is_sanitizer_kcfi_arity_enabled() {
371            llvm::add_module_flag_u32(
372                llmod,
373                llvm::ModuleFlagMergeBehavior::Override,
374                "kcfi-arity",
375                1,
376            );
377        }
378    }
379
380    // Control Flow Guard is currently only supported by MSVC and LLVM on Windows.
381    if sess.target.is_like_msvc
382        || (sess.target.options.os == Os::Windows
383            && sess.target.options.env == Env::Gnu
384            && sess.target.options.cfg_abi == CfgAbi::Llvm)
385    {
386        match sess.opts.cg.control_flow_guard {
387            CFGuard::Disabled => {}
388            CFGuard::NoChecks => {
389                // Set `cfguard=1` module flag to emit metadata only.
390                llvm::add_module_flag_u32(
391                    llmod,
392                    llvm::ModuleFlagMergeBehavior::Warning,
393                    "cfguard",
394                    1,
395                );
396            }
397            CFGuard::Checks => {
398                // Set `cfguard=2` module flag to emit metadata and checks.
399                llvm::add_module_flag_u32(
400                    llmod,
401                    llvm::ModuleFlagMergeBehavior::Warning,
402                    "cfguard",
403                    2,
404                );
405            }
406        }
407    }
408
409    if let Some(regparm_count) = sess.opts.unstable_opts.regparm {
410        llvm::add_module_flag_u32(
411            llmod,
412            llvm::ModuleFlagMergeBehavior::Error,
413            "NumRegisterParameters",
414            regparm_count,
415        );
416    }
417
418    if let Some(BranchProtection { bti, pac_ret, gcs }) = sess.branch_protection() {
419        if sess.target.arch == Arch::AArch64 {
420            llvm::add_module_flag_u32(
421                llmod,
422                llvm::ModuleFlagMergeBehavior::Min,
423                "branch-target-enforcement",
424                bti.into(),
425            );
426            llvm::add_module_flag_u32(
427                llmod,
428                llvm::ModuleFlagMergeBehavior::Min,
429                "sign-return-address",
430                pac_ret.is_some().into(),
431            );
432            let pac_opts = pac_ret.unwrap_or_else(|| {
433                // Windows on Arm only supports PAC key B.
434                let key = if sess.target.os == Os::Windows { PAuthKey::B } else { PAuthKey::A };
435                PacRet { leaf: false, pc: false, key }
436            });
437            llvm::add_module_flag_u32(
438                llmod,
439                llvm::ModuleFlagMergeBehavior::Min,
440                "branch-protection-pauth-lr",
441                pac_opts.pc.into(),
442            );
443            llvm::add_module_flag_u32(
444                llmod,
445                llvm::ModuleFlagMergeBehavior::Min,
446                "sign-return-address-all",
447                pac_opts.leaf.into(),
448            );
449            llvm::add_module_flag_u32(
450                llmod,
451                llvm::ModuleFlagMergeBehavior::Min,
452                "sign-return-address-with-bkey",
453                u32::from(pac_opts.key == PAuthKey::B),
454            );
455            llvm::add_module_flag_u32(
456                llmod,
457                llvm::ModuleFlagMergeBehavior::Min,
458                "guarded-control-stack",
459                gcs.into(),
460            );
461        } else {
462            bug_impl(None,
    format_args!("branch-protection used on non-AArch64 target; this should be checked in rustc_session."),
    Location::caller());bug!(
463                "branch-protection used on non-AArch64 target; \
464                  this should be checked in rustc_session."
465            );
466        }
467    }
468
469    // Pass on the control-flow protection flags to LLVM (equivalent to `-fcf-protection` in Clang).
470    if let CFProtection::Branch | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
471        llvm::add_module_flag_u32(
472            llmod,
473            llvm::ModuleFlagMergeBehavior::Override,
474            "cf-protection-branch",
475            1,
476        );
477    }
478    if let CFProtection::Return | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
479        llvm::add_module_flag_u32(
480            llmod,
481            llvm::ModuleFlagMergeBehavior::Override,
482            "cf-protection-return",
483            1,
484        );
485    }
486
487    if sess.opts.unstable_opts.virtual_function_elimination {
488        llvm::add_module_flag_u32(
489            llmod,
490            llvm::ModuleFlagMergeBehavior::Error,
491            "Virtual Function Elim",
492            1,
493        );
494    }
495
496    // Set module flag to enable Windows EHCont Guard (/guard:ehcont).
497    if sess.opts.unstable_opts.ehcont_guard {
498        llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "ehcontguard", 1);
499    }
500
501    match sess.opts.unstable_opts.function_return {
502        FunctionReturn::Keep => {}
503        FunctionReturn::ThunkExtern => {
504            llvm::add_module_flag_u32(
505                llmod,
506                llvm::ModuleFlagMergeBehavior::Override,
507                "function_return_thunk_extern",
508                1,
509            );
510        }
511    }
512
513    let fp = attributes::frame_pointer(sess);
514    if fp != FramePointer::MayOmit {
515        llvm::add_module_flag_u32(
516            llmod,
517            llvm::ModuleFlagMergeBehavior::Max,
518            "frame-pointer",
519            match fp {
520                FramePointer::Always => llvm::FramePointerKind::All as u32,
521                FramePointer::NonLeaf => llvm::FramePointerKind::NonLeaf as u32,
522                FramePointer::MayOmit => llvm::FramePointerKind::None as u32,
523            },
524        );
525    }
526
527    if sess.opts.unstable_opts.indirect_branch_cs_prefix {
528        llvm::add_module_flag_u32(
529            llmod,
530            llvm::ModuleFlagMergeBehavior::Override,
531            "indirect_branch_cs_prefix",
532            1,
533        );
534    }
535
536    match (sess.opts.unstable_opts.small_data_threshold, sess.target.small_data_threshold_support())
537    {
538        // Set up the small-data optimization limit for architectures that use
539        // an LLVM module flag to control this.
540        (Some(threshold), SmallDataThresholdSupport::LlvmModuleFlag(flag)) => {
541            llvm::add_module_flag_u32(
542                llmod,
543                llvm::ModuleFlagMergeBehavior::Error,
544                &flag,
545                threshold as u32,
546            );
547        }
548        _ => (),
549    };
550
551    // Insert `llvm.ident` metadata.
552    //
553    // On the wasm targets it will get hooked up to the "producer" sections
554    // `processed-by` information.
555    #[allow(clippy::option_env_unwrap)]
556    let rustc_producer =
557        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("rustc version {0}",
                ::core::option::Option::Some("1.100.0-nightly (923c95cdf 2026-09-16)").expect("CFG_VERSION")))
    })format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"));
558
559    let name_metadata = cx.create_metadata(rustc_producer.as_bytes());
560    cx.module_add_named_metadata_node(llmod, c"llvm.ident", &[name_metadata]);
561
562    // Emit RISC-V specific target-abi metadata
563    // to workaround lld as the LTO plugin not
564    // correctly setting target-abi for the LTO object
565    // FIXME: https://github.com/llvm/llvm-project/issues/50591
566    let llvm_abiname = &sess.target.options.llvm_abiname;
567    if #[allow(non_exhaustive_omitted_patterns)] match sess.target.arch {
    Arch::RiscV32 | Arch::RiscV64 => true,
    _ => false,
}matches!(sess.target.arch, Arch::RiscV32 | Arch::RiscV64) {
568        llvm::add_module_flag_str(
569            llmod,
570            llvm::ModuleFlagMergeBehavior::Error,
571            "target-abi",
572            llvm_abiname.desc(),
573        );
574    }
575
576    if llvm_version >= (24, 0, 0)
577        && let Some(floatabi) = sess.target.llvm_floatabi
578    {
579        llvm::add_module_flag_str(
580            llmod,
581            llvm::ModuleFlagMergeBehavior::Error,
582            "float-abi",
583            floatabi.desc(),
584        );
585    }
586
587    // Add module flags specified via -Z llvm_module_flag
588    for (key, value, merge_behavior) in &sess.opts.unstable_opts.llvm_module_flag {
589        let merge_behavior = match merge_behavior.as_str() {
590            "error" => llvm::ModuleFlagMergeBehavior::Error,
591            "warning" => llvm::ModuleFlagMergeBehavior::Warning,
592            "require" => llvm::ModuleFlagMergeBehavior::Require,
593            "override" => llvm::ModuleFlagMergeBehavior::Override,
594            "append" => llvm::ModuleFlagMergeBehavior::Append,
595            "appendunique" => llvm::ModuleFlagMergeBehavior::AppendUnique,
596            "max" => llvm::ModuleFlagMergeBehavior::Max,
597            "min" => llvm::ModuleFlagMergeBehavior::Min,
598            // We already checked this during option parsing
599            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
600        };
601        llvm::add_module_flag_u32(llmod, merge_behavior, key, *value);
602    }
603
604    llmod
605}
606
607impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
608    pub(crate) fn new(
609        tcx: TyCtxt<'tcx>,
610        codegen_unit: &'tcx CodegenUnit<'tcx>,
611        llvm_module: &'ll crate::ModuleLlvm,
612        bitcode_needed: bool,
613    ) -> Self {
614        // An interesting part of Windows which MSVC forces our hand on (and
615        // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
616        // attributes in LLVM IR as well as native dependencies (in C these
617        // correspond to `__declspec(dllimport)`).
618        //
619        // LD (BFD) in MinGW mode can often correctly guess `dllexport` but
620        // relying on that can result in issues like #50176.
621        // LLD won't support that and expects symbols with proper attributes.
622        // Because of that we make MinGW target emit dllexport just like MSVC.
623        // When it comes to dllimport we use it for constants but for functions
624        // rely on the linker to do the right thing. Opposed to dllexport this
625        // task is easy for them (both LD and LLD) and allows us to easily use
626        // symbols from static libraries in shared libraries.
627        //
628        // Whenever a dynamic library is built on Windows it must have its public
629        // interface specified by functions tagged with `dllexport` or otherwise
630        // they're not available to be linked against. This poses a few problems
631        // for the compiler, some of which are somewhat fundamental, but we use
632        // the `use_dll_storage_attrs` variable below to attach the `dllexport`
633        // attribute to all LLVM functions that are exported e.g., they're
634        // already tagged with external linkage). This is suboptimal for a few
635        // reasons:
636        //
637        // * If an object file will never be included in a dynamic library,
638        //   there's no need to attach the dllexport attribute. Most object
639        //   files in Rust are not destined to become part of a dll as binaries
640        //   are statically linked by default.
641        // * If the compiler is emitting both an rlib and a dylib, the same
642        //   source object file is currently used but with MSVC this may be less
643        //   feasible. The compiler may be able to get around this, but it may
644        //   involve some invasive changes to deal with this.
645        //
646        // The flip side of this situation is that whenever you link to a dll and
647        // you import a function from it, the import should be tagged with
648        // `dllimport`. At this time, however, the compiler does not emit
649        // `dllimport` for any declarations other than constants (where it is
650        // required), which is again suboptimal for even more reasons!
651        //
652        // * Calling a function imported from another dll without using
653        //   `dllimport` causes the linker/compiler to have extra overhead (one
654        //   `jmp` instruction on x86) when calling the function.
655        // * The same object file may be used in different circumstances, so a
656        //   function may be imported from a dll if the object is linked into a
657        //   dll, but it may be just linked against if linked into an rlib.
658        // * The compiler has no knowledge about whether native functions should
659        //   be tagged dllimport or not.
660        //
661        // For now the compiler takes the perf hit (I do not have any numbers to
662        // this effect) by marking very little as `dllimport` and praying the
663        // linker will take care of everything. Fixing this problem will likely
664        // require adding a few attributes to Rust itself (feature gated at the
665        // start) and then strongly recommending static linkage on Windows!
666        let use_dll_storage_attrs = tcx.sess.target.is_like_windows;
667
668        let tls_model = to_llvm_tls_model(tcx.sess.tls_model());
669
670        let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod());
671
672        let coverage_cx =
673            tcx.sess.instrument_coverage().then(coverageinfo::CguCoverageContext::new);
674
675        let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
676            let dctx = debuginfo::CodegenUnitDebugContext::new(llmod, tcx.sess);
677            debuginfo::metadata::build_compile_unit_di_node(
678                tcx,
679                codegen_unit.name().as_str(),
680                &dctx,
681            );
682            Some(dctx)
683        } else {
684            None
685        };
686
687        // FIXME: This parses the ignorelist files for each CGU, which adds a performance overhead.
688        // Clang parses it once per frontend invocation. LLVM's `SpecialCaseList::inSection`
689        // mutates an internal `LazyInit` cache and is not thread-safe. We either need to wrap
690        // the queries in a lock or wait for LLVM to expose a thread-safe way to query it.
691        let sanitizer_ignorelist = if !tcx.sess.opts.unstable_opts.sanitizer_ignorelist.is_empty() {
692            for path in &tcx.sess.opts.unstable_opts.sanitizer_ignorelist {
693                let _ = tcx.sess.source_map().load_file(std::path::Path::new(path));
694            }
695            match SanitizerIgnoreList::new(&tcx.sess.opts.unstable_opts.sanitizer_ignorelist) {
696                Ok(list) => Some(list),
697                Err(err) => {
698                    tcx.dcx().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to parse sanitizer ignorelist: {0}",
                err))
    })format!("failed to parse sanitizer ignorelist: {}", err));
699                }
700            }
701        } else {
702            None
703        };
704
705        GenericCx(
706            FullCx {
707                tcx,
708                bitcode_needed,
709                scx: SimpleCx::new(llmod, llcx, tcx.data_layout.pointer_size()),
710                use_dll_storage_attrs,
711                tls_model,
712                codegen_unit,
713                instances: Default::default(),
714                intrinsic_instances: Default::default(),
715                vtables: Default::default(),
716                const_str_cache: Default::default(),
717                const_globals: Default::default(),
718                statics_to_rauw: RefCell::new(Vec::new()),
719                used_statics: Vec::new(),
720                compiler_used_statics: Default::default(),
721                type_lowering: Default::default(),
722                scalar_lltypes: Default::default(),
723                coverage_cx,
724                dbg_cx,
725                sanitizer_ignorelist,
726                eh_personality: Cell::new(None),
727                rust_try_fn: Cell::new(None),
728                intrinsics: Default::default(),
729                local_gen_sym_counter: Cell::new(0),
730                global_gen_sym_counter: Cell::new(0),
731                renamed_statics: Default::default(),
732                objc_class_t: Cell::new(None),
733                objc_classrefs: Default::default(),
734                objc_selrefs: Default::default(),
735                offload_globals: Default::default(),
736                offload_kernel_cache: Default::default(),
737            },
738            PhantomData,
739        )
740    }
741
742    pub(crate) fn statics_to_rauw(&self) -> &RefCell<Vec<(&'ll Value, &'ll Value)>> {
743        &self.statics_to_rauw
744    }
745
746    /// Extra state that is only available when coverage instrumentation is enabled.
747    #[inline]
748    #[track_caller]
749    pub(crate) fn coverage_cx(&self) -> &coverageinfo::CguCoverageContext<'ll, 'tcx> {
750        self.coverage_cx.as_ref().expect("only called when coverage instrumentation is enabled")
751    }
752
753    pub(crate) fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) {
754        let array = self.const_array(self.type_ptr(), values);
755
756        let g = llvm::add_global(self.llmod, self.val_ty(array), name);
757        llvm::set_initializer(g, array);
758        llvm::set_linkage(g, llvm::Linkage::AppendingLinkage);
759        llvm::set_section(g, c"llvm.metadata");
760    }
761
762    /// The Objective-C ABI that is used.
763    ///
764    /// This corresponds to the `-fobjc-abi-version=` flag in Clang / GCC.
765    pub(crate) fn objc_abi_version(&self) -> u32 {
766        if !self.tcx.sess.target.is_like_darwin {
    ::core::panicking::panic("assertion failed: self.tcx.sess.target.is_like_darwin")
};assert!(self.tcx.sess.target.is_like_darwin);
767        if self.tcx.sess.target.arch == Arch::X86 && self.tcx.sess.target.os == Os::MacOs {
768            // 32-bit x86 macOS uses ABI version 1 (a.k.a. the "fragile ABI").
769            1
770        } else {
771            // All other Darwin-like targets we support use ABI version 2
772            // (a.k.a the "non-fragile ABI").
773            2
774        }
775    }
776
777    pub(crate) fn add_ptrauth_elf_got_flag(&self) {
778        llvm::add_module_flag_u32(
779            self.llmod,
780            llvm::ModuleFlagMergeBehavior::Error,
781            "ptrauth-elf-got",
782            1,
783        );
784    }
785
786    pub(crate) fn add_ptrauth_sign_personality_flag(&self) {
787        llvm::add_module_flag_u32(
788            self.llmod,
789            llvm::ModuleFlagMergeBehavior::Error,
790            "ptrauth-sign-personality",
791            1,
792        );
793    }
794
795    pub(crate) fn add_ptrauth_pauthabi_version_and_platform_flags(
796        &self,
797        aarch64_elf_pauthabi_version: u32,
798    ) {
799        // NOTE: This must correspond to llvm's AARCH64_PAUTH_PLATFORM_LLVM_LINUX, as defined in
800        // <llvm_root>/llvm/include/llvm/BinaryFormat/ELF.h.
801        // FIXME (jchlanda) extend possible values once we start supporting other platforms (for
802        // example: AARCH64_PAUTH_PLATFORM_BAREMETAL = 0x1);
803        const AARCH64_PAUTH_PLATFORM_LLVM_LINUX: u32 = 0x10000002;
804        llvm::add_module_flag_u32(
805            self.llmod,
806            llvm::ModuleFlagMergeBehavior::Error,
807            "aarch64-elf-pauthabi-platform",
808            AARCH64_PAUTH_PLATFORM_LLVM_LINUX,
809        );
810        llvm::add_module_flag_u32(
811            self.llmod,
812            llvm::ModuleFlagMergeBehavior::Error,
813            "aarch64-elf-pauthabi-version",
814            aarch64_elf_pauthabi_version,
815        );
816    }
817
818    // We do our best here to match what Clang does when compiling Objective-C natively.
819    // See Clang's `CGObjCCommonMac::EmitImageInfo`:
820    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5085
821    pub(crate) fn add_objc_module_flags(&self) {
822        let abi_version = self.objc_abi_version();
823
824        llvm::add_module_flag_u32(
825            self.llmod,
826            llvm::ModuleFlagMergeBehavior::Error,
827            "Objective-C Version",
828            abi_version,
829        );
830
831        llvm::add_module_flag_u32(
832            self.llmod,
833            llvm::ModuleFlagMergeBehavior::Error,
834            "Objective-C Image Info Version",
835            0,
836        );
837
838        llvm::add_module_flag_str(
839            self.llmod,
840            llvm::ModuleFlagMergeBehavior::Error,
841            "Objective-C Image Info Section",
842            match abi_version {
843                1 => "__OBJC,__image_info,regular",
844                2 => "__DATA,__objc_imageinfo,regular,no_dead_strip",
845                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
846            },
847        );
848
849        if self.tcx.sess.target.env == Env::Sim {
850            llvm::add_module_flag_u32(
851                self.llmod,
852                llvm::ModuleFlagMergeBehavior::Error,
853                "Objective-C Is Simulated",
854                1 << 5,
855            );
856        }
857
858        llvm::add_module_flag_u32(
859            self.llmod,
860            llvm::ModuleFlagMergeBehavior::Error,
861            "Objective-C Class Properties",
862            1 << 6,
863        );
864    }
865
866    pub(crate) fn is_sanitizer_type_ignored(
867        &self,
868        sanitizer: &std::ffi::CStr,
869        fn_abi: &rustc_target::callconv::FnAbi<'tcx, Ty<'tcx>>,
870    ) -> bool {
871        self.sanitizer_ignorelist.as_ref().is_some_and(|ignorelist| {
872            let type_name = typename_for_ignore_list(self.tcx, fn_abi);
873            ignorelist.contains_prefix(sanitizer, c"type", &type_name)
874        })
875    }
876}
877impl<'ll> SimpleCx<'ll> {
878    pub(crate) fn get_type_of_global(&self, val: &'ll Value) -> &'ll Type {
879        unsafe { llvm::LLVMGlobalGetValueType(val) }
880    }
881    pub(crate) fn val_ty(&self, v: &'ll Value) -> &'ll Type {
882        common::val_ty(v)
883    }
884}
885impl<'ll> SimpleCx<'ll> {
886    pub(crate) fn new(
887        llmod: &'ll llvm::Module,
888        llcx: &'ll llvm::Context,
889        pointer_size: Size,
890    ) -> Self {
891        let isize_ty = llvm::LLVMIntTypeInContext(llcx, pointer_size.bits() as c_uint);
892        Self(SCx { llmod, llcx, isize_ty }, PhantomData)
893    }
894}
895
896impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
897    pub(crate) fn get_metadata_value(&self, metadata: &'ll Metadata) -> &'ll Value {
898        llvm::LLVMMetadataAsValue(self.llcx(), metadata)
899    }
900
901    pub(crate) fn get_const_int(&self, ty: &'ll Type, val: u64) -> &'ll Value {
902        unsafe { llvm::LLVMConstInt(ty, val, llvm::FALSE) }
903    }
904
905    pub(crate) fn get_const_i64(&self, n: u64) -> &'ll Value {
906        self.get_const_int(self.type_i64(), n)
907    }
908
909    pub(crate) fn get_const_i32(&self, n: u64) -> &'ll Value {
910        self.get_const_int(self.type_i32(), n)
911    }
912
913    pub(crate) fn get_const_i16(&self, n: u64) -> &'ll Value {
914        self.get_const_int(self.type_i16(), n)
915    }
916
917    pub(crate) fn get_const_i8(&self, n: u64) -> &'ll Value {
918        self.get_const_int(self.type_i8(), n)
919    }
920
921    pub(crate) fn get_md_kind_id(&self, name: &str) -> llvm::MetadataKindId {
922        unsafe {
923            llvm::LLVMGetMDKindIDInContext(
924                self.llcx(),
925                name.as_ptr() as *const c_char,
926                name.len() as c_uint,
927            )
928        }
929    }
930
931    pub(crate) fn create_metadata(&self, name: &[u8]) -> &'ll Metadata {
932        unsafe {
933            llvm::LLVMMDStringInContext2(self.llcx(), name.as_ptr() as *const c_char, name.len())
934        }
935    }
936
937    pub(crate) fn get_functions(&self) -> Vec<&'ll Value> {
938        let mut functions = ::alloc::vec::Vec::new()vec![];
939        let mut func = unsafe { llvm::LLVMGetFirstFunction(self.llmod()) };
940        while let Some(f) = func {
941            functions.push(f);
942            func = unsafe { llvm::LLVMGetNextFunction(f) }
943        }
944        functions
945    }
946}
947
948impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
949    fn vtables(
950        &self,
951    ) -> &RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>> {
952        &self.vtables
953    }
954
955    fn apply_vcall_visibility_metadata(
956        &self,
957        ty: Ty<'tcx>,
958        poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
959        vtable: &'ll Value,
960    ) {
961        apply_vcall_visibility_metadata(self, ty, poly_trait_ref, vtable);
962    }
963
964    fn get_fn(&self, instance: Instance<'tcx>) -> &'ll Value {
965        get_fn(self, instance)
966    }
967
968    fn get_fn_addr(
969        &self,
970        instance: Instance<'tcx>,
971        pointer_auth_schema: Option<&PointerAuthSchema>,
972    ) -> &'ll Value {
973        // When pointer authentication metadata is provided, `get_fn_addr` will
974        // attempt to sign the pointer using LLVM's `ConstPtrAuth` constant
975        // expression.
976        //
977        // FIXME(jchlanda) Currently, all function addresses requested from
978        // within LLVM codegen are signed. This behavior is too broad, resulting
979        // in the logic being applied to function values, not just pointers
980        // (addresses).
981        //
982        // See the discussion in the rust-lang issue:
983        // <https://github.com/rust-lang/rust/issues/152532>, and comment in
984        // builder's `ptrauth_operand_bundle`.
985        let llfn = get_fn(self, instance);
986        match pointer_auth_schema {
987            Some(schema) => common::maybe_sign_fn_ptr(self, instance, llfn, schema),
988            None => llfn,
989        }
990    }
991
992    fn eh_personality(&self) -> &'ll Value {
993        // The exception handling personality function.
994        //
995        // If our compilation unit has the `eh_personality` lang item somewhere
996        // within it, then we just need to codegen that. Otherwise, we're
997        // building an rlib which will depend on some upstream implementation of
998        // this function, so we just codegen a generic reference to it. We don't
999        // specify any of the types for the function, we just make it a symbol
1000        // that LLVM can later use.
1001        //
1002        // Note that MSVC is a little special here in that we don't use the
1003        // `eh_personality` lang item at all. Currently LLVM has support for
1004        // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
1005        // *name of the personality function* to decide what kind of unwind side
1006        // tables/landing pads to emit. It looks like Dwarf is used by default,
1007        // injecting a dependency on the `_Unwind_Resume` symbol for resuming
1008        // an "exception", but for MSVC we want to force SEH. This means that we
1009        // can't actually have the personality function be our standard
1010        // `rust_eh_personality` function, but rather we wired it up to the
1011        // CRT's custom personality function, which forces LLVM to consider
1012        // landing pads as "landing pads for SEH".
1013        if let Some(llpersonality) = self.eh_personality.get() {
1014            return llpersonality;
1015        }
1016
1017        let name = if wants_msvc_seh(&self.sess().target) {
1018            Some("__CxxFrameHandler3")
1019        } else if wants_wasm_eh(&self.sess().target) {
1020            // LLVM specifically tests for the name of the personality function
1021            // There is no need for this function to exist anywhere, it will
1022            // not be called. However, its name has to be "__gxx_wasm_personality_v0"
1023            // for native wasm exceptions.
1024            Some("__gxx_wasm_personality_v0")
1025        } else {
1026            None
1027        };
1028
1029        let tcx = self.tcx;
1030        let llfn = match tcx.lang_items().eh_personality() {
1031            Some(def_id) if name.is_none() => self.get_fn_addr(
1032                ty::Instance::expect_resolve(
1033                    tcx,
1034                    self.typing_env(),
1035                    def_id,
1036                    ty::List::empty(),
1037                    DUMMY_SP,
1038                ),
1039                tcx.sess.pointer_authentication_functions(),
1040            ),
1041            _ => {
1042                let name = name.unwrap_or("rust_eh_personality");
1043                if let Some(llfn) = self.get_declared_value(name) {
1044                    llfn
1045                } else {
1046                    let fty = self.type_variadic_func(&[], self.type_i32());
1047                    let llfn = self.declare_cfn(name, llvm::UnnamedAddr::Global, fty);
1048                    let target_cpu = attributes::target_cpu_attr(self, self.sess());
1049                    attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[target_cpu]);
1050                    llfn
1051                }
1052            }
1053        };
1054        self.eh_personality.set(Some(llfn));
1055        llfn
1056    }
1057
1058    fn sess(&self) -> &Session {
1059        self.tcx.sess
1060    }
1061
1062    fn set_frame_pointer_type(&self, llfn: &'ll Value) {
1063        if let Some(attr) = attributes::frame_pointer_type_attr(self, self.sess()) {
1064            attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[attr]);
1065        }
1066    }
1067
1068    fn apply_target_cpu_attr(&self, llfn: &'ll Value) {
1069        let mut attrs = SmallVec::<[_; 2]>::new();
1070        attrs.push(attributes::target_cpu_attr(self, self.sess()));
1071        attrs.extend(attributes::tune_cpu_attr(self, self.sess()));
1072        attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &attrs);
1073    }
1074
1075    fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
1076        let entry_name = self.sess().target.entry_name.as_ref();
1077        if self.get_declared_value(entry_name).is_none() {
1078            let llfn = self.declare_entry_fn(
1079                entry_name,
1080                to_llvm_calling_convention(self.sess(), self.sess().target.entry_abi),
1081                llvm::UnnamedAddr::Global,
1082                fn_type,
1083            );
1084            attributes::apply_to_llfn(
1085                llfn,
1086                llvm::AttributePlace::Function,
1087                attributes::target_features_attr(self, self.tcx, ::alloc::vec::Vec::new()vec![]).as_slice(),
1088            );
1089            Some(llfn)
1090        } else {
1091            // If the symbol already exists, it is an error: for example, the user wrote
1092            // #[no_mangle] extern "C" fn main(..) {..}
1093            None
1094        }
1095    }
1096
1097    fn intrinsic_call_expects_place_always(&self, name: Symbol) -> bool {
1098        #[allow(non_exhaustive_omitted_patterns)] match name {
    sym::black_box => true,
    _ => false,
}matches!(name, sym::black_box)
1099    }
1100}
1101
1102impl<'ll> CodegenCx<'ll, '_> {
1103    pub(crate) fn get_intrinsic(
1104        &self,
1105        base_name: Cow<'static, str>,
1106        type_params: &[&'ll Type],
1107    ) -> (&'ll Type, &'ll Value) {
1108        *self
1109            .intrinsics
1110            .borrow_mut()
1111            .entry((base_name, SmallVec::from_slice(type_params)))
1112            .or_insert_with_key(|(base_name, type_params)| {
1113                self.declare_intrinsic(base_name, type_params)
1114            })
1115    }
1116
1117    fn declare_intrinsic(
1118        &self,
1119        base_name: &str,
1120        type_params: &[&'ll Type],
1121    ) -> (&'ll Type, &'ll Value) {
1122        match base_name {
1123            // This isn't an "LLVM intrinsic", but LLVM's optimization passes
1124            // recognize it like one (including turning it into `bcmp` sometimes)
1125            // and we use it to implement intrinsics like `raw_eq` and `compare_bytes`
1126            "memcmp" => {
1127                let fn_ty = self.type_func(
1128                    &[self.type_ptr(), self.type_ptr(), self.type_isize()],
1129                    self.type_int(),
1130                );
1131                let f = self.declare_cfn("memcmp", llvm::UnnamedAddr::No, fn_ty);
1132
1133                (fn_ty, f)
1134            }
1135            // Experimental retag intrinsics.
1136            // This form is used to retag a pointer that has already been stored in a register. It receives
1137            // the pointer and returns an alias with the same address, but different provenance.
1138            "__rust_retag_reg" => {
1139                let fn_ty = self.type_func(type_params, self.type_ptr());
1140                let llfn = self.declare_cfn(base_name, llvm::UnnamedAddr::No, fn_ty);
1141                let nounwind = llvm::AttributeKind::NoUnwind.create_attr(self.llcx);
1142                attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[nounwind]);
1143                (fn_ty, llfn)
1144            }
1145            // This form is used to retag a pointer that is stored in another place. It receives a pointer to the
1146            // place and returns `void`. This communicates the indirection  without requiring an explicit load and
1147            // store. If we used the `reg` form instead, then we would need to load the place, retag it, and then
1148            // store the result back, which would be undefined behavior for `readonly` places.
1149            "__rust_retag_mem" => {
1150                let fn_ty = self.type_func(type_params, self.type_void());
1151                let llfn = self.declare_cfn(base_name, llvm::UnnamedAddr::No, fn_ty);
1152                let nounwind = llvm::AttributeKind::NoUnwind.create_attr(self.llcx);
1153                attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[nounwind]);
1154                (fn_ty, llfn)
1155            }
1156            _ => {
1157                let intrinsic = llvm::Intrinsic::lookup(base_name.as_bytes())
1158                    .unwrap_or_else(|| bug_impl(None, format_args!("Unknown intrinsic: `{0}`", base_name),
    Location::caller())bug!("Unknown intrinsic: `{base_name}`"));
1159                let f = intrinsic.get_declaration(self.llmod, &type_params);
1160                (self.get_type_of_global(f), f)
1161            }
1162        }
1163    }
1164}
1165
1166impl CodegenCx<'_, '_> {
1167    /// Generates a new symbol name with the given prefix. This symbol name must
1168    /// only be used for definitions with `internal` or `private` linkage.
1169    pub(crate) fn generate_local_symbol_name(&self, prefix: &str) -> String {
1170        let idx = self.local_gen_sym_counter.get();
1171        self.local_gen_sym_counter.set(idx + 1);
1172        // Include a '.' character, so there can be no accidental conflicts with
1173        // user defined names
1174        let mut name = String::with_capacity(prefix.len() + 6);
1175        name.push_str(prefix);
1176        name.push('.');
1177        name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY));
1178        name
1179    }
1180
1181    /// Generates a new global symbol name with the given prefix.
1182    pub(crate) fn generate_global_symbol_name(&self) -> String {
1183        let idx = self.global_gen_sym_counter.get();
1184        self.global_gen_sym_counter.set(idx + 1);
1185
1186        let sym = self.codegen_unit.symbol_name();
1187        let prefix = sym.as_str();
1188        let mut name = String::with_capacity(prefix.len() + 6);
1189        name.push_str(prefix);
1190        name.push('.');
1191        name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY));
1192        name
1193    }
1194}
1195
1196impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
1197    /// Wrapper for `LLVMMDNodeInContext2`, i.e. `llvm::MDNode::get`.
1198    pub(crate) fn md_node_in_context(&self, md_list: &[&'ll Metadata]) -> &'ll Metadata {
1199        unsafe { llvm::LLVMMDNodeInContext2(self.llcx(), md_list.as_ptr(), md_list.len()) }
1200    }
1201
1202    /// A wrapper for [`llvm::LLVMSetMetadata`], but it takes `Metadata` as a parameter instead of `Value`.
1203    pub(crate) fn set_metadata<'a>(
1204        &self,
1205        val: &'a Value,
1206        kind_id: MetadataKindId,
1207        md: &'ll Metadata,
1208    ) {
1209        let node = self.get_metadata_value(md);
1210        llvm::LLVMSetMetadata(val, kind_id, node);
1211    }
1212
1213    /// Helper method for the sequence of calls:
1214    /// - `LLVMMDNodeInContext2` (to create an `llvm::MDNode` from a list of metadata)
1215    /// - `LLVMMetadataAsValue` (to adapt that node to an `llvm::Value`)
1216    /// - `LLVMSetMetadata` (to set that node as metadata of `kind_id` for `instruction`)
1217    pub(crate) fn set_metadata_node(
1218        &self,
1219        instruction: &'ll Value,
1220        kind_id: MetadataKindId,
1221        md_list: &[&'ll Metadata],
1222    ) -> &'ll Metadata {
1223        let md = self.md_node_in_context(md_list);
1224        self.set_metadata(instruction, kind_id, md);
1225        md
1226    }
1227
1228    /// Helper method for the sequence of calls:
1229    /// - `LLVMMDNodeInContext2` (to create an `llvm::MDNode` from a list of metadata)
1230    /// - `LLVMMetadataAsValue` (to adapt that node to an `llvm::Value`)
1231    /// - `LLVMAddNamedMetadataOperand` (to set that node as metadata of `kind_name` for `module`)
1232    pub(crate) fn module_add_named_metadata_node(
1233        &self,
1234        module: &'ll Module,
1235        kind_name: &CStr,
1236        md_list: &[&'ll Metadata],
1237    ) {
1238        let md = self.md_node_in_context(md_list);
1239        let md_as_val = self.get_metadata_value(md);
1240        unsafe { llvm::LLVMAddNamedMetadataOperand(module, kind_name.as_ptr(), md_as_val) };
1241    }
1242
1243    /// Helper method for the sequence of calls:
1244    /// - `LLVMMDNodeInContext2` (to create an `llvm::MDNode` from a list of metadata)
1245    /// - `LLVMRustGlobalAddMetadata` (to set that node as metadata of `kind_id` for `global`)
1246    pub(crate) fn global_add_metadata_node(
1247        &self,
1248        global: &'ll Value,
1249        kind_id: MetadataKindId,
1250        md_list: &[&'ll Metadata],
1251    ) {
1252        let md = self.md_node_in_context(md_list);
1253        unsafe { llvm::LLVMRustGlobalAddMetadata(global, kind_id, md) };
1254    }
1255
1256    /// Helper method for the sequence of calls:
1257    /// - `LLVMMDNodeInContext2` (to create an `llvm::MDNode` from a list of metadata)
1258    /// - `LLVMGlobalSetMetadata` (to set that node as metadata of `kind_id` for `global`)
1259    pub(crate) fn global_set_metadata_node(
1260        &self,
1261        global: &'ll Value,
1262        kind_id: MetadataKindId,
1263        md_list: &[&'ll Metadata],
1264    ) {
1265        let md = self.md_node_in_context(md_list);
1266        unsafe { llvm::LLVMGlobalSetMetadata(global, kind_id, md) };
1267    }
1268}
1269
1270impl HasDataLayout for CodegenCx<'_, '_> {
1271    #[inline]
1272    fn data_layout(&self) -> &TargetDataLayout {
1273        &self.tcx.data_layout
1274    }
1275}
1276
1277impl HasTargetSpec for CodegenCx<'_, '_> {
1278    #[inline]
1279    fn target_spec(&self) -> &Target {
1280        &self.tcx.sess.target
1281    }
1282}
1283
1284impl<'tcx> ty::layout::HasTyCtxt<'tcx> for CodegenCx<'_, 'tcx> {
1285    #[inline]
1286    fn tcx(&self) -> TyCtxt<'tcx> {
1287        self.tcx
1288    }
1289}
1290
1291impl<'tcx, 'll> HasTypingEnv<'tcx> for CodegenCx<'ll, 'tcx> {
1292    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
1293        ty::TypingEnv::fully_monomorphized()
1294    }
1295}
1296
1297impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
1298    #[inline]
1299    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
1300        if let LayoutError::SizeOverflow(_)
1301        | LayoutError::ReferencesError(_)
1302        | LayoutError::InvalidSimd { .. } = err
1303        {
1304            self.tcx.dcx().span_fatal(span, err.to_string())
1305        } else {
1306            self.tcx.dcx().emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err })
1307        }
1308    }
1309}
1310
1311impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
1312    #[inline]
1313    fn handle_fn_abi_err(
1314        &self,
1315        err: FnAbiError<'tcx>,
1316        span: Span,
1317        fn_abi_request: FnAbiRequest<'tcx>,
1318    ) -> ! {
1319        codegen_handle_fn_abi_err(self.tcx, err, span, fn_abi_request).raise_fatal()
1320    }
1321}