Skip to main content

rustc_codegen_llvm/
consts.rs

1use std::ops::Range;
2
3use rustc_abi::{Align, ExternAbi, HasDataLayout, Primitive, Scalar, Size, WrappingRange};
4use rustc_attr_ir::Linkage;
5use rustc_attr_ir::lang_items::LangItem;
6use rustc_codegen_ssa::common;
7use rustc_codegen_ssa::traits::*;
8use rustc_hir::def::DefKind;
9use rustc_hir::def_id::{DefId, LOCAL_CRATE};
10use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
11use rustc_middle::mir::interpret::{
12    Allocation, ConstAllocation, ErrorHandled, InitChunk, Pointer, Scalar as InterpScalar,
13    read_target_uint,
14};
15use rustc_middle::mono::MonoItem;
16use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf};
17use rustc_middle::ty::{self, Instance};
18use rustc_span::{Symbol, bug, span_bug};
19use rustc_target::spec::Arch;
20use tracing::{debug, instrument, trace};
21
22use crate::common::CodegenCx;
23use crate::diagnostics::SymbolAlreadyDefined;
24use crate::llvm::{self, Type, Value, const_ptr_auth};
25use crate::type_of::LayoutLlvmExt;
26use crate::{base, debuginfo};
27
28/// Indicates whether a value originates from a `static`.
29pub(crate) enum IsStatic {
30    Yes,
31    No,
32}
33/// Indicates whether a symbol is part of `.init_array` or `.fini_array`.
34#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for IsInitOrFini { }
#[automatically_derived]
impl ::core::cmp::PartialEq for IsInitOrFini {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq)]
35pub(crate) enum IsInitOrFini {
36    Yes,
37    No,
38}
39pub(crate) fn const_alloc_to_llvm<'ll>(
40    cx: &CodegenCx<'ll, '_>,
41    alloc: &Allocation,
42    is_static: IsStatic,
43    is_init_fini: IsInitOrFini,
44) -> &'ll Value {
45    // We expect that callers of const_alloc_to_llvm will instead directly codegen a pointer or
46    // integer for any &ZST where the ZST is a constant (i.e. not a static). We should never be
47    // producing empty LLVM allocations as they're just adding noise to binaries and forcing less
48    // optimal codegen.
49    //
50    // Statics have a guaranteed meaningful address so it's less clear that we want to do
51    // something like this; it's also harder.
52    if #[allow(non_exhaustive_omitted_patterns)] match is_static {
    IsStatic::No => true,
    _ => false,
}matches!(is_static, IsStatic::No) {
53        if !(alloc.len() != 0) {
    ::core::panicking::panic("assertion failed: alloc.len() != 0")
};assert!(alloc.len() != 0);
54    }
55    let mut llvals = Vec::with_capacity(alloc.provenance().ptrs().len() + 1);
56    let dl = cx.data_layout();
57    let pointer_size = dl.pointer_size();
58    let pointer_size_bytes = pointer_size.bytes() as usize;
59
60    // Note: this function may call `inspect_with_uninit_and_ptr_outside_interpreter`, so `range`
61    // must be within the bounds of `alloc` and not contain or overlap a pointer provenance.
62    fn append_chunks_of_init_and_uninit_bytes<'ll, 'a, 'b>(
63        llvals: &mut Vec<&'ll Value>,
64        cx: &'a CodegenCx<'ll, 'b>,
65        alloc: &'a Allocation,
66        range: Range<usize>,
67    ) {
68        let chunks = alloc.init_mask().range_as_init_chunks(range.clone().into());
69
70        let chunk_to_llval = move |chunk| match chunk {
71            InitChunk::Init(range) => {
72                let range = (range.start.bytes() as usize)..(range.end.bytes() as usize);
73                let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
74                cx.const_bytes(bytes)
75            }
76            InitChunk::Uninit(range) => {
77                let len = range.end.bytes() - range.start.bytes();
78                cx.const_undef(cx.type_array(cx.type_i8(), len))
79            }
80        };
81
82        // Generating partially-uninit consts is limited to small numbers of chunks,
83        // to avoid the cost of generating large complex const expressions.
84        // For example, `[(u32, u8); 1024 * 1024]` contains uninit padding in each element, and
85        // would result in `{ [5 x i8] zeroinitializer, [3 x i8] undef, ...repeat 1M times... }`.
86        let max = cx.sess().opts.unstable_opts.uninit_const_chunk_threshold;
87        let allow_uninit_chunks = chunks.clone().take(max.saturating_add(1)).count() <= max;
88
89        if allow_uninit_chunks {
90            llvals.extend(chunks.map(chunk_to_llval));
91        } else {
92            // If this allocation contains any uninit bytes, codegen as if it was initialized
93            // (using some arbitrary value for uninit bytes).
94            let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
95            llvals.push(cx.const_bytes(bytes));
96        }
97    }
98
99    let mut next_offset = 0;
100    for &(offset, prov) in alloc.provenance().ptrs().iter() {
101        let offset = offset.bytes();
102        {
    match (&(offset as usize as u64), &offset) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(offset as usize as u64, offset);
103        let offset = offset as usize;
104        if offset > next_offset {
105            // This `inspect` is okay since we have checked that there is no provenance, it
106            // is within the bounds of the allocation, and it doesn't affect interpreter execution
107            // (we inspect the result after interpreter execution).
108            append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, next_offset..offset);
109        }
110        let ptr_offset = read_target_uint(
111            dl.endian,
112            // This `inspect` is okay since it is within the bounds of the allocation, it doesn't
113            // affect interpreter execution (we inspect the result after interpreter execution),
114            // and we properly interpret the provenance as a relocation pointer offset.
115            alloc.inspect_with_uninit_and_ptr_outside_interpreter(
116                offset..(offset + pointer_size_bytes),
117            ),
118        )
119        .expect("const_alloc_to_llvm: could not read relocation pointer")
120            as u64;
121
122        let address_space = cx.tcx.global_alloc(prov.alloc_id()).address_space(cx);
123        let schema = if cx.sess().pointer_authentication() {
124            match is_init_fini {
125                IsInitOrFini::Yes => cx.sess().pointer_authentication_init_fini(),
126                IsInitOrFini::No => cx.sess().pointer_authentication_functions(),
127            }
128        } else {
129            None
130        };
131        llvals.push(cx.scalar_to_backend_with_pac(
132            InterpScalar::from_pointer(Pointer::new(prov, Size::from_bytes(ptr_offset)), &cx.tcx),
133            Scalar::Initialized {
134                value: Primitive::Pointer(address_space),
135                valid_range: WrappingRange::full(pointer_size),
136            },
137            cx.type_ptr_ext(address_space),
138            schema,
139        ));
140        next_offset = offset + pointer_size_bytes;
141    }
142    if alloc.len() >= next_offset {
143        let range = next_offset..alloc.len();
144        // This `inspect` is okay since we have check that it is after all provenance, it is
145        // within the bounds of the allocation, and it doesn't affect interpreter execution (we
146        // inspect the result after interpreter execution).
147        append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, range);
148    }
149
150    // Avoid wrapping in a struct if there is only a single value. This ensures
151    // that LLVM is able to perform the string merging optimization if the constant
152    // is a valid C string. LLVM only considers bare arrays for this optimization,
153    // not arrays wrapped in a struct. LLVM handles this at:
154    // https://github.com/rust-lang/llvm-project/blob/acaea3d2bb8f351b740db7ebce7d7a40b9e21488/llvm/lib/Target/TargetLoweringObjectFile.cpp#L249-L280
155    if let &[data] = &*llvals { data } else { cx.const_struct(&llvals, true) }
156}
157
158fn codegen_static_initializer<'ll, 'tcx>(
159    cx: &CodegenCx<'ll, 'tcx>,
160    def_id: DefId,
161) -> Result<(&'ll Value, ConstAllocation<'tcx>), ErrorHandled> {
162    let alloc = cx.tcx.eval_static_initializer(def_id)?;
163    let attrs = cx.tcx.codegen_fn_attrs(def_id);
164    // FIXME(jchlanda) Decide if this could be better served by `ctor` crate. See the discussion
165    // here: <https://github.com/rust-lang/rust/pull/155722#discussion_r3320477047>
166    let is_in_init_fini: IsInitOrFini = attrs
167        .link_section
168        .map(|link_section| {
169            let s = link_section.as_str();
170            if s.starts_with(".init_array") || s.starts_with(".fini_array") {
171                IsInitOrFini::Yes
172            } else {
173                IsInitOrFini::No
174            }
175        })
176        .unwrap_or(IsInitOrFini::No);
177    Ok((const_alloc_to_llvm(cx, alloc.inner(), IsStatic::Yes, is_in_init_fini), alloc))
178}
179
180fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: Align) {
181    // The target may require greater alignment for globals than the type does.
182    // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
183    // which can force it to be smaller. Rust doesn't support this yet.
184    if let Some(min_global) = cx.sess().target.min_global_align {
185        align = Ord::max(align, min_global);
186    }
187    llvm::set_alignment(gv, align);
188}
189
190fn check_and_apply_linkage<'ll, 'tcx>(
191    cx: &CodegenCx<'ll, 'tcx>,
192    attrs: &CodegenFnAttrs,
193    llty: &'ll Type,
194    sym: &str,
195    def_id: DefId,
196) -> &'ll Value {
197    if let Some(linkage) = attrs.import_linkage {
198        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/consts.rs:198",
                        "rustc_codegen_llvm::consts", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/consts.rs"),
                        ::tracing_core::__macro_support::Option::Some(198u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("get_static: sym={0} linkage={1:?}",
                                                    sym, linkage) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("get_static: sym={} linkage={:?}", sym, linkage);
199
200        let mut should_sign = false;
201        // Declare a symbol `foo`. If `foo` is an extern_weak symbol, we declare
202        // an extern_weak function, otherwise a global with the desired linkage.
203        let g1 = if #[allow(non_exhaustive_omitted_patterns)] match attrs.import_linkage {
    Some(Linkage::ExternalWeak) => true,
    _ => false,
}matches!(attrs.import_linkage, Some(Linkage::ExternalWeak)) {
204            // An `extern_weak` function is represented as an `Option<unsafe extern ...>`,
205            // we extract the function signature and declare it as an extern_weak function
206            // instead of an extern_weak i8.
207            let instance = Instance::mono(cx.tcx, def_id);
208            if let ty::Adt(struct_def, args) = instance.ty(cx.tcx, cx.typing_env()).kind()
209                && cx.tcx.is_lang_item(struct_def.did(), LangItem::Option)
210                && let ty::FnPtr(sig, header) = args.type_at(0).kind()
211            {
212                let fn_sig = sig.with(*header);
213                let fn_abi = cx.fn_abi_of_fn_ptr(fn_sig, ty::List::empty());
214                // Decide if the initializer needs to be signed
215                if cx.sess().pointer_authentication_functions().is_some()
216                    && #[allow(non_exhaustive_omitted_patterns)] match fn_sig.abi() {
    ExternAbi::C { .. } | ExternAbi::System { .. } => true,
    _ => false,
}matches!(fn_sig.abi(), ExternAbi::C { .. } | ExternAbi::System { .. })
217                {
218                    should_sign = true;
219                }
220                cx.declare_fn(sym, &fn_abi, None)
221            } else {
222                cx.declare_global(sym, cx.type_i8())
223            }
224        } else {
225            cx.declare_global(sym, cx.type_i8())
226        };
227        llvm::set_linkage(g1, base::linkage_to_llvm(linkage));
228
229        // Normally this is done in `get_static_inner`, but when as we generate an internal global,
230        // it will apply the dso_local to the internal global instead, so do it here, too.
231        cx.assume_dso_local(g1, true);
232
233        // Declare an internal global `extern_with_linkage_foo` which
234        // is initialized with the address of `foo`. If `foo` is
235        // discarded during linking (for example, if `foo` has weak
236        // linkage and there are no definitions), then
237        // `extern_with_linkage_foo` will instead be initialized to
238        // zero.
239        let real_name =
240            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("_rust_extern_with_linkage_{0:016x}_{1}",
                cx.tcx.stable_crate_id(LOCAL_CRATE), sym))
    })format!("_rust_extern_with_linkage_{:016x}_{sym}", cx.tcx.stable_crate_id(LOCAL_CRATE));
