rustc_codegen_llvm/
context.rs

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