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