241        let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| {
242            cx.sess().dcx().emit_fatal(SymbolAlreadyDefined {
243                span: cx.tcx.def_span(def_id),
244                symbol_name: sym,
245            })
246        });
247        llvm::set_linkage(g2, llvm::Linkage::InternalLinkage);
248        llvm::set_unnamed_address(g2, llvm::UnnamedAddr::Global);
249
250        // Sign the function pointer that is used to initialize the global
251        let initializer = if should_sign {
252            let schema = cx
253                .tcx
254                .sess
255                .pointer_authentication_functions()
256                .expect("pointer authentication functions must be available when signing");
257
258            const_ptr_auth(
259                cx.const_bitcast(g1, llty),
260                schema.key as u32,
261                schema.constant_discriminator as u64,
262                None, /* address_diversity */
263            )
264        } else {
265            g1
266        };
267
268        llvm::set_initializer(g2, initializer);
269
270        g2
271    } else if cx.tcx.sess.target.arch == Arch::X86
272        && common::is_using_dlltool(&cx.tcx.sess.target)
273        && let Some(dllimport) = crate::common::get_dllimport(cx.tcx, def_id, sym)
274    {
275        cx.declare_global(&common::i686_decorated_name(dllimport, true, true, false), llty)
276    } else {
277        // Generate an external declaration.
278        // FIXME(nagisa): investigate whether it can be changed into define_global
279        cx.declare_global(sym, llty)
280    }
281}
282
283impl<'ll> CodegenCx<'ll, '_> {
284    pub(crate) fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
285        unsafe { llvm::LLVMConstBitCast(val, ty) }
286    }
287
288    pub(crate) fn const_pointercast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
289        unsafe { llvm::LLVMConstPointerCast(val, ty) }
290    }
291
292    /// Create a global variable.
293    ///
294    /// The returned global variable is a pointer in the default address space for globals.
295    /// Fails if a symbol with the given name already exists.
296    pub(crate) fn static_addr_of_mut(
297        &self,
298        cv: &'ll Value,
299        align: Align,
300        kind: Option<&str>,
301    ) -> &'ll Value {
302        let gv = match kind {
303            Some(kind) if !self.tcx.sess.fewer_names() => {
304                let name = self.generate_local_symbol_name(kind);
305                let gv = self.define_global(&name, self.val_ty(cv)).unwrap_or_else(|| {
306                    ::rustc_span::macros::bug_impl(None,
    format_args!("symbol `{0}` is already defined", name),
    Location::caller());bug!("symbol `{}` is already defined", name);
307                });
308                gv
309            }
310            _ => self.define_global("", self.val_ty(cv)).unwrap_or_else(|| {
311                ::rustc_span::macros::bug_impl(None,
    format_args!("anonymous global symbol is already defined"),
    Location::caller());bug!("anonymous global symbol is already defined");
312            }),
313        };
314        llvm::set_linkage(gv, llvm::Linkage::PrivateLinkage);
315        llvm::set_initializer(gv, cv);
316        set_global_alignment(self, gv, align);
317        llvm::set_unnamed_address(gv, llvm::UnnamedAddr::Global);
318        gv
319    }
320
321    /// Create a global constant.
322    ///
323    /// The returned global variable is a pointer in the default address space for globals.
324    pub(crate) fn static_addr_of_impl(
325        &self,
326        cv: &'ll Value,
327        align: Align,
328        kind: Option<&str>,
329    ) -> &'ll Value {
330        if let Some(&gv) = self.const_globals.borrow().get(&cv) {
331            unsafe {
332                // Upgrade the alignment in cases where the same constant is used with different
333                // alignment requirements
334                let llalign = align.bytes() as u32;
335                if llalign > llvm::LLVMGetAlignment(gv) {
336                    llvm::LLVMSetAlignment(gv, llalign);
337                }
338            }
339            return gv;
340        }
341        let gv = self.static_addr_of_mut(cv, align, kind);
342        llvm::set_global_constant(gv, true);
343
344        self.const_globals.borrow_mut().insert(cv, gv);
345        gv
346    }
347
348    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("get_static",
                                    "rustc_codegen_llvm::consts", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/consts.rs"),
                                    ::tracing_core::__macro_support::Option::Some(348u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'ll Value = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let instance = Instance::mono(self.tcx, def_id);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/consts.rs:351",
                                    "rustc_codegen_llvm::consts", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/consts.rs"),
                                    ::tracing_core::__macro_support::Option::Some(351u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instance")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instance");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let DefKind::Static { nested, .. } =
                self.tcx.def_kind(def_id) else {
                    ::rustc_span::macros::bug_impl(None,
                        format_args!("impossible case reached"), Location::caller())
                };
            let llty =
                if nested {
                    self.type_i8()
                } else {
                    let ty = instance.ty(self.tcx, self.typing_env());
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/consts.rs:360",
                                            "rustc_codegen_llvm::consts", ::tracing::Level::TRACE,
                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/consts.rs"),
                                            ::tracing_core::__macro_support::Option::Some(360u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("ty")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("ty");
                                                                NAME.as_str()
                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::TRACE <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    self.layout_of(ty).llvm_type(self)
                };
            self.get_static_inner(def_id, llty)
        }
    }
}#[instrument(level = "debug", skip(self))]
349    pub(crate) fn get_static(&self, def_id: DefId) -> &'ll Value {
350        let instance = Instance::mono(self.tcx, def_id);
351        trace!(?instance);
352
353        let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
354        // Nested statics do not have a type, so pick a dummy type and let `codegen_static` figure
355        // out the llvm type from the actual evaluated initializer.
356        let llty = if nested {
357            self.type_i8()
358        } else {
359            let ty = instance.ty(self.tcx, self.typing_env());
360            trace!(?ty);
361            self.layout_of(ty).llvm_type(self)
362        };
363        self.get_static_inner(def_id, llty)
364    }
365
366    {}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("get_static_inner",
                                    "rustc_codegen_llvm::consts", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/consts.rs"),
                                    ::tracing_core::__macro_support::Option::Some(366u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("def_id")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("def_id");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: &'ll Value = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let instance = Instance::mono(self.tcx, def_id);
            if let Some(&g) = self.instances.borrow().get(&instance) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/consts.rs:370",
                                        "rustc_codegen_llvm::consts", ::tracing::Level::TRACE,
                                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/consts.rs"),
                                        ::tracing_core::__macro_support::Option::Some(370u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                        ::tracing_core::field::FieldSet::new(&["message"],
                                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                        ::tracing::metadata::Kind::EVENT)
                                };
                            ::tracing::callsite::DefaultCallsite::new(&META)
                        };
                    let enabled =
                        ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            {
                                let interest = __CALLSITE.interest();
                                !interest.is_never() &&
                                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                        interest)
                            };
                    if enabled {
                        (|value_set: ::tracing::field::ValueSet|
                                    {
                                        let meta = __CALLSITE.metadata();
                                        ::tracing::Event::dispatch(meta, &value_set);
                                        ;
                                    })({
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("used cached value")
                                                            as &dyn ::tracing::field::Value))])
                            });
                    } else { ; }
                };
                return g;
            }
            let defined_in_current_codegen_unit =
                self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
            if !!defined_in_current_codegen_unit {
                {
                    ::core::panicking::panic_fmt(format_args!("consts::get_static() should always hit the cache for statics defined in the same CGU, but did not for `{0:?}`",
                            def_id));
                }
            };
            let sym = self.tcx.symbol_name(instance).name;
            let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/consts.rs:385",
                                    "rustc_codegen_llvm::consts", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/48f4b05538b8eca412137042d9647a61e692c6b3/compiler/rustc_codegen_llvm/src/consts.rs"),
                                    ::tracing_core::__macro_support::Option::Some(385u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::consts"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sym")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sym");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("fn_attrs")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("fn_attrs");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sym)
                                                        as &dyn ::tracing::field::Value)),
                                            (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_attrs)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let g =
                if def_id.is_local() && !self.tcx.is_foreign_item(def_id) {
                    if let Some(g) = self.get_declared_value(sym) {
                        if self.val_ty(g) != self.type_ptr() {
                            ::rustc_span::macros::bug_impl(Some(self.tcx.def_span(def_id)),
                                format_args!("Conflicting types for static"),
                                Location::caller());
                        }
                    }
                    let g = self.declare_global(sym, llty);
                    if !self.tcx.is_reachable_non_generic(def_id) {
                        llvm::set_visibility(g, llvm::Visibility::Hidden);
                    }
                    g
                } else if let Some(classname) = fn_attrs.objc_class {
                    self.get_objc_classref(classname)
                } else if let Some(methname) = fn_attrs.objc_selector {
                    self.get_objc_selref(methname)
                } else {
                    check_and_apply_linkage(self, fn_attrs, llty, sym, def_id)
                };
            if fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
                llvm::set_thread_local_mode(g, self.tls_model);
            }
            let dso_local = self.assume_dso_local(g, true);
            if !def_id.is_local() {
                let is_eii =
                    fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
                let needs_dll_storage_attr =
                    self.use_dll_storage_attrs &&
                                (!self.tcx.is_foreign_item(def_id) || is_eii) && !dso_local
                        && !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
                if !!(self.tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
                                        self.tcx.sess.target.is_like_windows &&
                                    self.tcx.sess.opts.cg.prefer_dynamic) {
                    ::core::panicking::panic("assertion failed: !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled() &&\n                self.tcx.sess.target.is_like_windows &&\n            self.tcx.sess.opts.cg.prefer_dynamic)")
                };
                if needs_dll_storage_attr {
                    if !self.tcx.is_codegened_item(def_id) {
                        llvm::set_dllimport_storage_class(g);
                    }
                }
            }
            if self.use_dll_storage_attrs &&
                        let Some(library) = self.tcx.native_library(def_id) &&
                    library.kind.is_dllimport() {
                llvm::set_dllimport_storage_class(g);
            }
            self.instances.borrow_mut().insert(instance, g);
            g
        }
    }
}#[instrument(level = "debug", skip(self, llty))]
367    fn get_static_inner(&self, def_id: DefId, llty: &'ll Type) -> &'ll Value {
368        let instance = Instance::mono(self.tcx, def_id);
369        if let Some(&g) = self.instances.borrow().get(&instance) {
370            trace!("used cached value");
371            return g;
372        }
373
374        let defined_in_current_codegen_unit =
375            self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
376        assert!(
377            !defined_in_current_codegen_unit,
378            "consts::get_static() should always hit the cache for \
379                 statics defined in the same CGU, but did not for `{def_id:?}`"
380        );
381
382        let sym = self.tcx.symbol_name(instance).name;
383        let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
384
385        debug!(?sym, ?fn_attrs);
386
387        let g = if def_id.is_local() && !self.tcx.is_foreign_item(def_id) {
388            if let Some(g) = self.get_declared_value(sym) {
389                if self.val_ty(g) != self.type_ptr() {
390                    span_bug!(self.tcx.def_span(def_id), "Conflicting types for static");
391                }
392            }
393
394            let g = self.declare_global(sym, llty);
395
396            if !self.tcx.is_reachable_non_generic(def_id) {
397                llvm::set_visibility(g, llvm::Visibility::Hidden);
398            }
399
400            g
401        } else if let Some(classname) = fn_attrs.objc_class {
402            self.get_objc_classref(classname)
403        } else if let Some(methname) = fn_attrs.objc_selector {
404            self.get_objc_selref(methname)
405        } else {
406            check_and_apply_linkage(self, fn_attrs, llty, sym, def_id)
407        };
408
409        // Thread-local statics in some other crate need to *always* be linked
410        // against in a thread-local fashion, so we need to be sure to apply the
411        // thread-local attribute locally if it was present remotely. If we
412        // don't do this then linker errors can be generated where the linker
413        // complains that one object files has a thread local version of the
414        // symbol and another one doesn't.
415        if fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
416            llvm::set_thread_local_mode(g, self.tls_model);
417        }
418
419        let dso_local = self.assume_dso_local(g, true);
420
421        if !def_id.is_local() {
422            let is_eii = fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
423            let needs_dll_storage_attr = self.use_dll_storage_attrs
424                // EII static declarations are encoded as foreign items, but their symbols are
425                // resolved by Rust crates, not native libraries.
426                && (!self.tcx.is_foreign_item(def_id) || is_eii)
427                // Local definitions can never be imported, so we must not apply
428                // the DLLImport annotation.
429                && !dso_local
430                // Linker plugin ThinLTO doesn't create the self-dllimport Rust uses for rlibs
431                // as the code generation happens out of process. Instead we assume static linkage
432                // and disallow dynamic linking when linker plugin based LTO is enabled.
433                // Regular in-process ThinLTO doesn't need this workaround.
434                && !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
435
436            // If this assertion triggers, there's something wrong with commandline
437            // argument validation.
438            assert!(
439                !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
440                    && self.tcx.sess.target.is_like_windows
441                    && self.tcx.sess.opts.cg.prefer_dynamic)
442            );
443
444            if needs_dll_storage_attr {
445                // This item is external but not foreign, i.e., it originates from an external Rust
446                // crate. EII static declarations are handled the same way, even though they are
447                // represented as foreign items. Since we don't know whether this crate will be
448                // linked dynamically or statically in the final application, we always mark such
449                // symbols as 'dllimport'. If final linkage happens to be static, we rely on
450                // compiler-emitted __imp_ stubs to make things work.
451                //
452                // However, in some scenarios we defer emission of statics to downstream
453                // crates, so there are cases where a static with an upstream DefId
454                // is actually present in the current crate. We can find out via the
455                // is_codegened_item query.
456                if !self.tcx.is_codegened_item(def_id) {
457                    llvm::set_dllimport_storage_class(g);
458                }
459            }
460        }
461
462        if self.use_dll_storage_attrs
463            && let Some(library) = self.tcx.native_library(def_id)
464            && library.kind.is_dllimport()
465        {
466            // For foreign (native) libs we know the exact storage type to use.
467            llvm::set_dllimport_storage_class(g);
468        }
469
470        self.instances.borrow_mut().insert(instance, g);
471        g
472    }
473
474    fn codegen_static_item(&mut self, def_id: DefId) {
475        if !llvm::LLVMGetInitializer(self.instances.borrow().get(&Instance::mono(self.tcx,
                                def_id)).unwrap()).is_none() {
    ::core::panicking::panic("assertion failed: llvm::LLVMGetInitializer(self.instances.borrow().get(&Instance::mono(self.tcx,\n                        def_id)).unwrap()).is_none()")
};assert!(
476            llvm::LLVMGetInitializer(
477                self.instances.borrow().get(&Instance::mono(self.tcx, def_id)).unwrap()
478            )
479            .is_none()
480        );
481        let attrs = self.tcx.codegen_fn_attrs(def_id);
482
483        let Ok((v, alloc)) = codegen_static_initializer(self, def_id) else {
484            // Error has already been reported
485            return;
486        };
487        let alloc = alloc.inner();
488
489        let val_llty = self.val_ty(v);
490
491        let g = self.get_static_inner(def_id, val_llty);
492        let llty = self.get_type_of_global(g);
493
494        let g = if val_llty == llty {
495            g
496        } else {
497            // codegen_static_initializer creates the global value just from the
498            // `Allocation` data by generating one big struct value that is just
499            // all the bytes and pointers after each other. This will almost never
500            // match the type that the static was declared with. Unfortunately
501            // we can't just LLVMConstBitCast our way out of it because that has very
502            // specific rules on what can be cast. So instead of adding a new way to
503            // generate static initializers that match the static's type, we picked
504            // the easier option and retroactively change the type of the static item itself.
505            let name = String::from_utf8(llvm::get_value_name(g))
506                .expect("we declare our statics with a utf8-valid name");
507            llvm::set_value_name(g, b"");
508
509            let linkage = llvm::get_linkage(g);
510            let visibility = llvm::get_visibility(g);
511
512            let new_g = self.declare_global(&name, val_llty);
513
514            llvm::set_linkage(new_g, linkage);
515            llvm::set_visibility(new_g, visibility);
516
517            // The old global has had its name removed but is returned by
518            // get_static since it is in the instance cache. Provide an
519            // alternative lookup that points to the new global so that
520            // global_asm! can compute the correct mangled symbol name
521            // for the global.
522            self.renamed_statics.borrow_mut().insert(def_id, new_g);
523
524            // To avoid breaking any invariants, we leave around the old
525            // global for the moment; we'll replace all references to it
526            // with the new global later. (See base::codegen_backend.)
527            self.statics_to_rauw.borrow_mut().push((g, new_g));
528            new_g
529        };
530
531        // NOTE: Alignment from attributes has already been applied to the allocation.
532        set_global_alignment(self, g, alloc.align);
533        llvm::set_initializer(g, v);
534
535        self.assume_dso_local(g, true);
536
537        // Forward the allocation's mutability (picked by the const interner) to LLVM.
538        if alloc.mutability.is_not() {
539            llvm::set_global_constant(g, true);
540        }
541
542        debuginfo::build_global_var_di_node(self, def_id, g);
543
544        if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
545            llvm::set_thread_local_mode(g, self.tls_model);
546        }
547
548        // Wasm statics with custom link sections get special treatment as they
549        // also go into custom sections of the wasm executable. The exception to
550        // this is the `.init_array` section for which we can't emit a custom
551        // section as it contains relocations.
552        if self.tcx.sess.target.is_like_wasm
553            && attrs
554                .link_section
555                .map(|link_section| !link_section.as_str().starts_with(".init_array"))
556                .unwrap_or(true)
557        {
558            if let Some(section) = attrs.link_section {
559                let section = self.create_metadata(section.as_str().as_bytes());
560                if !alloc.provenance().ptrs().is_empty() {
    ::core::panicking::panic("assertion failed: alloc.provenance().ptrs().is_empty()")
};assert!(alloc.provenance().ptrs().is_empty());
561
562                // The `inspect` method is okay here because we checked for provenance, and
563                // because we are doing this access to inspect the final interpreter state (not
564                // as part of the interpreter execution).
565                let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len());
566                let alloc = self.create_metadata(bytes);
567                let data = [section, alloc];
568                self.module_add_named_metadata_node(self.llmod(), c"wasm.custom_sections", &data);
569            }
570        }
571
572        base::set_link_section(g, attrs);
573        base::set_variable_sanitizer_attrs(g, attrs);
574
575        if let Some(ignorelist) = &self.sanitizer_ignorelist {
576            let instance = ty::Instance::mono(self.tcx, def_id);
577            let sym_name = self.tcx.symbol_name(instance).name;
578            let span = self.tcx.def_span(def_id);
579            let source_map = self.tcx.sess.source_map();
580            let filename =
581                source_map.span_to_filename(span).prefer_local_unconditionally().to_string();
582            let ty_name = {
    let _guard = NoTrimmedGuard::new();
    self.tcx.type_of(def_id).skip_binder().to_string()
}rustc_middle::ty::print::with_no_trimmed_paths!(
583                self.tcx.type_of(def_id).skip_binder().to_string()
584            );
585            let mainfile = self
586                .tcx
587                .sess
588                .local_crate_source_file()
589                .and_then(|path| path.local_path().map(|p| p.display().to_string()))
590                .unwrap_or_default();
591
592            let demangled =
593                { let _guard = NoTrimmedGuard::new(); self.tcx.def_path_str(def_id) }rustc_middle::ty::print::with_no_trimmed_paths!(self.tcx.def_path_str(def_id));
594
595            let global_blame = |section| -> (
596                rustc_sanitizers::ignorelist::Blame,
597                rustc_sanitizers::ignorelist::Blame,
598            ) {
599                let mut no_san = rustc_sanitizers::ignorelist::Blame::NONE;
600                let mut san = rustc_sanitizers::ignorelist::Blame::NONE;
601                let mut update = |prefix, query| {
602                    let (ns, s) = ignorelist.in_section_blame(section, prefix, query);
603                    no_san = no_san.max(ns);
604                    san = san.max(s);
605                };
606                update(c"global", sym_name);
607                update(c"global", &demangled);
608                update(c"src", &filename);
609                if !mainfile.is_empty() {
610                    update(c"mainfile", &mainfile);
611                }
612                update(c"type", &ty_name);
613                (no_san, san)
614            };
615
616            let sanitizers = self.tcx.sess.sanitizers();
617            let (address_nosan, address_san) = global_blame(c"address");
618            let (kaddress_nosan, kaddress_san) = global_blame(c"kernel-address");
619            let (hwaddress_nosan, hwaddress_san) = global_blame(c"hwaddress");
620            let (khwaddress_nosan, khwaddress_san) = global_blame(c"kernel-hwaddress");
621
622            let ignore_address =
623                rustc_sanitizers::ignorelist::is_blame_ignored(address_nosan, address_san);
624            let ignore_kernel_address = rustc_sanitizers::ignorelist::is_blame_ignored(
625                address_nosan.max(kaddress_nosan),
626                address_san.max(kaddress_san),
627            );
628            let ignore_hwaddress =
629                rustc_sanitizers::ignorelist::is_blame_ignored(hwaddress_nosan, hwaddress_san);
630            let ignore_kernel_hwaddress = rustc_sanitizers::ignorelist::is_blame_ignored(
631                hwaddress_nosan.max(khwaddress_nosan),
632                hwaddress_san.max(khwaddress_san),
633            );
634
635            if (sanitizers.contains(rustc_target::spec::SanitizerSet::ADDRESS) && ignore_address)
636                || (sanitizers.contains(rustc_target::spec::SanitizerSet::KERNELADDRESS)
637                    && ignore_kernel_address)
638            {
639                unsafe { llvm::LLVMRustSetNoSanitizeAddress(g) };
640            }
641            if (sanitizers.contains(rustc_target::spec::SanitizerSet::HWADDRESS)
642                && ignore_hwaddress)
643                || (sanitizers.contains(rustc_target::spec::SanitizerSet::KERNELHWADDRESS)
644                    && ignore_kernel_hwaddress)
645            {
646                unsafe { llvm::LLVMRustSetNoSanitizeHWAddress(g) };
647            }
648        }
649
650        if attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER) {
651            // `USED` and `USED_LINKER` can't be used together.
652            if !!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
    ::core::panicking::panic("assertion failed: !attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)")
};assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER));
653
654            // The semantics of #[used] in Rust only require the symbol to make it into the
655            // object file. It is explicitly allowed for the linker to strip the symbol if it
656            // is dead, which means we are allowed to use `llvm.compiler.used` instead of
657            // `llvm.used` here.
658            //
659            // Additionally, https://reviews.llvm.org/D97448 in LLVM 13 started emitting unique
660            // sections with SHF_GNU_RETAIN flag for llvm.used symbols, which may trigger bugs
661            // in the handling of `.init_array` (the static constructor list) in versions of
662            // the gold linker (prior to the one released with binutils 2.36).
663            //
664            // That said, we only ever emit these when `#[used(compiler)]` is explicitly
665            // requested. This is to avoid similar breakage on other targets, in particular
666            // MachO targets have *their* static constructor lists broken if `llvm.compiler.used`
667            // is emitted rather than `llvm.used`. However, that check happens when assigning
668            // the `CodegenFnAttrFlags` in the `codegen_fn_attrs` query, so we don't need to
669            // take care of it here.
670            self.add_compiler_used_global(g);
671        }
672        if attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
673            // `USED` and `USED_LINKER` can't be used together.
674            if !!attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER) {
    ::core::panicking::panic("assertion failed: !attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)")
};assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER));
675
676            self.add_used_global(g);
677        }
678    }
679
680    /// Add a global value to a list to be stored in the `llvm.used` variable, an array of ptr.
681    pub(crate) fn add_used_global(&mut self, global: &'ll Value) {
682        self.used_statics.push(global);
683    }
684
685    /// Add a global value to a list to be stored in the `llvm.compiler.used` variable,
686    /// an array of ptr.
687    pub(crate) fn add_compiler_used_global(&self, global: &'ll Value) {
688        self.compiler_used_statics.borrow_mut().push(global);
689    }
690
691    // We do our best here to match what Clang does when compiling Objective-C natively.
692    // See Clang's `CGObjCCommonMac::CreateCStringLiteral`:
693    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L4134
694    fn define_objc_classname(&self, classname: &str) -> &'ll Value {
695        {
    match (&self.objc_abi_version(), &1) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(self.objc_abi_version(), 1);
696
697        let llval = self.null_terminate_const_bytes(classname.as_bytes());
698        let llty = self.val_ty(llval);
699        let sym = self.generate_local_symbol_name("OBJC_CLASS_NAME_");
700        let g = self.define_global(&sym, llty).unwrap_or_else(|| {
701            ::rustc_span::macros::bug_impl(None,
    format_args!("symbol `{0}` is already defined", sym), Location::caller());bug!("symbol `{}` is already defined", sym);
702        });
703        set_global_alignment(self, g, self.tcx.data_layout.i8_align);
704        llvm::set_initializer(g, llval);
705        llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
706        llvm::set_section(g, c"__TEXT,__cstring,cstring_literals");
707        llvm::LLVMSetGlobalConstant(g, llvm::TRUE);
708        llvm::LLVMSetUnnamedAddress(g, llvm::UnnamedAddr::Global);
709        self.add_compiler_used_global(g);
710
711        g
712    }
713
714    // We do our best here to match what Clang does when compiling Objective-C natively.
715    // See Clang's `ObjCNonFragileABITypesHelper`:
716    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L6052
717    fn get_objc_class_t(&self) -> &'ll Type {
718        if let Some(class_t) = self.objc_class_t.get() {
719            return class_t;
720        }
721
722        {
    match (&self.objc_abi_version(), &2) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(self.objc_abi_version(), 2);
723
724        // struct _class_t {
725        //     struct _class_t* isa;
726        //     struct _class_t* const superclass;
727        //     void* cache;
728        //     IMP* vtable;
729        //     struct class_ro_t* ro;
730        // }
731
732        let class_t = self.type_named_struct("struct._class_t");
733        let els = [self.type_ptr(); 5];
734        let packed = false;
735        self.set_struct_body(class_t, &els, packed);
736
737        self.objc_class_t.set(Some(class_t));
738        class_t
739    }
740
741    // We do our best here to match what Clang does when compiling Objective-C natively. We
742    // deduplicate references within a CGU, but we need a reference definition in each referencing
743    // CGU. All attempts at using external references to a single reference definition result in
744    // linker errors.
745    fn get_objc_classref(&self, classname: Symbol) -> &'ll Value {
746        let mut classrefs = self.objc_classrefs.borrow_mut();
747        if let Some(classref) = classrefs.get(&classname).copied() {
748            return classref;
749        }
750
751        let g = match self.objc_abi_version() {
752            1 => {
753                // See Clang's `CGObjCMac::EmitClassRefFromId`:
754                // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5205
755                let llval = self.define_objc_classname(classname.as_str());
756                let llty = self.type_ptr();
757                let sym = self.generate_local_symbol_name("OBJC_CLASS_REFERENCES_");
758                let g = self.define_global(&sym, llty).unwrap_or_else(|| {
759                    ::rustc_span::macros::bug_impl(None,
    format_args!("symbol `{0}` is already defined", sym), Location::caller());bug!("symbol `{}` is already defined", sym);
760                });
761                set_global_alignment(self, g, self.tcx.data_layout.pointer_align().abi);
762                llvm::set_initializer(g, llval);
763                llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
764                llvm::set_section(g, c"__OBJC,__cls_refs,literal_pointers,no_dead_strip");
765                self.add_compiler_used_global(g);
766                g
767            }
768            2 => {
769                // See Clang's `CGObjCNonFragileABIMac::EmitClassRefFromId`:
770                // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L7423
771                let llval = {
772                    let extern_sym = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("OBJC_CLASS_$_{0}",
                classname.as_str()))
    })format!("OBJC_CLASS_$_{}", classname.as_str());
