rustc_codegen_llvm/
context.rs

1use std::borrow::Borrow;
2use std::cell::{Cell, RefCell};
3use std::ffi::{CStr, c_char, c_uint};
4use std::ops::Deref;
5use std::str;
6
7use rustc_abi::{HasDataLayout, TargetDataLayout, VariantIdx};
8use rustc_codegen_ssa::back::versioned_llvm_target;
9use rustc_codegen_ssa::base::{wants_msvc_seh, wants_wasm_eh};
10use rustc_codegen_ssa::common::TypeKind;
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::middle::codegen_fn_attrs::PatchableFunctionEntry;
18use rustc_middle::mir::mono::CodegenUnit;
19use rustc_middle::ty::layout::{
20    FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTypingEnv, LayoutError, LayoutOfHelpers,
21};
22use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
23use rustc_middle::{bug, span_bug};
24use rustc_session::Session;
25use rustc_session::config::{
26    BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, FunctionReturn, PAuthKey, PacRet,
27};
28use rustc_span::source_map::Spanned;
29use rustc_span::{DUMMY_SP, Span};
30use rustc_target::spec::{HasTargetSpec, RelocModel, SmallDataThresholdSupport, Target, TlsModel};
31use smallvec::SmallVec;
32
33use crate::back::write::to_llvm_code_model;
34use crate::callee::get_fn;
35use crate::common::{self, AsCCharPtr};
36use crate::debuginfo::metadata::apply_vcall_visibility_metadata;
37use crate::llvm::{Metadata, MetadataType};
38use crate::type_::Type;
39use crate::value::Value;
40use crate::{attributes, coverageinfo, debuginfo, llvm, 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 SimpleCx<'ll> {
47    pub llmod: &'ll llvm::Module,
48    pub llcx: &'ll llvm::Context,
49}
50
51impl<'ll> Borrow<SimpleCx<'ll>> for CodegenCx<'ll, '_> {
52    fn borrow(&self) -> &SimpleCx<'ll> {
53        &self.scx
54    }
55}
56
57impl<'ll, 'tcx> Deref for CodegenCx<'ll, 'tcx> {
58    type Target = SimpleCx<'ll>;
59
60    #[inline]
61    fn deref(&self) -> &Self::Target {
62        &self.scx
63    }
64}
65
66/// There is one `CodegenCx` per codegen unit. Each one has its own LLVM
67/// `llvm::Context` so that several codegen units may be processed in parallel.
68/// All other LLVM data structures in the `CodegenCx` are tied to that `llvm::Context`.
69pub(crate) struct CodegenCx<'ll, 'tcx> {
70    pub tcx: TyCtxt<'tcx>,
71    pub scx: SimpleCx<'ll>,
72    pub use_dll_storage_attrs: bool,
73    pub tls_model: llvm::ThreadLocalMode,
74
75    pub codegen_unit: &'tcx CodegenUnit<'tcx>,
76
77    /// Cache instances of monomorphic and polymorphic items
78    pub instances: RefCell<FxHashMap<Instance<'tcx>, &'ll Value>>,
79    /// Cache generated vtables
80    pub vtables: RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>>,
81    /// Cache of constant strings,
82    pub const_str_cache: RefCell<FxHashMap<String, &'ll Value>>,
83
84    /// Cache of emitted const globals (value -> global)
85    pub const_globals: RefCell<FxHashMap<&'ll Value, &'ll Value>>,
86
87    /// List of globals for static variables which need to be passed to the
88    /// LLVM function ReplaceAllUsesWith (RAUW) when codegen is complete.
89    /// (We have to make sure we don't invalidate any Values referring
90    /// to constants.)
91    pub statics_to_rauw: RefCell<Vec<(&'ll Value, &'ll Value)>>,
92
93    /// Statics that will be placed in the llvm.used variable
94    /// See <https://llvm.org/docs/LangRef.html#the-llvm-used-global-variable> for details
95    pub used_statics: RefCell<Vec<&'ll Value>>,
96
97    /// Statics that will be placed in the llvm.compiler.used variable
98    /// See <https://llvm.org/docs/LangRef.html#the-llvm-compiler-used-global-variable> for details
99    pub compiler_used_statics: RefCell<Vec<&'ll Value>>,
100
101    /// Mapping of non-scalar types to llvm types.
102    pub type_lowering: RefCell<FxHashMap<(Ty<'tcx>, Option<VariantIdx>), &'ll Type>>,
103
104    /// Mapping of scalar types to llvm types.
105    pub scalar_lltypes: RefCell<FxHashMap<Ty<'tcx>, &'ll Type>>,
106
107    pub isize_ty: &'ll Type,
108
109    /// Extra per-CGU codegen state needed when coverage instrumentation is enabled.
110    pub coverage_cx: Option<coverageinfo::CguCoverageContext<'ll, 'tcx>>,
111    pub dbg_cx: Option<debuginfo::CodegenUnitDebugContext<'ll, 'tcx>>,
112
113    eh_personality: Cell<Option<&'ll Value>>,
114    eh_catch_typeinfo: Cell<Option<&'ll Value>>,
115    pub rust_try_fn: Cell<Option<(&'ll Type, &'ll Value)>>,
116
117    intrinsics: RefCell<FxHashMap<&'static str, (&'ll Type, &'ll Value)>>,
118
119    /// A counter that is used for generating local symbol names
120    local_gen_sym_counter: Cell<usize>,
121
122    /// `codegen_static` will sometimes create a second global variable with a
123    /// different type and clear the symbol name of the original global.
124    /// `global_asm!` needs to be able to find this new global so that it can
125    /// compute the correct mangled symbol name to insert into the asm.
126    pub renamed_statics: RefCell<FxHashMap<DefId, &'ll Value>>,
127}
128
129fn to_llvm_tls_model(tls_model: TlsModel) -> llvm::ThreadLocalMode {
130    match tls_model {
131        TlsModel::GeneralDynamic => llvm::ThreadLocalMode::GeneralDynamic,
132        TlsModel::LocalDynamic => llvm::ThreadLocalMode::LocalDynamic,
133        TlsModel::InitialExec => llvm::ThreadLocalMode::InitialExec,
134        TlsModel::LocalExec => llvm::ThreadLocalMode::LocalExec,
135        TlsModel::Emulated => llvm::ThreadLocalMode::GeneralDynamic,
136    }
137}
138
139pub(crate) unsafe fn create_module<'ll>(
140    tcx: TyCtxt<'_>,
141    llcx: &'ll llvm::Context,
142    mod_name: &str,
143) -> &'ll llvm::Module {
144    let sess = tcx.sess;
145    let mod_name = SmallCStr::new(mod_name);
146    let llmod = unsafe { llvm::LLVMModuleCreateWithNameInContext(mod_name.as_ptr(), llcx) };
147
148    let mut target_data_layout = sess.target.data_layout.to_string();
149    let llvm_version = llvm_util::get_version();
150
151    if llvm_version < (19, 0, 0) {
152        if sess.target.arch == "aarch64" || sess.target.arch.starts_with("arm64") {
153            // LLVM 19 sets -Fn32 in its data layout string for 64-bit ARM
154            // Earlier LLVMs leave this default, so remove it.
155            // See https://github.com/llvm/llvm-project/pull/90702
156            target_data_layout = target_data_layout.replace("-Fn32", "");
157        }
158    }
159
160    if llvm_version < (19, 0, 0) {
161        if sess.target.arch == "loongarch64" {
162            // LLVM 19 updates the LoongArch64 data layout.
163            // See https://github.com/llvm/llvm-project/pull/93814
164            target_data_layout = target_data_layout.replace("-n32:64", "-n64");
165        }
166    }
167
168    if llvm_version < (20, 0, 0) {
169        if sess.target.arch == "aarch64" || sess.target.arch.starts_with("arm64") {
170            // LLVM 20 defines three additional address spaces for alternate
171            // pointer kinds used in Windows.
172            // See https://github.com/llvm/llvm-project/pull/111879
173            target_data_layout =
174                target_data_layout.replace("-p270:32:32-p271:32:32-p272:64:64", "");
175        }
176        if sess.target.arch.starts_with("sparc") {
177            // LLVM 20 updates the sparc layout to correctly align 128 bit integers to 128 bit.
178            // See https://github.com/llvm/llvm-project/pull/106951
179            target_data_layout = target_data_layout.replace("-i128:128", "");
180        }
181        if sess.target.arch.starts_with("mips64") {
182            // LLVM 20 updates the mips64 layout to correctly align 128 bit integers to 128 bit.
183            // See https://github.com/llvm/llvm-project/pull/112084
184            target_data_layout = target_data_layout.replace("-i128:128", "");
185        }
186        if sess.target.arch.starts_with("powerpc64") {
187            // LLVM 20 updates the powerpc64 layout to correctly align 128 bit integers to 128 bit.
188            // See https://github.com/llvm/llvm-project/pull/118004
189            target_data_layout = target_data_layout.replace("-i128:128", "");
190        }
191        if sess.target.arch.starts_with("wasm32") || sess.target.arch.starts_with("wasm64") {
192            // LLVM 20 updates the wasm(32|64) layout to correctly align 128 bit integers to 128 bit.
193            // See https://github.com/llvm/llvm-project/pull/119204
194            target_data_layout = target_data_layout.replace("-i128:128", "");
195        }
196    }
197
198    // Ensure the data-layout values hardcoded remain the defaults.
199    {
200        let tm = crate::back::write::create_informational_target_machine(tcx.sess, false);
201        unsafe {
202            llvm::LLVMRustSetDataLayoutFromTargetMachine(llmod, &tm);
203        }
204
205        let llvm_data_layout = unsafe { llvm::LLVMGetDataLayoutStr(llmod) };
206        let llvm_data_layout =
207            str::from_utf8(unsafe { CStr::from_ptr(llvm_data_layout) }.to_bytes())
208                .expect("got a non-UTF8 data-layout from LLVM");
209
210        if target_data_layout != llvm_data_layout {
211            tcx.dcx().emit_err(crate::errors::MismatchedDataLayout {
212                rustc_target: sess.opts.target_triple.to_string().as_str(),
213                rustc_layout: target_data_layout.as_str(),
214                llvm_target: sess.target.llvm_target.borrow(),
215                llvm_layout: llvm_data_layout,
216            });
217        }
218    }
219
220    let data_layout = SmallCStr::new(&target_data_layout);
221    unsafe {
222        llvm::LLVMSetDataLayout(llmod, data_layout.as_ptr());
223    }
224
225    let llvm_target = SmallCStr::new(&versioned_llvm_target(sess));
226    unsafe {
227        llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
228    }
229
230    let reloc_model = sess.relocation_model();
231    if matches!(reloc_model, RelocModel::Pic | RelocModel::Pie) {
232        unsafe {
233            llvm::LLVMRustSetModulePICLevel(llmod);
234        }
235        // PIE is potentially more effective than PIC, but can only be used in executables.
236        // If all our outputs are executables, then we can relax PIC to PIE.
237        if reloc_model == RelocModel::Pie
238            || tcx.crate_types().iter().all(|ty| *ty == CrateType::Executable)
239        {
240            unsafe {
241                llvm::LLVMRustSetModulePIELevel(llmod);
242            }
243        }
244    }
245
246    // Linking object files with different code models is undefined behavior
247    // because the compiler would have to generate additional code (to span
248    // longer jumps) if a larger code model is used with a smaller one.
249    //
250    // See https://reviews.llvm.org/D52322 and https://reviews.llvm.org/D52323.
251    unsafe {
252        llvm::LLVMRustSetModuleCodeModel(llmod, to_llvm_code_model(sess.code_model()));
253    }
254
255    // If skipping the PLT is enabled, we need to add some module metadata
256    // to ensure intrinsic calls don't use it.
257    if !sess.needs_plt() {
258        llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "RtLibUseGOT", 1);
259    }
260
261    // Enable canonical jump tables if CFI is enabled. (See https://reviews.llvm.org/D65629.)
262    if sess.is_sanitizer_cfi_canonical_jump_tables_enabled() && sess.is_sanitizer_cfi_enabled() {
263        llvm::add_module_flag_u32(
264            llmod,
265            llvm::ModuleFlagMergeBehavior::Override,
266            "CFI Canonical Jump Tables",
267            1,
268        );
269    }
270
271    // If we're normalizing integers with CFI, ensure LLVM generated functions do the same.
272    // See https://github.com/llvm/llvm-project/pull/104826
273    if sess.is_sanitizer_cfi_normalize_integers_enabled() {
274        llvm::add_module_flag_u32(
275            llmod,
276            llvm::ModuleFlagMergeBehavior::Override,
277            "cfi-normalize-integers",
278            1,
279        );
280    }
281
282    // Enable LTO unit splitting if specified or if CFI is enabled. (See
283    // https://reviews.llvm.org/D53891.)
284    if sess.is_split_lto_unit_enabled() || sess.is_sanitizer_cfi_enabled() {
285        llvm::add_module_flag_u32(
286            llmod,
287            llvm::ModuleFlagMergeBehavior::Override,
288            "EnableSplitLTOUnit",
289            1,
290        );
291    }
292
293    // Add "kcfi" module flag if KCFI is enabled. (See https://reviews.llvm.org/D119296.)
294    if sess.is_sanitizer_kcfi_enabled() {
295        llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Override, "kcfi", 1);
296
297        // Add "kcfi-offset" module flag with -Z patchable-function-entry (See
298        // https://reviews.llvm.org/D141172).
299        let pfe =
300            PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry);
301        if pfe.prefix() > 0 {
302            llvm::add_module_flag_u32(
303                llmod,
304                llvm::ModuleFlagMergeBehavior::Override,
305                "kcfi-offset",
306                pfe.prefix().into(),
307            );
308        }
309    }
310
311    // Control Flow Guard is currently only supported by MSVC and LLVM on Windows.
312    if sess.target.is_like_msvc
313        || (sess.target.options.os == "windows"
314            && sess.target.options.env == "gnu"
315            && sess.target.options.abi == "llvm")
316    {
317        match sess.opts.cg.control_flow_guard {
318            CFGuard::Disabled => {}
319            CFGuard::NoChecks => {
320                // Set `cfguard=1` module flag to emit metadata only.
321                llvm::add_module_flag_u32(
322                    llmod,
323                    llvm::ModuleFlagMergeBehavior::Warning,
324                    "cfguard",
325                    1,
326                );
327            }
328            CFGuard::Checks => {
329                // Set `cfguard=2` module flag to emit metadata and checks.
330                llvm::add_module_flag_u32(
331                    llmod,
332                    llvm::ModuleFlagMergeBehavior::Warning,
333                    "cfguard",
334                    2,
335                );
336            }
337        }
338    }
339
340    if let Some(BranchProtection { bti, pac_ret }) = sess.opts.unstable_opts.branch_protection {
341        if sess.target.arch == "aarch64" {
342            llvm::add_module_flag_u32(
343                llmod,
344                llvm::ModuleFlagMergeBehavior::Min,
345                "branch-target-enforcement",
346                bti.into(),
347            );
348            llvm::add_module_flag_u32(
349                llmod,
350                llvm::ModuleFlagMergeBehavior::Min,
351                "sign-return-address",
352                pac_ret.is_some().into(),
353            );
354            let pac_opts = pac_ret.unwrap_or(PacRet { leaf: false, pc: false, key: PAuthKey::A });
355            llvm::add_module_flag_u32(
356                llmod,
357                llvm::ModuleFlagMergeBehavior::Min,
358                "branch-protection-pauth-lr",
359                pac_opts.pc.into(),
360            );
361            llvm::add_module_flag_u32(
362                llmod,
363                llvm::ModuleFlagMergeBehavior::Min,
364                "sign-return-address-all",
365                pac_opts.leaf.into(),
366            );
367            llvm::add_module_flag_u32(
368                llmod,
369                llvm::ModuleFlagMergeBehavior::Min,
370                "sign-return-address-with-bkey",
371                u32::from(pac_opts.key == PAuthKey::B),
372            );
373        } else {
374            bug!(
375                "branch-protection used on non-AArch64 target; \
376                  this should be checked in rustc_session."
377            );
378        }
379    }
380
381    // Pass on the control-flow protection flags to LLVM (equivalent to `-fcf-protection` in Clang).
382    if let CFProtection::Branch | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
383        llvm::add_module_flag_u32(
384            llmod,
385            llvm::ModuleFlagMergeBehavior::Override,
386            "cf-protection-branch",
387            1,
388        );
389    }
390    if let CFProtection::Return | CFProtection::Full = sess.opts.unstable_opts.cf_protection {
391        llvm::add_module_flag_u32(
392            llmod,
393            llvm::ModuleFlagMergeBehavior::Override,
394            "cf-protection-return",
395            1,
396        );
397    }
398
399    if sess.opts.unstable_opts.virtual_function_elimination {
400        llvm::add_module_flag_u32(
401            llmod,
402            llvm::ModuleFlagMergeBehavior::Error,
403            "Virtual Function Elim",
404            1,
405        );
406    }
407
408    // Set module flag to enable Windows EHCont Guard (/guard:ehcont).
409    if sess.opts.unstable_opts.ehcont_guard {
410        llvm::add_module_flag_u32(llmod, llvm::ModuleFlagMergeBehavior::Warning, "ehcontguard", 1);
411    }
412
413    match sess.opts.unstable_opts.function_return {
414        FunctionReturn::Keep => {}
415        FunctionReturn::ThunkExtern => {
416            llvm::add_module_flag_u32(
417                llmod,
418                llvm::ModuleFlagMergeBehavior::Override,
419                "function_return_thunk_extern",
420                1,
421            );
422        }
423    }
424
425    match (sess.opts.unstable_opts.small_data_threshold, sess.target.small_data_threshold_support())
426    {
427        // Set up the small-data optimization limit for architectures that use
428        // an LLVM module flag to control this.
429        (Some(threshold), SmallDataThresholdSupport::LlvmModuleFlag(flag)) => {
430            llvm::add_module_flag_u32(
431                llmod,
432                llvm::ModuleFlagMergeBehavior::Error,
433                &flag,
434                threshold as u32,
435            );
436        }
437        _ => (),
438    };
439
440    // Insert `llvm.ident` metadata.
441    //
442    // On the wasm targets it will get hooked up to the "producer" sections
443    // `processed-by` information.
444    #[allow(clippy::option_env_unwrap)]
445    let rustc_producer =
446        format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION"));
447    let name_metadata = unsafe {
448        llvm::LLVMMDStringInContext2(
449            llcx,
450            rustc_producer.as_c_char_ptr(),
451            rustc_producer.as_bytes().len(),
452        )
453    };
454    unsafe {
455        llvm::LLVMAddNamedMetadataOperand(
456            llmod,
457            c"llvm.ident".as_ptr(),
458            &llvm::LLVMMetadataAsValue(llcx, llvm::LLVMMDNodeInContext2(llcx, &name_metadata, 1)),
459        );
460    }
461
462    // Emit RISC-V specific target-abi metadata
463    // to workaround lld as the LTO plugin not
464    // correctly setting target-abi for the LTO object
465    // FIXME: https://github.com/llvm/llvm-project/issues/50591
466    // If llvm_abiname is empty, emit nothing.
467    let llvm_abiname = &sess.target.options.llvm_abiname;
468    if matches!(sess.target.arch.as_ref(), "riscv32" | "riscv64") && !llvm_abiname.is_empty() {
469        llvm::add_module_flag_str(
470            llmod,
471            llvm::ModuleFlagMergeBehavior::Error,
472            "target-abi",
473            llvm_abiname,
474        );
475    }
476
477    // Add module flags specified via -Z llvm_module_flag
478    for (key, value, merge_behavior) in &sess.opts.unstable_opts.llvm_module_flag {
479        let merge_behavior = match merge_behavior.as_str() {
480            "error" => llvm::ModuleFlagMergeBehavior::Error,
481            "warning" => llvm::ModuleFlagMergeBehavior::Warning,
482            "require" => llvm::ModuleFlagMergeBehavior::Require,
483            "override" => llvm::ModuleFlagMergeBehavior::Override,
484            "append" => llvm::ModuleFlagMergeBehavior::Append,
485            "appendunique" => llvm::ModuleFlagMergeBehavior::AppendUnique,
486            "max" => llvm::ModuleFlagMergeBehavior::Max,
487            "min" => llvm::ModuleFlagMergeBehavior::Min,
488            // We already checked this during option parsing
489            _ => unreachable!(),
490        };
491        llvm::add_module_flag_u32(llmod, merge_behavior, key, *value);
492    }
493
494    llmod
495}
496
497impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
498    pub(crate) fn new(
499        tcx: TyCtxt<'tcx>,
500        codegen_unit: &'tcx CodegenUnit<'tcx>,
501        llvm_module: &'ll crate::ModuleLlvm,
502    ) -> Self {
503        // An interesting part of Windows which MSVC forces our hand on (and
504        // apparently MinGW didn't) is the usage of `dllimport` and `dllexport`
505        // attributes in LLVM IR as well as native dependencies (in C these
506        // correspond to `__declspec(dllimport)`).
507        //
508        // LD (BFD) in MinGW mode can often correctly guess `dllexport` but
509        // relying on that can result in issues like #50176.
510        // LLD won't support that and expects symbols with proper attributes.
511        // Because of that we make MinGW target emit dllexport just like MSVC.
512        // When it comes to dllimport we use it for constants but for functions
513        // rely on the linker to do the right thing. Opposed to dllexport this
514        // task is easy for them (both LD and LLD) and allows us to easily use
515        // symbols from static libraries in shared libraries.
516        //
517        // Whenever a dynamic library is built on Windows it must have its public
518        // interface specified by functions tagged with `dllexport` or otherwise
519        // they're not available to be linked against. This poses a few problems
520        // for the compiler, some of which are somewhat fundamental, but we use
521        // the `use_dll_storage_attrs` variable below to attach the `dllexport`
522        // attribute to all LLVM functions that are exported e.g., they're
523        // already tagged with external linkage). This is suboptimal for a few
524        // reasons:
525        //
526        // * If an object file will never be included in a dynamic library,
527        //   there's no need to attach the dllexport attribute. Most object
528        //   files in Rust are not destined to become part of a dll as binaries
529        //   are statically linked by default.
530        // * If the compiler is emitting both an rlib and a dylib, the same
531        //   source object file is currently used but with MSVC this may be less
532        //   feasible. The compiler may be able to get around this, but it may
533        //   involve some invasive changes to deal with this.
534        //
535        // The flip side of this situation is that whenever you link to a dll and
536        // you import a function from it, the import should be tagged with
537        // `dllimport`. At this time, however, the compiler does not emit
538        // `dllimport` for any declarations other than constants (where it is
539        // required), which is again suboptimal for even more reasons!
540        //
541        // * Calling a function imported from another dll without using
542        //   `dllimport` causes the linker/compiler to have extra overhead (one
543        //   `jmp` instruction on x86) when calling the function.
544        // * The same object file may be used in different circumstances, so a
545        //   function may be imported from a dll if the object is linked into a
546        //   dll, but it may be just linked against if linked into an rlib.
547        // * The compiler has no knowledge about whether native functions should
548        //   be tagged dllimport or not.
549        //
550        // For now the compiler takes the perf hit (I do not have any numbers to
551        // this effect) by marking very little as `dllimport` and praying the
552        // linker will take care of everything. Fixing this problem will likely
553        // require adding a few attributes to Rust itself (feature gated at the
554        // start) and then strongly recommending static linkage on Windows!
555        let use_dll_storage_attrs = tcx.sess.target.is_like_windows;
556
557        let tls_model = to_llvm_tls_model(tcx.sess.tls_model());
558
559        let (llcx, llmod) = (&*llvm_module.llcx, llvm_module.llmod());
560
561        let coverage_cx =
562            tcx.sess.instrument_coverage().then(coverageinfo::CguCoverageContext::new);
563
564        let dbg_cx = if tcx.sess.opts.debuginfo != DebugInfo::None {
565            let dctx = debuginfo::CodegenUnitDebugContext::new(llmod);
566            debuginfo::metadata::build_compile_unit_di_node(
567                tcx,
568                codegen_unit.name().as_str(),
569                &dctx,
570            );
571            Some(dctx)
572        } else {
573            None
574        };
575
576        let isize_ty = Type::ix_llcx(llcx, tcx.data_layout.pointer_size.bits());
577
578        CodegenCx {
579            tcx,
580            scx: SimpleCx { llcx, llmod },
581            use_dll_storage_attrs,
582            tls_model,
583            codegen_unit,
584            instances: Default::default(),
585            vtables: Default::default(),
586            const_str_cache: Default::default(),
587            const_globals: Default::default(),
588            statics_to_rauw: RefCell::new(Vec::new()),
589            used_statics: RefCell::new(Vec::new()),
590            compiler_used_statics: RefCell::new(Vec::new()),
591            type_lowering: Default::default(),
592            scalar_lltypes: Default::default(),
593            isize_ty,
594            coverage_cx,
595            dbg_cx,
596            eh_personality: Cell::new(None),
597            eh_catch_typeinfo: Cell::new(None),
598            rust_try_fn: Cell::new(None),
599            intrinsics: Default::default(),
600            local_gen_sym_counter: Cell::new(0),
601            renamed_statics: Default::default(),
602        }
603    }
604
605    pub(crate) fn statics_to_rauw(&self) -> &RefCell<Vec<(&'ll Value, &'ll Value)>> {
606        &self.statics_to_rauw
607    }
608
609    /// Extra state that is only available when coverage instrumentation is enabled.
610    #[inline]
611    #[track_caller]
612    pub(crate) fn coverage_cx(&self) -> &coverageinfo::CguCoverageContext<'ll, 'tcx> {
613        self.coverage_cx.as_ref().expect("only called when coverage instrumentation is enabled")
614    }
615
616    pub(crate) fn create_used_variable_impl(&self, name: &'static CStr, values: &[&'ll Value]) {
617        let array = self.const_array(self.type_ptr(), values);
618
619        let g = llvm::add_global(self.llmod, self.val_ty(array), name);
620        llvm::set_initializer(g, array);
621        llvm::set_linkage(g, llvm::Linkage::AppendingLinkage);
622        llvm::set_section(g, c"llvm.metadata");
623    }
624}
625impl<'ll> SimpleCx<'ll> {
626    pub(crate) fn val_ty(&self, v: &'ll Value) -> &'ll Type {
627        common::val_ty(v)
628    }
629
630    pub(crate) fn get_metadata_value(&self, metadata: &'ll Metadata) -> &'ll Value {
631        unsafe { llvm::LLVMMetadataAsValue(self.llcx, metadata) }
632    }
633
634    pub(crate) fn get_function(&self, name: &str) -> Option<&'ll Value> {
635        let name = SmallCStr::new(name);
636        unsafe { llvm::LLVMGetNamedFunction(self.llmod, name.as_ptr()) }
637    }
638
639    pub(crate) fn get_md_kind_id(&self, name: &str) -> u32 {
640        unsafe {
641            llvm::LLVMGetMDKindIDInContext(
642                self.llcx,
643                name.as_ptr() as *const c_char,
644                name.len() as c_uint,
645            )
646        }
647    }
648
649    pub(crate) fn create_metadata(&self, name: String) -> Option<&'ll Metadata> {
650        Some(unsafe {
651            llvm::LLVMMDStringInContext2(self.llcx, name.as_ptr() as *const c_char, name.len())
652        })
653    }
654
655    pub(crate) fn type_kind(&self, ty: &'ll Type) -> TypeKind {
656        unsafe { llvm::LLVMRustGetTypeKind(ty).to_generic() }
657    }
658}
659
660impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
661    fn vtables(
662        &self,
663    ) -> &RefCell<FxHashMap<(Ty<'tcx>, Option<ty::ExistentialTraitRef<'tcx>>), &'ll Value>> {
664        &self.vtables
665    }
666
667    fn apply_vcall_visibility_metadata(
668        &self,
669        ty: Ty<'tcx>,
670        poly_trait_ref: Option<ty::ExistentialTraitRef<'tcx>>,
671        vtable: &'ll Value,
672    ) {
673        apply_vcall_visibility_metadata(self, ty, poly_trait_ref, vtable);
674    }
675
676    fn get_fn(&self, instance: Instance<'tcx>) -> &'ll Value {
677        get_fn(self, instance)
678    }
679
680    fn get_fn_addr(&self, instance: Instance<'tcx>) -> &'ll Value {
681        get_fn(self, instance)
682    }
683
684    fn eh_personality(&self) -> &'ll Value {
685        // The exception handling personality function.
686        //
687        // If our compilation unit has the `eh_personality` lang item somewhere
688        // within it, then we just need to codegen that. Otherwise, we're
689        // building an rlib which will depend on some upstream implementation of
690        // this function, so we just codegen a generic reference to it. We don't
691        // specify any of the types for the function, we just make it a symbol
692        // that LLVM can later use.
693        //
694        // Note that MSVC is a little special here in that we don't use the
695        // `eh_personality` lang item at all. Currently LLVM has support for
696        // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
697        // *name of the personality function* to decide what kind of unwind side
698        // tables/landing pads to emit. It looks like Dwarf is used by default,
699        // injecting a dependency on the `_Unwind_Resume` symbol for resuming
700        // an "exception", but for MSVC we want to force SEH. This means that we
701        // can't actually have the personality function be our standard
702        // `rust_eh_personality` function, but rather we wired it up to the
703        // CRT's custom personality function, which forces LLVM to consider
704        // landing pads as "landing pads for SEH".
705        if let Some(llpersonality) = self.eh_personality.get() {
706            return llpersonality;
707        }
708
709        let name = if wants_msvc_seh(self.sess()) {
710            Some("__CxxFrameHandler3")
711        } else if wants_wasm_eh(self.sess()) {
712            // LLVM specifically tests for the name of the personality function
713            // There is no need for this function to exist anywhere, it will
714            // not be called. However, its name has to be "__gxx_wasm_personality_v0"
715            // for native wasm exceptions.
716            Some("__gxx_wasm_personality_v0")
717        } else {
718            None
719        };
720
721        let tcx = self.tcx;
722        let llfn = match tcx.lang_items().eh_personality() {
723            Some(def_id) if name.is_none() => self.get_fn_addr(ty::Instance::expect_resolve(
724                tcx,
725                self.typing_env(),
726                def_id,
727                ty::List::empty(),
728                DUMMY_SP,
729            )),
730            _ => {
731                let name = name.unwrap_or("rust_eh_personality");
732                if let Some(llfn) = self.get_declared_value(name) {
733                    llfn
734                } else {
735                    let fty = self.type_variadic_func(&[], self.type_i32());
736                    let llfn = self.declare_cfn(name, llvm::UnnamedAddr::Global, fty);
737                    let target_cpu = attributes::target_cpu_attr(self);
738                    attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[target_cpu]);
739                    llfn
740                }
741            }
742        };
743        self.eh_personality.set(Some(llfn));
744        llfn
745    }
746
747    fn sess(&self) -> &Session {
748        self.tcx.sess
749    }
750
751    fn codegen_unit(&self) -> &'tcx CodegenUnit<'tcx> {
752        self.codegen_unit
753    }
754
755    fn set_frame_pointer_type(&self, llfn: &'ll Value) {
756        if let Some(attr) = attributes::frame_pointer_type_attr(self) {
757            attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &[attr]);
758        }
759    }
760
761    fn apply_target_cpu_attr(&self, llfn: &'ll Value) {
762        let mut attrs = SmallVec::<[_; 2]>::new();
763        attrs.push(attributes::target_cpu_attr(self));
764        attrs.extend(attributes::tune_cpu_attr(self));
765        attributes::apply_to_llfn(llfn, llvm::AttributePlace::Function, &attrs);
766    }
767
768    fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
769        let entry_name = self.sess().target.entry_name.as_ref();
770        if self.get_declared_value(entry_name).is_none() {
771            Some(self.declare_entry_fn(
772                entry_name,
773                llvm::CallConv::from_conv(
774                    self.sess().target.entry_abi,
775                    self.sess().target.arch.borrow(),
776                ),
777                llvm::UnnamedAddr::Global,
778                fn_type,
779            ))
780        } else {
781            // If the symbol already exists, it is an error: for example, the user wrote
782            // #[no_mangle] extern "C" fn main(..) {..}
783            None
784        }
785    }
786}
787
788impl<'ll> CodegenCx<'ll, '_> {
789    pub(crate) fn get_intrinsic(&self, key: &str) -> (&'ll Type, &'ll Value) {
790        if let Some(v) = self.intrinsics.borrow().get(key).cloned() {
791            return v;
792        }
793
794        self.declare_intrinsic(key).unwrap_or_else(|| bug!("unknown intrinsic '{}'", key))
795    }
796
797    fn insert_intrinsic(
798        &self,
799        name: &'static str,
800        args: Option<&[&'ll llvm::Type]>,
801        ret: &'ll llvm::Type,
802    ) -> (&'ll llvm::Type, &'ll llvm::Value) {
803        let fn_ty = if let Some(args) = args {
804            self.type_func(args, ret)
805        } else {
806            self.type_variadic_func(&[], ret)
807        };
808        let f = self.declare_cfn(name, llvm::UnnamedAddr::No, fn_ty);
809        self.intrinsics.borrow_mut().insert(name, (fn_ty, f));
810        (fn_ty, f)
811    }
812
813    fn declare_intrinsic(&self, key: &str) -> Option<(&'ll Type, &'ll Value)> {
814        macro_rules! ifn {
815            ($name:expr, fn() -> $ret:expr) => (
816                if key == $name {
817                    return Some(self.insert_intrinsic($name, Some(&[]), $ret));
818                }
819            );
820            ($name:expr, fn(...) -> $ret:expr) => (
821                if key == $name {
822                    return Some(self.insert_intrinsic($name, None, $ret));
823                }
824            );
825            ($name:expr, fn($($arg:expr),*) -> $ret:expr) => (
826                if key == $name {
827                    return Some(self.insert_intrinsic($name, Some(&[$($arg),*]), $ret));
828                }
829            );
830        }
831        macro_rules! mk_struct {
832            ($($field_ty:expr),*) => (self.type_struct( &[$($field_ty),*], false))
833        }
834
835        let ptr = self.type_ptr();
836        let void = self.type_void();
837        let i1 = self.type_i1();
838        let t_i8 = self.type_i8();
839        let t_i16 = self.type_i16();
840        let t_i32 = self.type_i32();
841        let t_i64 = self.type_i64();
842        let t_i128 = self.type_i128();
843        let t_isize = self.type_isize();
844        let t_f16 = self.type_f16();
845        let t_f32 = self.type_f32();
846        let t_f64 = self.type_f64();
847        let t_f128 = self.type_f128();
848        let t_metadata = self.type_metadata();
849        let t_token = self.type_token();
850
851        ifn!("llvm.wasm.get.exception", fn(t_token) -> ptr);
852        ifn!("llvm.wasm.get.ehselector", fn(t_token) -> t_i32);
853
854        ifn!("llvm.wasm.trunc.unsigned.i32.f32", fn(t_f32) -> t_i32);
855        ifn!("llvm.wasm.trunc.unsigned.i32.f64", fn(t_f64) -> t_i32);
856        ifn!("llvm.wasm.trunc.unsigned.i64.f32", fn(t_f32) -> t_i64);
857        ifn!("llvm.wasm.trunc.unsigned.i64.f64", fn(t_f64) -> t_i64);
858        ifn!("llvm.wasm.trunc.signed.i32.f32", fn(t_f32) -> t_i32);
859        ifn!("llvm.wasm.trunc.signed.i32.f64", fn(t_f64) -> t_i32);
860        ifn!("llvm.wasm.trunc.signed.i64.f32", fn(t_f32) -> t_i64);
861        ifn!("llvm.wasm.trunc.signed.i64.f64", fn(t_f64) -> t_i64);
862
863        ifn!("llvm.fptosi.sat.i8.f32", fn(t_f32) -> t_i8);
864        ifn!("llvm.fptosi.sat.i16.f32", fn(t_f32) -> t_i16);
865        ifn!("llvm.fptosi.sat.i32.f32", fn(t_f32) -> t_i32);
866        ifn!("llvm.fptosi.sat.i64.f32", fn(t_f32) -> t_i64);
867        ifn!("llvm.fptosi.sat.i128.f32", fn(t_f32) -> t_i128);
868        ifn!("llvm.fptosi.sat.i8.f64", fn(t_f64) -> t_i8);
869        ifn!("llvm.fptosi.sat.i16.f64", fn(t_f64) -> t_i16);
870        ifn!("llvm.fptosi.sat.i32.f64", fn(t_f64) -> t_i32);
871        ifn!("llvm.fptosi.sat.i64.f64", fn(t_f64) -> t_i64);
872        ifn!("llvm.fptosi.sat.i128.f64", fn(t_f64) -> t_i128);
873
874        ifn!("llvm.fptoui.sat.i8.f32", fn(t_f32) -> t_i8);
875        ifn!("llvm.fptoui.sat.i16.f32", fn(t_f32) -> t_i16);
876        ifn!("llvm.fptoui.sat.i32.f32", fn(t_f32) -> t_i32);
877        ifn!("llvm.fptoui.sat.i64.f32", fn(t_f32) -> t_i64);
878        ifn!("llvm.fptoui.sat.i128.f32", fn(t_f32) -> t_i128);
879        ifn!("llvm.fptoui.sat.i8.f64", fn(t_f64) -> t_i8);
880        ifn!("llvm.fptoui.sat.i16.f64", fn(t_f64) -> t_i16);
881        ifn!("llvm.fptoui.sat.i32.f64", fn(t_f64) -> t_i32);
882        ifn!("llvm.fptoui.sat.i64.f64", fn(t_f64) -> t_i64);
883        ifn!("llvm.fptoui.sat.i128.f64", fn(t_f64) -> t_i128);
884
885        ifn!("llvm.trap", fn() -> void);
886        ifn!("llvm.debugtrap", fn() -> void);
887        ifn!("llvm.frameaddress", fn(t_i32) -> ptr);
888
889        ifn!("llvm.powi.f16.i32", fn(t_f16, t_i32) -> t_f16);
890        ifn!("llvm.powi.f32.i32", fn(t_f32, t_i32) -> t_f32);
891        ifn!("llvm.powi.f64.i32", fn(t_f64, t_i32) -> t_f64);
892        ifn!("llvm.powi.f128.i32", fn(t_f128, t_i32) -> t_f128);
893
894        ifn!("llvm.pow.f16", fn(t_f16, t_f16) -> t_f16);
895        ifn!("llvm.pow.f32", fn(t_f32, t_f32) -> t_f32);
896        ifn!("llvm.pow.f64", fn(t_f64, t_f64) -> t_f64);
897        ifn!("llvm.pow.f128", fn(t_f128, t_f128) -> t_f128);
898
899        ifn!("llvm.sqrt.f16", fn(t_f16) -> t_f16);
900        ifn!("llvm.sqrt.f32", fn(t_f32) -> t_f32);
901        ifn!("llvm.sqrt.f64", fn(t_f64) -> t_f64);
902        ifn!("llvm.sqrt.f128", fn(t_f128) -> t_f128);
903
904        ifn!("llvm.sin.f16", fn(t_f16) -> t_f16);
905        ifn!("llvm.sin.f32", fn(t_f32) -> t_f32);
906        ifn!("llvm.sin.f64", fn(t_f64) -> t_f64);
907        ifn!("llvm.sin.f128", fn(t_f128) -> t_f128);
908
909        ifn!("llvm.cos.f16", fn(t_f16) -> t_f16);
910        ifn!("llvm.cos.f32", fn(t_f32) -> t_f32);
911        ifn!("llvm.cos.f64", fn(t_f64) -> t_f64);
912        ifn!("llvm.cos.f128", fn(t_f128) -> t_f128);
913
914        ifn!("llvm.exp.f16", fn(t_f16) -> t_f16);
915        ifn!("llvm.exp.f32", fn(t_f32) -> t_f32);
916        ifn!("llvm.exp.f64", fn(t_f64) -> t_f64);
917        ifn!("llvm.exp.f128", fn(t_f128) -> t_f128);
918
919        ifn!("llvm.exp2.f16", fn(t_f16) -> t_f16);
920        ifn!("llvm.exp2.f32", fn(t_f32) -> t_f32);
921        ifn!("llvm.exp2.f64", fn(t_f64) -> t_f64);
922        ifn!("llvm.exp2.f128", fn(t_f128) -> t_f128);
923
924        ifn!("llvm.log.f16", fn(t_f16) -> t_f16);
925        ifn!("llvm.log.f32", fn(t_f32) -> t_f32);
926        ifn!("llvm.log.f64", fn(t_f64) -> t_f64);
927        ifn!("llvm.log.f128", fn(t_f128) -> t_f128);
928
929        ifn!("llvm.log10.f16", fn(t_f16) -> t_f16);
930        ifn!("llvm.log10.f32", fn(t_f32) -> t_f32);
931        ifn!("llvm.log10.f64", fn(t_f64) -> t_f64);
932        ifn!("llvm.log10.f128", fn(t_f128) -> t_f128);
933
934        ifn!("llvm.log2.f16", fn(t_f16) -> t_f16);
935        ifn!("llvm.log2.f32", fn(t_f32) -> t_f32);
936        ifn!("llvm.log2.f64", fn(t_f64) -> t_f64);
937        ifn!("llvm.log2.f128", fn(t_f128) -> t_f128);
938
939        ifn!("llvm.fma.f16", fn(t_f16, t_f16, t_f16) -> t_f16);
940        ifn!("llvm.fma.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
941        ifn!("llvm.fma.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
942        ifn!("llvm.fma.f128", fn(t_f128, t_f128, t_f128) -> t_f128);
943
944        ifn!("llvm.fmuladd.f16", fn(t_f16, t_f16, t_f16) -> t_f16);
945        ifn!("llvm.fmuladd.f32", fn(t_f32, t_f32, t_f32) -> t_f32);
946        ifn!("llvm.fmuladd.f64", fn(t_f64, t_f64, t_f64) -> t_f64);
947        ifn!("llvm.fmuladd.f128", fn(t_f128, t_f128, t_f128) -> t_f128);
948
949        ifn!("llvm.fabs.f16", fn(t_f16) -> t_f16);
950        ifn!("llvm.fabs.f32", fn(t_f32) -> t_f32);
951        ifn!("llvm.fabs.f64", fn(t_f64) -> t_f64);
952        ifn!("llvm.fabs.f128", fn(t_f128) -> t_f128);
953
954        ifn!("llvm.minnum.f16", fn(t_f16, t_f16) -> t_f16);
955        ifn!("llvm.minnum.f32", fn(t_f32, t_f32) -> t_f32);
956        ifn!("llvm.minnum.f64", fn(t_f64, t_f64) -> t_f64);
957        ifn!("llvm.minnum.f128", fn(t_f128, t_f128) -> t_f128);
958
959        ifn!("llvm.maxnum.f16", fn(t_f16, t_f16) -> t_f16);
960        ifn!("llvm.maxnum.f32", fn(t_f32, t_f32) -> t_f32);
961        ifn!("llvm.maxnum.f64", fn(t_f64, t_f64) -> t_f64);
962        ifn!("llvm.maxnum.f128", fn(t_f128, t_f128) -> t_f128);
963
964        ifn!("llvm.floor.f16", fn(t_f16) -> t_f16);
965        ifn!("llvm.floor.f32", fn(t_f32) -> t_f32);
966        ifn!("llvm.floor.f64", fn(t_f64) -> t_f64);
967        ifn!("llvm.floor.f128", fn(t_f128) -> t_f128);
968
969        ifn!("llvm.ceil.f16", fn(t_f16) -> t_f16);
970        ifn!("llvm.ceil.f32", fn(t_f32) -> t_f32);
971        ifn!("llvm.ceil.f64", fn(t_f64) -> t_f64);
972        ifn!("llvm.ceil.f128", fn(t_f128) -> t_f128);
973
974        ifn!("llvm.trunc.f16", fn(t_f16) -> t_f16);
975        ifn!("llvm.trunc.f32", fn(t_f32) -> t_f32);
976        ifn!("llvm.trunc.f64", fn(t_f64) -> t_f64);
977        ifn!("llvm.trunc.f128", fn(t_f128) -> t_f128);
978
979        ifn!("llvm.copysign.f16", fn(t_f16, t_f16) -> t_f16);
980        ifn!("llvm.copysign.f32", fn(t_f32, t_f32) -> t_f32);
981        ifn!("llvm.copysign.f64", fn(t_f64, t_f64) -> t_f64);
982        ifn!("llvm.copysign.f128", fn(t_f128, t_f128) -> t_f128);
983
984        ifn!("llvm.round.f16", fn(t_f16) -> t_f16);
985        ifn!("llvm.round.f32", fn(t_f32) -> t_f32);
986        ifn!("llvm.round.f64", fn(t_f64) -> t_f64);
987        ifn!("llvm.round.f128", fn(t_f128) -> t_f128);
988
989        ifn!("llvm.roundeven.f16", fn(t_f16) -> t_f16);
990        ifn!("llvm.roundeven.f32", fn(t_f32) -> t_f32);
991        ifn!("llvm.roundeven.f64", fn(t_f64) -> t_f64);
992        ifn!("llvm.roundeven.f128", fn(t_f128) -> t_f128);
993
994        ifn!("llvm.rint.f16", fn(t_f16) -> t_f16);
995        ifn!("llvm.rint.f32", fn(t_f32) -> t_f32);
996        ifn!("llvm.rint.f64", fn(t_f64) -> t_f64);
997        ifn!("llvm.rint.f128", fn(t_f128) -> t_f128);
998
999        ifn!("llvm.nearbyint.f16", fn(t_f16) -> t_f16);
1000        ifn!("llvm.nearbyint.f32", fn(t_f32) -> t_f32);
1001        ifn!("llvm.nearbyint.f64", fn(t_f64) -> t_f64);
1002        ifn!("llvm.nearbyint.f128", fn(t_f128) -> t_f128);
1003
1004        ifn!("llvm.ctpop.i8", fn(t_i8) -> t_i8);
1005        ifn!("llvm.ctpop.i16", fn(t_i16) -> t_i16);
1006        ifn!("llvm.ctpop.i32", fn(t_i32) -> t_i32);
1007        ifn!("llvm.ctpop.i64", fn(t_i64) -> t_i64);
1008        ifn!("llvm.ctpop.i128", fn(t_i128) -> t_i128);
1009
1010        ifn!("llvm.ctlz.i8", fn(t_i8, i1) -> t_i8);
1011        ifn!("llvm.ctlz.i16", fn(t_i16, i1) -> t_i16);
1012        ifn!("llvm.ctlz.i32", fn(t_i32, i1) -> t_i32);
1013        ifn!("llvm.ctlz.i64", fn(t_i64, i1) -> t_i64);
1014        ifn!("llvm.ctlz.i128", fn(t_i128, i1) -> t_i128);
1015
1016        ifn!("llvm.cttz.i8", fn(t_i8, i1) -> t_i8);
1017        ifn!("llvm.cttz.i16", fn(t_i16, i1) -> t_i16);
1018        ifn!("llvm.cttz.i32", fn(t_i32, i1) -> t_i32);
1019        ifn!("llvm.cttz.i64", fn(t_i64, i1) -> t_i64);
1020        ifn!("llvm.cttz.i128", fn(t_i128, i1) -> t_i128);
1021
1022        ifn!("llvm.bswap.i16", fn(t_i16) -> t_i16);
1023        ifn!("llvm.bswap.i32", fn(t_i32) -> t_i32);
1024        ifn!("llvm.bswap.i64", fn(t_i64) -> t_i64);
1025        ifn!("llvm.bswap.i128", fn(t_i128) -> t_i128);
1026
1027        ifn!("llvm.bitreverse.i8", fn(t_i8) -> t_i8);
1028        ifn!("llvm.bitreverse.i16", fn(t_i16) -> t_i16);
1029        ifn!("llvm.bitreverse.i32", fn(t_i32) -> t_i32);
1030        ifn!("llvm.bitreverse.i64", fn(t_i64) -> t_i64);
1031        ifn!("llvm.bitreverse.i128", fn(t_i128) -> t_i128);
1032
1033        ifn!("llvm.fshl.i8", fn(t_i8, t_i8, t_i8) -> t_i8);
1034        ifn!("llvm.fshl.i16", fn(t_i16, t_i16, t_i16) -> t_i16);
1035        ifn!("llvm.fshl.i32", fn(t_i32, t_i32, t_i32) -> t_i32);
1036        ifn!("llvm.fshl.i64", fn(t_i64, t_i64, t_i64) -> t_i64);
1037        ifn!("llvm.fshl.i128", fn(t_i128, t_i128, t_i128) -> t_i128);
1038
1039        ifn!("llvm.fshr.i8", fn(t_i8, t_i8, t_i8) -> t_i8);
1040        ifn!("llvm.fshr.i16", fn(t_i16, t_i16, t_i16) -> t_i16);
1041        ifn!("llvm.fshr.i32", fn(t_i32, t_i32, t_i32) -> t_i32);
1042        ifn!("llvm.fshr.i64", fn(t_i64, t_i64, t_i64) -> t_i64);
1043        ifn!("llvm.fshr.i128", fn(t_i128, t_i128, t_i128) -> t_i128);
1044
1045        ifn!("llvm.sadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
1046        ifn!("llvm.sadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
1047        ifn!("llvm.sadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
1048        ifn!("llvm.sadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
1049        ifn!("llvm.sadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
1050
1051        ifn!("llvm.uadd.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
1052        ifn!("llvm.uadd.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
1053        ifn!("llvm.uadd.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
1054        ifn!("llvm.uadd.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
1055        ifn!("llvm.uadd.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
1056
1057        ifn!("llvm.ssub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
1058        ifn!("llvm.ssub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
1059        ifn!("llvm.ssub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
1060        ifn!("llvm.ssub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
1061        ifn!("llvm.ssub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
1062
1063        ifn!("llvm.usub.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
1064        ifn!("llvm.usub.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
1065        ifn!("llvm.usub.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
1066        ifn!("llvm.usub.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
1067        ifn!("llvm.usub.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
1068
1069        ifn!("llvm.smul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
1070        ifn!("llvm.smul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
1071        ifn!("llvm.smul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
1072        ifn!("llvm.smul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
1073        ifn!("llvm.smul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
1074
1075        ifn!("llvm.umul.with.overflow.i8", fn(t_i8, t_i8) -> mk_struct! {t_i8, i1});
1076        ifn!("llvm.umul.with.overflow.i16", fn(t_i16, t_i16) -> mk_struct! {t_i16, i1});
1077        ifn!("llvm.umul.with.overflow.i32", fn(t_i32, t_i32) -> mk_struct! {t_i32, i1});
1078        ifn!("llvm.umul.with.overflow.i64", fn(t_i64, t_i64) -> mk_struct! {t_i64, i1});
1079        ifn!("llvm.umul.with.overflow.i128", fn(t_i128, t_i128) -> mk_struct! {t_i128, i1});
1080
1081        ifn!("llvm.sadd.sat.i8", fn(t_i8, t_i8) -> t_i8);
1082        ifn!("llvm.sadd.sat.i16", fn(t_i16, t_i16) -> t_i16);
1083        ifn!("llvm.sadd.sat.i32", fn(t_i32, t_i32) -> t_i32);
1084        ifn!("llvm.sadd.sat.i64", fn(t_i64, t_i64) -> t_i64);
1085        ifn!("llvm.sadd.sat.i128", fn(t_i128, t_i128) -> t_i128);
1086
1087        ifn!("llvm.uadd.sat.i8", fn(t_i8, t_i8) -> t_i8);
1088        ifn!("llvm.uadd.sat.i16", fn(t_i16, t_i16) -> t_i16);
1089        ifn!("llvm.uadd.sat.i32", fn(t_i32, t_i32) -> t_i32);
1090        ifn!("llvm.uadd.sat.i64", fn(t_i64, t_i64) -> t_i64);
1091        ifn!("llvm.uadd.sat.i128", fn(t_i128, t_i128) -> t_i128);
1092
1093        ifn!("llvm.ssub.sat.i8", fn(t_i8, t_i8) -> t_i8);
1094        ifn!("llvm.ssub.sat.i16", fn(t_i16, t_i16) -> t_i16);
1095        ifn!("llvm.ssub.sat.i32", fn(t_i32, t_i32) -> t_i32);
1096        ifn!("llvm.ssub.sat.i64", fn(t_i64, t_i64) -> t_i64);
1097        ifn!("llvm.ssub.sat.i128", fn(t_i128, t_i128) -> t_i128);
1098
1099        ifn!("llvm.usub.sat.i8", fn(t_i8, t_i8) -> t_i8);
1100        ifn!("llvm.usub.sat.i16", fn(t_i16, t_i16) -> t_i16);
1101        ifn!("llvm.usub.sat.i32", fn(t_i32, t_i32) -> t_i32);
1102        ifn!("llvm.usub.sat.i64", fn(t_i64, t_i64) -> t_i64);
1103        ifn!("llvm.usub.sat.i128", fn(t_i128, t_i128) -> t_i128);
1104
1105        ifn!("llvm.lifetime.start.p0i8", fn(t_i64, ptr) -> void);
1106        ifn!("llvm.lifetime.end.p0i8", fn(t_i64, ptr) -> void);
1107
1108        // FIXME: This is an infinitesimally small portion of the types you can
1109        // pass to this intrinsic, if we can ever lazily register intrinsics we
1110        // should register these when they're used, that way any type can be
1111        // passed.
1112        ifn!("llvm.is.constant.i1", fn(i1) -> i1);
1113        ifn!("llvm.is.constant.i8", fn(t_i8) -> i1);
1114        ifn!("llvm.is.constant.i16", fn(t_i16) -> i1);
1115        ifn!("llvm.is.constant.i32", fn(t_i32) -> i1);
1116        ifn!("llvm.is.constant.i64", fn(t_i64) -> i1);
1117        ifn!("llvm.is.constant.i128", fn(t_i128) -> i1);
1118        ifn!("llvm.is.constant.isize", fn(t_isize) -> i1);
1119        ifn!("llvm.is.constant.f16", fn(t_f16) -> i1);
1120        ifn!("llvm.is.constant.f32", fn(t_f32) -> i1);
1121        ifn!("llvm.is.constant.f64", fn(t_f64) -> i1);
1122        ifn!("llvm.is.constant.f128", fn(t_f128) -> i1);
1123        ifn!("llvm.is.constant.ptr", fn(ptr) -> i1);
1124
1125        ifn!("llvm.expect.i1", fn(i1, i1) -> i1);
1126        ifn!("llvm.eh.typeid.for", fn(ptr) -> t_i32);
1127        ifn!("llvm.localescape", fn(...) -> void);
1128        ifn!("llvm.localrecover", fn(ptr, ptr, t_i32) -> ptr);
1129        ifn!("llvm.x86.seh.recoverfp", fn(ptr, ptr) -> ptr);
1130
1131        ifn!("llvm.assume", fn(i1) -> void);
1132        ifn!("llvm.prefetch", fn(ptr, t_i32, t_i32, t_i32) -> void);
1133
1134        // This isn't an "LLVM intrinsic", but LLVM's optimization passes
1135        // recognize it like one (including turning it into `bcmp` sometimes)
1136        // and we use it to implement intrinsics like `raw_eq` and `compare_bytes`
1137        match self.sess().target.arch.as_ref() {
1138            "avr" | "msp430" => ifn!("memcmp", fn(ptr, ptr, t_isize) -> t_i16),
1139            _ => ifn!("memcmp", fn(ptr, ptr, t_isize) -> t_i32),
1140        }
1141
1142        // variadic intrinsics
1143        ifn!("llvm.va_start", fn(ptr) -> void);
1144        ifn!("llvm.va_end", fn(ptr) -> void);
1145        ifn!("llvm.va_copy", fn(ptr, ptr) -> void);
1146
1147        if self.sess().instrument_coverage() {
1148            ifn!("llvm.instrprof.increment", fn(ptr, t_i64, t_i32, t_i32) -> void);
1149            if crate::llvm_util::get_version() >= (19, 0, 0) {
1150                ifn!("llvm.instrprof.mcdc.parameters", fn(ptr, t_i64, t_i32) -> void);
1151                ifn!("llvm.instrprof.mcdc.tvbitmap.update", fn(ptr, t_i64, t_i32, ptr) -> void);
1152            }
1153        }
1154
1155        ifn!("llvm.type.test", fn(ptr, t_metadata) -> i1);
1156        ifn!("llvm.type.checked.load", fn(ptr, t_i32, t_metadata) -> mk_struct! {ptr, i1});
1157
1158        if self.sess().opts.debuginfo != DebugInfo::None {
1159            ifn!("llvm.dbg.declare", fn(t_metadata, t_metadata) -> void);
1160            ifn!("llvm.dbg.value", fn(t_metadata, t_i64, t_metadata) -> void);
1161        }
1162
1163        ifn!("llvm.ptrmask", fn(ptr, t_isize) -> ptr);
1164
1165        None
1166    }
1167
1168    pub(crate) fn eh_catch_typeinfo(&self) -> &'ll Value {
1169        if let Some(eh_catch_typeinfo) = self.eh_catch_typeinfo.get() {
1170            return eh_catch_typeinfo;
1171        }
1172        let tcx = self.tcx;
1173        assert!(self.sess().target.os == "emscripten");
1174        let eh_catch_typeinfo = match tcx.lang_items().eh_catch_typeinfo() {
1175            Some(def_id) => self.get_static(def_id),
1176            _ => {
1177                let ty = self.type_struct(&[self.type_ptr(), self.type_ptr()], false);
1178                self.declare_global("rust_eh_catch_typeinfo", ty)
1179            }
1180        };
1181        self.eh_catch_typeinfo.set(Some(eh_catch_typeinfo));
1182        eh_catch_typeinfo
1183    }
1184}
1185
1186impl CodegenCx<'_, '_> {
1187    /// Generates a new symbol name with the given prefix. This symbol name must
1188    /// only be used for definitions with `internal` or `private` linkage.
1189    pub(crate) fn generate_local_symbol_name(&self, prefix: &str) -> String {
1190        let idx = self.local_gen_sym_counter.get();
1191        self.local_gen_sym_counter.set(idx + 1);
1192        // Include a '.' character, so there can be no accidental conflicts with
1193        // user defined names
1194        let mut name = String::with_capacity(prefix.len() + 6);
1195        name.push_str(prefix);
1196        name.push('.');
1197        name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY));
1198        name
1199    }
1200
1201    /// A wrapper for [`llvm::LLVMSetMetadata`], but it takes `Metadata` as a parameter instead of `Value`.
1202    pub(crate) fn set_metadata<'a>(&self, val: &'a Value, kind_id: MetadataType, md: &'a Metadata) {
1203        unsafe {
1204            let node = llvm::LLVMMetadataAsValue(&self.llcx, md);
1205            llvm::LLVMSetMetadata(val, kind_id as c_uint, node);
1206        }
1207    }
1208}
1209
1210// This is a duplication of the set_metadata function above. However, so far it's the only one
1211// shared between both contexts, so it doesn't seem worth it to make the Cx generic like we did it
1212// for the Builder.
1213impl SimpleCx<'_> {
1214    #[allow(unused)]
1215    /// A wrapper for [`llvm::LLVMSetMetadata`], but it takes `Metadata` as a parameter instead of `Value`.
1216    pub(crate) fn set_metadata<'a>(&self, val: &'a Value, kind_id: MetadataType, md: &'a Metadata) {
1217        unsafe {
1218            let node = llvm::LLVMMetadataAsValue(&self.llcx, md);
1219            llvm::LLVMSetMetadata(val, kind_id as c_uint, node);
1220        }
1221    }
1222}
1223
1224impl HasDataLayout for CodegenCx<'_, '_> {
1225    #[inline]
1226    fn data_layout(&self) -> &TargetDataLayout {
1227        &self.tcx.data_layout
1228    }
1229}
1230
1231impl HasTargetSpec for CodegenCx<'_, '_> {
1232    #[inline]
1233    fn target_spec(&self) -> &Target {
1234        &self.tcx.sess.target
1235    }
1236}
1237
1238impl<'tcx> ty::layout::HasTyCtxt<'tcx> for CodegenCx<'_, 'tcx> {
1239    #[inline]
1240    fn tcx(&self) -> TyCtxt<'tcx> {
1241        self.tcx
1242    }
1243}
1244
1245impl<'tcx, 'll> HasTypingEnv<'tcx> for CodegenCx<'ll, 'tcx> {
1246    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
1247        ty::TypingEnv::fully_monomorphized()
1248    }
1249}
1250
1251impl<'tcx> LayoutOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
1252    #[inline]
1253    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
1254        if let LayoutError::SizeOverflow(_) | LayoutError::ReferencesError(_) = err {
1255            self.tcx.dcx().emit_fatal(Spanned { span, node: err.into_diagnostic() })
1256        } else {
1257            self.tcx.dcx().emit_fatal(ssa_errors::FailedToGetLayout { span, ty, err })
1258        }
1259    }
1260}
1261
1262impl<'tcx> FnAbiOfHelpers<'tcx> for CodegenCx<'_, 'tcx> {
1263    #[inline]
1264    fn handle_fn_abi_err(
1265        &self,
1266        err: FnAbiError<'tcx>,
1267        span: Span,
1268        fn_abi_request: FnAbiRequest<'tcx>,
1269    ) -> ! {
1270        match err {
1271            FnAbiError::Layout(LayoutError::SizeOverflow(_) | LayoutError::Cycle(_)) => {
1272                self.tcx.dcx().emit_fatal(Spanned { span, node: err });
1273            }
1274            _ => match fn_abi_request {
1275                FnAbiRequest::OfFnPtr { sig, extra_args } => {
1276                    span_bug!(span, "`fn_abi_of_fn_ptr({sig}, {extra_args:?})` failed: {err:?}",);
1277                }
1278                FnAbiRequest::OfInstance { instance, extra_args } => {
1279                    span_bug!(
1280                        span,
1281                        "`fn_abi_of_instance({instance}, {extra_args:?})` failed: {err:?}",
1282                    );
1283                }
1284            },
1285        }
1286    }
1287}