Skip to main content

rustc_codegen_llvm/
context.rs

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