773                    let extern_llty = self.get_objc_class_t();
774                    self.declare_global(&extern_sym, extern_llty)
775                };
776                let llty = self.type_ptr();
777                let sym = self.generate_local_symbol_name("OBJC_CLASSLIST_REFERENCES_$_");
778                let g = self.define_global(&sym, llty).unwrap_or_else(|| {
779                    ::rustc_span::macros::bug_impl(None,
    format_args!("symbol `{0}` is already defined", sym), Location::caller());bug!("symbol `{}` is already defined", sym);
780                });
781                set_global_alignment(self, g, self.tcx.data_layout.pointer_align().abi);
782                llvm::set_initializer(g, llval);
783                llvm::set_linkage(g, llvm::Linkage::InternalLinkage);
784                llvm::set_section(g, c"__DATA,__objc_classrefs,regular,no_dead_strip");
785                self.add_compiler_used_global(g);
786                g
787            }
788            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
789        };
790
791        classrefs.insert(classname, g);
792        g
793    }
794
795    // We do our best here to match what Clang does when compiling Objective-C natively. We
796    // deduplicate references within a CGU, but we need a reference definition in each referencing
797    // CGU. All attempts at using external references to a single reference definition result in
798    // linker errors.
799    //
800    // Newer versions of Apple Clang generate calls to `@"objc_msgSend$methname"` selector stub
801    // functions. We don't currently do that. The code we generate is closer to what Apple Clang
802    // generates with the `-fno-objc-msgsend-selector-stubs` option.
803    fn get_objc_selref(&self, methname: Symbol) -> &'ll Value {
804        let mut selrefs = self.objc_selrefs.borrow_mut();
805        if let Some(selref) = selrefs.get(&methname).copied() {
806            return selref;
807        }
808
809        let abi_version = self.objc_abi_version();
810
811        // See Clang's `CGObjCCommonMac::CreateCStringLiteral`:
812        // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L4134
813        let methname_llval = self.null_terminate_const_bytes(methname.as_str().as_bytes());
814        let methname_llty = self.val_ty(methname_llval);
815        let methname_sym = self.generate_local_symbol_name("OBJC_METH_VAR_NAME_");
816        let methname_g = self.define_global(&methname_sym, methname_llty).unwrap_or_else(|| {
817            ::rustc_span::macros::bug_impl(None,
    format_args!("symbol `{0}` is already defined", methname_sym),
    Location::caller());bug!("symbol `{}` is already defined", methname_sym);
818        });
819        set_global_alignment(self, methname_g, self.tcx.data_layout.i8_align);
820        llvm::set_initializer(methname_g, methname_llval);
821        llvm::set_linkage(methname_g, llvm::Linkage::PrivateLinkage);
822        llvm::set_section(
823            methname_g,
824            match abi_version {
825                1 => c"__TEXT,__cstring,cstring_literals",
826                2 => c"__TEXT,__objc_methname,cstring_literals",
827                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
828            },
829        );
830        llvm::LLVMSetGlobalConstant(methname_g, llvm::TRUE);
831        llvm::LLVMSetUnnamedAddress(methname_g, llvm::UnnamedAddr::Global);
832        self.add_compiler_used_global(methname_g);
833
834        // See Clang's `CGObjCMac::EmitSelectorAddr`:
835        // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5243
836        // And Clang's `CGObjCNonFragileABIMac::EmitSelectorAddr`:
837        // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L7586
838        let selref_llval = methname_g;
839        let selref_llty = self.type_ptr();
840        let selref_sym = self.generate_local_symbol_name("OBJC_SELECTOR_REFERENCES_");
841        let selref_g = self.define_global(&selref_sym, selref_llty).unwrap_or_else(|| {
842            ::rustc_span::macros::bug_impl(None,
    format_args!("symbol `{0}` is already defined", selref_sym),
    Location::caller());bug!("symbol `{}` is already defined", selref_sym);
843        });
844        set_global_alignment(self, selref_g, self.tcx.data_layout.pointer_align().abi);
845        llvm::set_initializer(selref_g, selref_llval);
846        llvm::set_externally_initialized(selref_g, true);
847        llvm::set_linkage(
848            selref_g,
849            match abi_version {
850                1 => llvm::Linkage::PrivateLinkage,
851                2 => llvm::Linkage::InternalLinkage,
852                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
853            },
854        );
855        llvm::set_section(
856            selref_g,
857            match abi_version {
858                1 => c"__OBJC,__message_refs,literal_pointers,no_dead_strip",
859                2 => c"__DATA,__objc_selrefs,literal_pointers,no_dead_strip",
860                _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
861            },
862        );
863        self.add_compiler_used_global(selref_g);
864
865        selrefs.insert(methname, selref_g);
866        selref_g
867    }
868
869    // We do our best here to match what Clang does when compiling Objective-C natively.
870    // See Clang's `ObjCTypesHelper`:
871    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5936
872    // And Clang's `CGObjCMac::EmitModuleInfo`:
873    // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5151
874    pub(crate) fn define_objc_module_info(&mut self) {
875        {
    match (&self.objc_abi_version(), &1) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(self.objc_abi_version(), 1);
876
877        // struct _objc_module {
878        //     long version;                // Hardcoded to 7 in Clang.
879        //     long size;                   // sizeof(struct _objc_module)
880        //     char* name;                  // Hardcoded to classname "" in Clang.
881        //     struct _objc_symtab* symtab; // Null without class or category definitions.
882        //  }
883
884        let llty = self.type_named_struct("struct._objc_module");
885        let i32_llty = self.type_i32();
886        let ptr_llty = self.type_ptr();
887        let packed = false;
888        self.set_struct_body(llty, &[i32_llty, i32_llty, ptr_llty, ptr_llty], packed);
889
890        let version = self.const_uint(i32_llty, 7);
891        let size = self.const_uint(i32_llty, 16);
892        let name = self.define_objc_classname("");
893        let symtab = self.const_null(ptr_llty);
894        let llval = crate::common::named_struct(llty, &[version, size, name, symtab]);
895
896        let sym = "OBJC_MODULES";
897        let g = self.define_global(&sym, llty).unwrap_or_else(|| {
898            ::rustc_span::macros::bug_impl(None,
    format_args!("symbol `{0}` is already defined", sym), Location::caller());bug!("symbol `{}` is already defined", sym);
899        });
900        set_global_alignment(self, g, self.tcx.data_layout.pointer_align().abi);
901        llvm::set_initializer(g, llval);
902        llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
903        llvm::set_section(g, c"__OBJC,__module_info,regular,no_dead_strip");
904
905        self.add_compiler_used_global(g);
906    }
907}
908
909impl<'ll> StaticCodegenMethods for CodegenCx<'ll, '_> {
910    /// Get a pointer to a global variable.
911    ///
912    /// The pointer will always be in the default address space. If global variables default to a
913    /// different address space, an addrspacecast is inserted.
914    fn static_addr_of(&self, alloc: ConstAllocation<'_>, kind: Option<&str>) -> &'ll Value {
915        // FIXME: should we cache `const_alloc_to_llvm` to avoid repeating this for the
916        // same `ConstAllocation`?
917        let cv = const_alloc_to_llvm(self, alloc.inner(), IsStatic::No, IsInitOrFini::No);
918
919        let gv = self.static_addr_of_impl(cv, alloc.inner().align, kind);
920        // static_addr_of_impl returns the bare global variable, which might not be in the default
921        // address space. Cast to the default address space if necessary.
922        self.const_pointercast(gv, self.type_ptr())
923    }
924
925    fn codegen_static(&mut self, def_id: DefId) {
926        self.codegen_static_item(def_id)
927    }
928}