1use std::ops::Range;
23use 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::{
12Allocation, ConstAllocation, ErrorHandled, InitChunk, Pointer, Scalaras InterpScalar,
13read_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};
2122use crate::common::CodegenCx;
23use crate::diagnostics::SymbolAlreadyDefined;
24use crate::llvm::{self, Type, Value, const_ptr_auth};
25use crate::{base, debuginfo};
2627/// Indicates whether a value originates from a `static`.
28pub(crate) enum IsStatic {
29 Yes,
30 No,
31}
32/// Indicates whether a symbol is part of `.init_array` or `.fini_array`.
33#[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)]
34pub(crate) enum IsInitOrFini {
35 Yes,
36 No,
37}
38pub(crate) fn const_alloc_to_llvm<'ll>(
39 cx: &CodegenCx<'ll, '_>,
40 alloc: &Allocation,
41 is_static: IsStatic,
42 is_init_fini: IsInitOrFini,
43) -> Value<'ll> {
44// We expect that callers of const_alloc_to_llvm will instead directly codegen a pointer or
45 // integer for any &ZST where the ZST is a constant (i.e. not a static). We should never be
46 // producing empty LLVM allocations as they're just adding noise to binaries and forcing less
47 // optimal codegen.
48 //
49 // Statics have a guaranteed meaningful address so it's less clear that we want to do
50 // something like this; it's also harder.
51if #[allow(non_exhaustive_omitted_patterns)] match is_static {
IsStatic::No => true,
_ => false,
}matches!(is_static, IsStatic::No) {
52if !(alloc.len() != 0) {
::core::panicking::panic("assertion failed: alloc.len() != 0")
};assert!(alloc.len() != 0);
53 }
54let mut llvals = Vec::with_capacity(alloc.provenance().ptrs().len() + 1);
55let dl = cx.data_layout();
56let pointer_size = dl.pointer_size();
57let pointer_size_bytes = pointer_size.bytes() as usize;
5859// Note: this function may call `inspect_with_uninit_and_ptr_outside_interpreter`, so `range`
60 // must be within the bounds of `alloc` and not contain or overlap a pointer provenance.
61fn append_chunks_of_init_and_uninit_bytes<'ll, 'a, 'b>(
62 llvals: &mut Vec<Value<'ll>>,
63 cx: &'a CodegenCx<'ll, 'b>,
64 alloc: &'a Allocation,
65 range: Range<usize>,
66 ) {
67let chunks = alloc.init_mask().range_as_init_chunks(range.clone().into());
6869let chunk_to_llval = move |chunk| match chunk {
70 InitChunk::Init(range) => {
71let range = (range.start.bytes() as usize)..(range.end.bytes() as usize);
72let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
73cx.const_bytes(bytes)
74 }
75 InitChunk::Uninit(range) => {
76let len = range.end.bytes() - range.start.bytes();
77cx.const_undef(cx.type_array(cx.type_i8(), len))
78 }
79 };
8081// Generating partially-uninit consts is limited to small numbers of chunks,
82 // to avoid the cost of generating large complex const expressions.
83 // For example, `[(u32, u8); 1024 * 1024]` contains uninit padding in each element, and
84 // would result in `{ [5 x i8] zeroinitializer, [3 x i8] undef, ...repeat 1M times... }`.
85let max = cx.sess().opts.unstable_opts.uninit_const_chunk_threshold;
86let allow_uninit_chunks = chunks.clone().take(max.saturating_add(1)).count() <= max;
8788if allow_uninit_chunks {
89llvals.extend(chunks.map(chunk_to_llval));
90 } else {
91// If this allocation contains any uninit bytes, codegen as if it was initialized
92 // (using some arbitrary value for uninit bytes).
93let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
94llvals.push(cx.const_bytes(bytes));
95 }
96 }
9798let mut next_offset = 0;
99for &(offset, prov) in alloc.provenance().ptrs().iter() {
100let offset = offset.bytes();
101{
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);
102let offset = offset as usize;
103if offset > next_offset {
104// This `inspect` is okay since we have checked that there is no provenance, it
105 // is within the bounds of the allocation, and it doesn't affect interpreter execution
106 // (we inspect the result after interpreter execution).
107append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, next_offset..offset);
108 }
109let ptr_offset = read_target_uint(
110 dl.endian,
111// This `inspect` is okay since it is within the bounds of the allocation, it doesn't
112 // affect interpreter execution (we inspect the result after interpreter execution),
113 // and we properly interpret the provenance as a relocation pointer offset.
114alloc.inspect_with_uninit_and_ptr_outside_interpreter(
115 offset..(offset + pointer_size_bytes),
116 ),
117 )
118 .expect("const_alloc_to_llvm: could not read relocation pointer")
119as u64;
120121let address_space = cx.tcx.global_alloc(prov.alloc_id()).address_space(cx);
122let schema = if cx.sess().pointer_authentication() {
123match is_init_fini {
124 IsInitOrFini::Yes => cx.sess().pointer_authentication_init_fini(),
125 IsInitOrFini::No => cx.sess().pointer_authentication_functions(),
126 }
127 } else {
128None
129};
130 llvals.push(cx.scalar_to_backend_with_pac(
131 InterpScalar::from_pointer(Pointer::new(prov, Size::from_bytes(ptr_offset)), &cx.tcx),
132 Scalar::Initialized {
133 value: Primitive::Pointer(address_space),
134 valid_range: WrappingRange::full(pointer_size),
135 },
136 cx.type_ptr_ext(address_space),
137 schema,
138 ));
139 next_offset = offset + pointer_size_bytes;
140 }
141if alloc.len() >= next_offset {
142let range = next_offset..alloc.len();
143// This `inspect` is okay since we have check that it is after all provenance, it is
144 // within the bounds of the allocation, and it doesn't affect interpreter execution (we
145 // inspect the result after interpreter execution).
146append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, range);
147 }
148149// Avoid wrapping in a struct if there is only a single value. This ensures
150 // that LLVM is able to perform the string merging optimization if the constant
151 // is a valid C string. LLVM only considers bare arrays for this optimization,
152 // not arrays wrapped in a struct. LLVM handles this at:
153 // https://github.com/rust-lang/llvm-project/blob/acaea3d2bb8f351b740db7ebce7d7a40b9e21488/llvm/lib/Target/TargetLoweringObjectFile.cpp#L249-L280
154if let &[data] = &*llvals { data } else { cx.const_struct(&llvals, true) }
155}
156157fn codegen_static_initializer<'ll, 'tcx>(
158 cx: &CodegenCx<'ll, 'tcx>,
159 def_id: DefId,
160) -> Result<(Value<'ll>, ConstAllocation<'tcx>), ErrorHandled> {
161let alloc = cx.tcx.eval_static_initializer(def_id)?;
162let attrs = cx.tcx.codegen_fn_attrs(def_id);
163// FIXME(jchlanda) Decide if this could be better served by `ctor` crate. See the discussion
164 // here: <https://github.com/rust-lang/rust/pull/155722#discussion_r3320477047>
165let is_in_init_fini: IsInitOrFini = attrs166 .link_section
167 .map(|link_section| {
168let s = link_section.as_str();
169if s.starts_with(".init_array") || s.starts_with(".fini_array") {
170 IsInitOrFini::Yes171 } else {
172 IsInitOrFini::No173 }
174 })
175 .unwrap_or(IsInitOrFini::No);
176Ok((const_alloc_to_llvm(cx, alloc.inner(), IsStatic::Yes, is_in_init_fini), alloc))
177}
178179fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: Value<'ll>, mut align: Align) {
180// The target may require greater alignment for globals than the type does.
181 // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
182 // which can force it to be smaller. Rust doesn't support this yet.
183if let Some(min_global) = cx.sess().target.min_global_align {
184align = Ord::max(align, min_global);
185 }
186 llvm::set_alignment(gv, align);
187}
188189fn check_and_apply_linkage<'ll, 'tcx>(
190 cx: &CodegenCx<'ll, 'tcx>,
191 attrs: &CodegenFnAttrs,
192 llty: Type<'ll>,
193 sym: &str,
194 def_id: DefId,
195) -> Value<'ll> {
196if let Some(linkage) = attrs.import_linkage {
197{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/consts.rs:197",
"rustc_codegen_llvm::consts", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/consts.rs"),
::tracing_core::__macro_support::Option::Some(197u32),
::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);
198199let mut should_sign = false;
200// Declare a symbol `foo`. If `foo` is an extern_weak symbol, we declare
201 // an extern_weak function, otherwise a global with the desired linkage.
202let actual_global = if #[allow(non_exhaustive_omitted_patterns)] match attrs.import_linkage {
Some(Linkage::ExternalWeak) => true,
_ => false,
}matches!(attrs.import_linkage, Some(Linkage::ExternalWeak)) {
203// An `extern_weak` function is represented as an `Option<unsafe extern ...>`,
204 // we extract the function signature and declare it as an extern_weak function
205 // instead of an extern_weak i8.
206let instance = Instance::mono(cx.tcx, def_id);
207if let ty::Adt(struct_def, args) = instance.ty(cx.tcx, cx.typing_env()).kind()
208 && cx.tcx.is_lang_item(struct_def.did(), LangItem::Option)
209 && let ty::FnPtr(sig, header) = args.type_at(0).kind()
210 {
211let fn_sig = sig.with(*header);
212let fn_abi = cx.fn_abi_of_fn_ptr(fn_sig, ty::List::empty());
213// Decide if the initializer needs to be signed
214if cx.sess().pointer_authentication_functions().is_some()
215 && #[allow(non_exhaustive_omitted_patterns)] match fn_sig.abi() {
ExternAbi::C { .. } | ExternAbi::System { .. } => true,
_ => false,
}matches!(fn_sig.abi(), ExternAbi::C { .. } | ExternAbi::System { .. })216 {
217should_sign = true;
218 }
219cx.declare_fn(sym, fn_abi, None)
220 } else {
221cx.declare_global(sym, cx.type_i8())
222 }
223 } else {
224cx.declare_global(sym, cx.type_i8())
225 };
226 llvm::set_linkage(actual_global, base::linkage_to_llvm(linkage));
227228// Normally this is done in `get_static_inner`, but when as we generate an internal global,
229 // it will apply the dso_local to the internal global instead, so do it here, too.
230cx.assume_dso_local(actual_global, true);
231232// Sign the function pointer that is used to initialize the global
233let initializer = if should_sign {
234let schema = cx235 .tcx
236 .sess
237 .pointer_authentication_functions()
238 .expect("pointer authentication functions must be available when signing");
239240const_ptr_auth(
241actual_global,
242schema.key as u32,
243schema.constant_discriminator as u64,
244None, /* address_diversity */
245)
246 } else {
247actual_global248 };
249250// Declare an internal global `extern_with_linkage_foo` which
251 // is initialized with the address of `foo`. If `foo` is
252 // discarded during linking (for example, if `foo` has weak
253 // linkage and there are no definitions), then
254 // `extern_with_linkage_foo` will instead be initialized to
255 // zero.
256let real_name =
257::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));
258let pointer_global =
259cx.define_global(&real_name, cx.val_ty(initializer)).unwrap_or_else(|| {
260cx.sess().dcx().emit_fatal(SymbolAlreadyDefined {
261 span: cx.tcx.def_span(def_id),
262 symbol_name: sym,
263 })
264 });
265 llvm::set_linkage(pointer_global, llvm::Linkage::InternalLinkage);
266 llvm::set_unnamed_address(pointer_global, llvm::UnnamedAddr::Global);
267268 llvm::set_initializer(pointer_global, initializer);
269270pointer_global271 } else if cx.tcx.sess.target.arch == Arch::X86272 && common::is_using_dlltool(&cx.tcx.sess.target)
273 && let Some(dllimport) = crate::common::get_dllimport(cx.tcx, def_id, sym)
274 {
275cx.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
279cx.declare_global(sym, llty)
280 }
281}
282283impl<'ll> CodegenCx<'ll, '_> {
284pub(crate) fn const_bitcast(&self, val: Value<'ll>, ty: Type<'ll>) -> Value<'ll> {
285unsafe { llvm::LLVMConstBitCast(val, ty) }
286 }
287288pub(crate) fn const_pointercast(&self, val: Value<'ll>, ty: Type<'ll>) -> Value<'ll> {
289unsafe { llvm::LLVMConstPointerCast(val, ty) }
290 }
291292/// 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.
296pub(crate) fn static_addr_of_mut(
297&self,
298 cv: Value<'ll>,
299 align: Align,
300 kind: Option<&str>,
301 ) -> Value<'ll> {
302let gv = match kind {
303Some(kind) if !self.tcx.sess.fewer_names() => {
304let name = self.generate_local_symbol_name(kind);
305self.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 }
309_ => self.define_global("", self.val_ty(cv)).unwrap_or_else(|| {
310::rustc_span::macros::bug_impl(None,
format_args!("anonymous global symbol is already defined"),
Location::caller());bug!("anonymous global symbol is already defined");
311 }),
312 };
313 llvm::set_linkage(gv, llvm::Linkage::PrivateLinkage);
314 llvm::set_initializer(gv, cv);
315set_global_alignment(self, gv, align);
316 llvm::set_unnamed_address(gv, llvm::UnnamedAddr::Global);
317gv318 }
319320/// Create a global constant.
321 ///
322 /// The returned global variable is a pointer in the default address space for globals.
323pub(crate) fn static_addr_of_impl(
324&self,
325 cv: Value<'ll>,
326 align: Align,
327 kind: Option<&str>,
328 ) -> Value<'ll> {
329if let Some(&gv) = self.const_globals.borrow().get(&cv) {
330unsafe {
331// Upgrade the alignment in cases where the same constant is used with different
332 // alignment requirements
333let llalign = align.bytes() as u32;
334if llalign > llvm::LLVMGetAlignment(gv) {
335 llvm::LLVMSetAlignment(gv, llalign);
336 }
337 }
338return gv;
339 }
340let gv = self.static_addr_of_mut(cv, align, kind);
341 llvm::set_global_constant(gv, true);
342343self.const_globals.borrow_mut().insert(cv, gv);
344gv345 }
346347{}
#[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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/consts.rs"),
::tracing_core::__macro_support::Option::Some(347u32),
::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: Value<'ll> = 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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/consts.rs:350",
"rustc_codegen_llvm::consts", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/consts.rs"),
::tracing_core::__macro_support::Option::Some(350u32),
::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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/consts.rs:359",
"rustc_codegen_llvm::consts", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/consts.rs"),
::tracing_core::__macro_support::Option::Some(359u32),
::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.type_array(self.type_i8(),
self.layout_of(ty).size.bytes())
};
self.get_static_inner(def_id, llty)
}
}
}#[instrument(level = "debug", skip(self))]348pub(crate) fn get_static(&self, def_id: DefId) -> Value<'ll> {
349let instance = Instance::mono(self.tcx, def_id);
350trace!(?instance);
351352let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
353// Nested statics do not have a type, so pick a dummy type and let `codegen_static` figure
354 // out the llvm type from the actual evaluated initializer.
355let llty = if nested {
356self.type_i8()
357 } else {
358let ty = instance.ty(self.tcx, self.typing_env());
359trace!(?ty);
360self.type_array(self.type_i8(), self.layout_of(ty).size.bytes())
361 };
362self.get_static_inner(def_id, llty)
363 }
364365{}
#[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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/consts.rs"),
::tracing_core::__macro_support::Option::Some(365u32),
::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: Value<'ll> = 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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/consts.rs:369",
"rustc_codegen_llvm::consts", ::tracing::Level::TRACE,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/consts.rs"),
::tracing_core::__macro_support::Option::Some(369u32),
::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/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/consts.rs:384",
"rustc_codegen_llvm::consts", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/5f4effd579500175af844241eb179e756190f1e7/compiler/rustc_codegen_llvm/src/consts.rs"),
::tracing_core::__macro_support::Option::Some(384u32),
::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))]366fn get_static_inner(&self, def_id: DefId, llty: Type<'ll>) -> Value<'ll> {
367let instance = Instance::mono(self.tcx, def_id);
368if let Some(&g) = self.instances.borrow().get(&instance) {
369trace!("used cached value");
370return g;
371 }
372373let defined_in_current_codegen_unit =
374self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
375assert!(
376 !defined_in_current_codegen_unit,
377"consts::get_static() should always hit the cache for \
378 statics defined in the same CGU, but did not for `{def_id:?}`"
379);
380381let sym = self.tcx.symbol_name(instance).name;
382let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
383384debug!(?sym, ?fn_attrs);
385386let g = if def_id.is_local() && !self.tcx.is_foreign_item(def_id) {
387if let Some(g) = self.get_declared_value(sym) {
388if self.val_ty(g) != self.type_ptr() {
389span_bug!(self.tcx.def_span(def_id), "Conflicting types for static");
390 }
391 }
392393let g = self.declare_global(sym, llty);
394395if !self.tcx.is_reachable_non_generic(def_id) {
396 llvm::set_visibility(g, llvm::Visibility::Hidden);
397 }
398399 g
400 } else if let Some(classname) = fn_attrs.objc_class {
401self.get_objc_classref(classname)
402 } else if let Some(methname) = fn_attrs.objc_selector {
403self.get_objc_selref(methname)
404 } else {
405 check_and_apply_linkage(self, fn_attrs, llty, sym, def_id)
406 };
407408// Thread-local statics in some other crate need to *always* be linked
409 // against in a thread-local fashion, so we need to be sure to apply the
410 // thread-local attribute locally if it was present remotely. If we
411 // don't do this then linker errors can be generated where the linker
412 // complains that one object files has a thread local version of the
413 // symbol and another one doesn't.
414if fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
415 llvm::set_thread_local_mode(g, self.tls_model);
416 }
417418let dso_local = self.assume_dso_local(g, true);
419420if !def_id.is_local() {
421let is_eii = fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM);
422let needs_dll_storage_attr = self.use_dll_storage_attrs
423// EII static declarations are encoded as foreign items, but their symbols are
424 // resolved by Rust crates, not native libraries.
425&& (!self.tcx.is_foreign_item(def_id) || is_eii)
426// Local definitions can never be imported, so we must not apply
427 // the DLLImport annotation.
428&& !dso_local
429// Linker plugin ThinLTO doesn't create the self-dllimport Rust uses for rlibs
430 // as the code generation happens out of process. Instead we assume static linkage
431 // and disallow dynamic linking when linker plugin based LTO is enabled.
432 // Regular in-process ThinLTO doesn't need this workaround.
433&& !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
434435// If this assertion triggers, there's something wrong with commandline
436 // argument validation.
437assert!(
438 !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
439 && self.tcx.sess.target.is_like_windows
440 && self.tcx.sess.opts.cg.prefer_dynamic)
441 );
442443if needs_dll_storage_attr {
444// This item is external but not foreign, i.e., it originates from an external Rust
445 // crate. EII static declarations are handled the same way, even though they are
446 // represented as foreign items. Since we don't know whether this crate will be
447 // linked dynamically or statically in the final application, we always mark such
448 // symbols as 'dllimport'. If final linkage happens to be static, we rely on
449 // compiler-emitted __imp_ stubs to make things work.
450 //
451 // However, in some scenarios we defer emission of statics to downstream
452 // crates, so there are cases where a static with an upstream DefId
453 // is actually present in the current crate. We can find out via the
454 // is_codegened_item query.
455if !self.tcx.is_codegened_item(def_id) {
456 llvm::set_dllimport_storage_class(g);
457 }
458 }
459 }
460461if self.use_dll_storage_attrs
462 && let Some(library) = self.tcx.native_library(def_id)
463 && library.kind.is_dllimport()
464 {
465// For foreign (native) libs we know the exact storage type to use.
466llvm::set_dllimport_storage_class(g);
467 }
468469self.instances.borrow_mut().insert(instance, g);
470 g
471 }
472473fn codegen_static_item(&mut self, def_id: DefId) {
474if !llvm::LLVMGetInitializer(self.instances.borrow().get(&Instance::mono(self.tcx,
def_id)).copied().unwrap()).is_none() {
::core::panicking::panic("assertion failed: llvm::LLVMGetInitializer(self.instances.borrow().get(&Instance::mono(self.tcx,\n def_id)).copied().unwrap()).is_none()")
};assert!(
475 llvm::LLVMGetInitializer(
476self.instances.borrow().get(&Instance::mono(self.tcx, def_id)).copied().unwrap()
477 )
478 .is_none()
479 );
480let attrs = self.tcx.codegen_fn_attrs(def_id);
481482let Ok((v, alloc)) = codegen_static_initializer(self, def_id) else {
483// Error has already been reported
484return;
485 };
486let alloc = alloc.inner();
487488let val_llty = self.val_ty(v);
489490let g = self.get_static_inner(def_id, val_llty);
491let llty = self.get_type_of_global(g);
492493let g = if val_llty == llty {
494g495 } else {
496// codegen_static_initializer creates the global value just from the
497 // `Allocation` data by generating one big struct value that is just
498 // all the bytes and pointers after each other. This will almost never
499 // match the type that the static was declared with. Unfortunately
500 // we can't just LLVMConstBitCast our way out of it because that has very
501 // specific rules on what can be cast. So instead of adding a new way to
502 // generate static initializers that match the static's type, we picked
503 // the easier option and retroactively change the type of the static item itself.
504let name = String::from_utf8(llvm::get_value_name(g))
505 .expect("we declare our statics with a utf8-valid name");
506 llvm::set_value_name(g, b"");
507508let linkage = llvm::get_linkage(g);
509let visibility = llvm::get_visibility(g);
510511let new_g = self.declare_global(&name, val_llty);
512513 llvm::set_linkage(new_g, linkage);
514 llvm::set_visibility(new_g, visibility);
515516// The old global has had its name removed but is returned by
517 // get_static since it is in the instance cache. Provide an
518 // alternative lookup that points to the new global so that
519 // global_asm! can compute the correct mangled symbol name
520 // for the global.
521self.renamed_statics.borrow_mut().insert(def_id, new_g);
522523// To avoid breaking any invariants, we leave around the old
524 // global for the moment; we'll replace all references to it
525 // with the new global later. (See base::codegen_backend.)
526self.statics_to_rauw.borrow_mut().push((g, new_g));
527new_g528 };
529530// NOTE: Alignment from attributes has already been applied to the allocation.
531set_global_alignment(self, g, alloc.align);
532 llvm::set_initializer(g, v);
533534self.assume_dso_local(g, true);
535536// Forward the allocation's mutability (picked by the const interner) to LLVM.
537if alloc.mutability.is_not() {
538 llvm::set_global_constant(g, true);
539 }
540541 debuginfo::build_global_var_di_node(self, def_id, g);
542543if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
544 llvm::set_thread_local_mode(g, self.tls_model);
545 }
546547// Wasm statics with custom link sections get special treatment as they
548 // also go into custom sections of the wasm executable. The exception to
549 // this is the `.init_array` section for which we can't emit a custom
550 // section as it contains relocations.
551if self.tcx.sess.target.is_like_wasm
552 && attrs553 .link_section
554 .map(|link_section| !link_section.as_str().starts_with(".init_array"))
555 .unwrap_or(true)
556 {
557if let Some(section) = attrs.link_section {
558let section = self.create_metadata(section.as_str().as_bytes());
559if !alloc.provenance().ptrs().is_empty() {
::core::panicking::panic("assertion failed: alloc.provenance().ptrs().is_empty()")
};assert!(alloc.provenance().ptrs().is_empty());
560561// The `inspect` method is okay here because we checked for provenance, and
562 // because we are doing this access to inspect the final interpreter state (not
563 // as part of the interpreter execution).
564let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len());
565let alloc = self.create_metadata(bytes);
566let data = [section, alloc];
567self.module_add_named_metadata_node(self.llmod(), c"wasm.custom_sections", &data);
568 }
569 }
570571 base::set_link_section(g, attrs);
572 base::set_variable_sanitizer_attrs(g, attrs);
573574if let Some(ignorelist) = &self.sanitizer_ignorelist {
575let instance = ty::Instance::mono(self.tcx, def_id);
576let sym_name = self.tcx.symbol_name(instance).name;
577let span = self.tcx.def_span(def_id);
578let source_map = self.tcx.sess.source_map();
579let filename =
580source_map.span_to_filename(span).prefer_local_unconditionally().to_string();
581let ty_name = {
let _guard = NoTrimmedGuard::new();
self.tcx.type_of(def_id).skip_binder().to_string()
}rustc_middle::ty::print::with_no_trimmed_paths!(
582self.tcx.type_of(def_id).skip_binder().to_string()
583 );
584let mainfile = self585 .tcx
586 .sess
587 .local_crate_source_file()
588 .and_then(|path| path.local_path().map(|p| p.display().to_string()))
589 .unwrap_or_default();
590591let demangled =
592{ 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));
593594let global_blame = |section| -> (
595 rustc_sanitizers::ignorelist::Blame,
596 rustc_sanitizers::ignorelist::Blame,
597 ) {
598let mut no_san = rustc_sanitizers::ignorelist::Blame::NONE;
599let mut san = rustc_sanitizers::ignorelist::Blame::NONE;
600let mut update = |prefix, query| {
601let (ns, s) = ignorelist.in_section_blame(section, prefix, query);
602no_san = no_san.max(ns);
603san = san.max(s);
604 };
605update(c"global", sym_name);
606update(c"global", &demangled);
607update(c"src", &filename);
608if !mainfile.is_empty() {
609update(c"mainfile", &mainfile);
610 }
611update(c"type", &ty_name);
612 (no_san, san)
613 };
614615let sanitizers = self.tcx.sess.sanitizers();
616let (address_nosan, address_san) = global_blame(c"address");
617let (kaddress_nosan, kaddress_san) = global_blame(c"kernel-address");
618let (hwaddress_nosan, hwaddress_san) = global_blame(c"hwaddress");
619let (khwaddress_nosan, khwaddress_san) = global_blame(c"kernel-hwaddress");
620621let ignore_address =
622 rustc_sanitizers::ignorelist::is_blame_ignored(address_nosan, address_san);
623let ignore_kernel_address = rustc_sanitizers::ignorelist::is_blame_ignored(
624address_nosan.max(kaddress_nosan),
625address_san.max(kaddress_san),
626 );
627let ignore_hwaddress =
628 rustc_sanitizers::ignorelist::is_blame_ignored(hwaddress_nosan, hwaddress_san);
629let ignore_kernel_hwaddress = rustc_sanitizers::ignorelist::is_blame_ignored(
630hwaddress_nosan.max(khwaddress_nosan),
631hwaddress_san.max(khwaddress_san),
632 );
633634if (sanitizers.contains(rustc_target::spec::SanitizerSet::ADDRESS) && ignore_address)
635 || (sanitizers.contains(rustc_target::spec::SanitizerSet::KERNELADDRESS)
636 && ignore_kernel_address)
637 {
638unsafe { llvm::LLVMRustSetNoSanitizeAddress(g) };
639 }
640if (sanitizers.contains(rustc_target::spec::SanitizerSet::HWADDRESS)
641 && ignore_hwaddress)
642 || (sanitizers.contains(rustc_target::spec::SanitizerSet::KERNELHWADDRESS)
643 && ignore_kernel_hwaddress)
644 {
645unsafe { llvm::LLVMRustSetNoSanitizeHWAddress(g) };
646 }
647 }
648649if attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER) {
650// `USED` and `USED_LINKER` can't be used together.
651if !!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
::core::panicking::panic("assertion failed: !attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER)")
};assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER));
652653// The semantics of #[used] in Rust only require the symbol to make it into the
654 // object file. It is explicitly allowed for the linker to strip the symbol if it
655 // is dead, which means we are allowed to use `llvm.compiler.used` instead of
656 // `llvm.used` here.
657 //
658 // Additionally, https://reviews.llvm.org/D97448 in LLVM 13 started emitting unique
659 // sections with SHF_GNU_RETAIN flag for llvm.used symbols, which may trigger bugs
660 // in the handling of `.init_array` (the static constructor list) in versions of
661 // the gold linker (prior to the one released with binutils 2.36).
662 //
663 // That said, we only ever emit these when `#[used(compiler)]` is explicitly
664 // requested. This is to avoid similar breakage on other targets, in particular
665 // MachO targets have *their* static constructor lists broken if `llvm.compiler.used`
666 // is emitted rather than `llvm.used`. However, that check happens when assigning
667 // the `CodegenFnAttrFlags` in the `codegen_fn_attrs` query, so we don't need to
668 // take care of it here.
669self.add_compiler_used_global(g);
670 }
671if attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
672// `USED` and `USED_LINKER` can't be used together.
673if !!attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER) {
::core::panicking::panic("assertion failed: !attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER)")
};assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_COMPILER));
674675self.add_used_global(g);
676 }
677 }
678679/// Add a global value to a list to be stored in the `llvm.used` variable, an array of ptr.
680pub(crate) fn add_used_global(&mut self, global: Value<'ll>) {
681self.used_statics.push(global);
682 }
683684/// Add a global value to a list to be stored in the `llvm.compiler.used` variable,
685 /// an array of ptr.
686pub(crate) fn add_compiler_used_global(&self, global: Value<'ll>) {
687self.compiler_used_statics.borrow_mut().push(global);
688 }
689690// We do our best here to match what Clang does when compiling Objective-C natively.
691 // See Clang's `CGObjCCommonMac::CreateCStringLiteral`:
692 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L4134
693fn define_objc_classname(&self, classname: &str) -> Value<'ll> {
694{
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);
695696let llval = self.null_terminate_const_bytes(classname.as_bytes());
697let llty = self.val_ty(llval);
698let sym = self.generate_local_symbol_name("OBJC_CLASS_NAME_");
699let g = self.define_global(&sym, llty).unwrap_or_else(|| {
700::rustc_span::macros::bug_impl(None,
format_args!("symbol `{0}` is already defined", sym), Location::caller());bug!("symbol `{}` is already defined", sym);
701 });
702set_global_alignment(self, g, self.tcx.data_layout.i8_align);
703 llvm::set_initializer(g, llval);
704 llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
705 llvm::set_section(g, c"__TEXT,__cstring,cstring_literals");
706 llvm::LLVMSetGlobalConstant(g, llvm::TRUE);
707 llvm::LLVMSetUnnamedAddress(g, llvm::UnnamedAddr::Global);
708self.add_compiler_used_global(g);
709710g711 }
712713// We do our best here to match what Clang does when compiling Objective-C natively.
714 // See Clang's `ObjCNonFragileABITypesHelper`:
715 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L6052
716fn get_objc_class_t(&self) -> Type<'ll> {
717if let Some(class_t) = self.objc_class_t.get() {
718return class_t;
719 }
720721{
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);
722723// struct _class_t {
724 // struct _class_t* isa;
725 // struct _class_t* const superclass;
726 // void* cache;
727 // IMP* vtable;
728 // struct class_ro_t* ro;
729 // }
730731let class_t = self.type_named_struct("struct._class_t");
732let els = [self.type_ptr(); 5];
733self.set_struct_body(class_t, &els);
734735self.objc_class_t.set(Some(class_t));
736class_t737 }
738739// We do our best here to match what Clang does when compiling Objective-C natively. We
740 // deduplicate references within a CGU, but we need a reference definition in each referencing
741 // CGU. All attempts at using external references to a single reference definition result in
742 // linker errors.
743fn get_objc_classref(&self, classname: Symbol) -> Value<'ll> {
744let mut classrefs = self.objc_classrefs.borrow_mut();
745if let Some(classref) = classrefs.get(&classname).copied() {
746return classref;
747 }
748749let g = match self.objc_abi_version() {
7501 => {
751// See Clang's `CGObjCMac::EmitClassRefFromId`:
752 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5205
753let llval = self.define_objc_classname(classname.as_str());
754let llty = self.type_ptr();
755let sym = self.generate_local_symbol_name("OBJC_CLASS_REFERENCES_");
756let g = self.define_global(&sym, llty).unwrap_or_else(|| {
757::rustc_span::macros::bug_impl(None,
format_args!("symbol `{0}` is already defined", sym), Location::caller());bug!("symbol `{}` is already defined", sym);
758 });
759set_global_alignment(self, g, self.tcx.data_layout.pointer_align());
760 llvm::set_initializer(g, llval);
761 llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
762 llvm::set_section(g, c"__OBJC,__cls_refs,literal_pointers,no_dead_strip");
763self.add_compiler_used_global(g);
764g765 }
7662 => {
767// See Clang's `CGObjCNonFragileABIMac::EmitClassRefFromId`:
768 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L7423
769let llval = {
770let extern_sym = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("OBJC_CLASS_$_{0}",
classname.as_str()))
})format!("OBJC_CLASS_$_{}", classname.as_str());
771let extern_llty = self.get_objc_class_t();
772self.declare_global(&extern_sym, extern_llty)
773 };
774let llty = self.type_ptr();
775let sym = self.generate_local_symbol_name("OBJC_CLASSLIST_REFERENCES_$_");
776let g = self.define_global(&sym, llty).unwrap_or_else(|| {
777::rustc_span::macros::bug_impl(None,
format_args!("symbol `{0}` is already defined", sym), Location::caller());bug!("symbol `{}` is already defined", sym);
778 });
779set_global_alignment(self, g, self.tcx.data_layout.pointer_align());
780 llvm::set_initializer(g, llval);
781 llvm::set_linkage(g, llvm::Linkage::InternalLinkage);
782 llvm::set_section(g, c"__DATA,__objc_classrefs,regular,no_dead_strip");
783self.add_compiler_used_global(g);
784g785 }
786_ => ::core::panicking::unreachable_default_msg()unreachable!(),
787 };
788789classrefs.insert(classname, g);
790g791 }
792793// We do our best here to match what Clang does when compiling Objective-C natively. We
794 // deduplicate references within a CGU, but we need a reference definition in each referencing
795 // CGU. All attempts at using external references to a single reference definition result in
796 // linker errors.
797 //
798 // Newer versions of Apple Clang generate calls to `@"objc_msgSend$methname"` selector stub
799 // functions. We don't currently do that. The code we generate is closer to what Apple Clang
800 // generates with the `-fno-objc-msgsend-selector-stubs` option.
801fn get_objc_selref(&self, methname: Symbol) -> Value<'ll> {
802let mut selrefs = self.objc_selrefs.borrow_mut();
803if let Some(selref) = selrefs.get(&methname).copied() {
804return selref;
805 }
806807let abi_version = self.objc_abi_version();
808809// See Clang's `CGObjCCommonMac::CreateCStringLiteral`:
810 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L4134
811let methname_llval = self.null_terminate_const_bytes(methname.as_str().as_bytes());
812let methname_llty = self.val_ty(methname_llval);
813let methname_sym = self.generate_local_symbol_name("OBJC_METH_VAR_NAME_");
814let methname_g = self.define_global(&methname_sym, methname_llty).unwrap_or_else(|| {
815::rustc_span::macros::bug_impl(None,
format_args!("symbol `{0}` is already defined", methname_sym),
Location::caller());bug!("symbol `{}` is already defined", methname_sym);
816 });
817set_global_alignment(self, methname_g, self.tcx.data_layout.i8_align);
818 llvm::set_initializer(methname_g, methname_llval);
819 llvm::set_linkage(methname_g, llvm::Linkage::PrivateLinkage);
820 llvm::set_section(
821methname_g,
822match abi_version {
8231 => c"__TEXT,__cstring,cstring_literals",
8242 => c"__TEXT,__objc_methname,cstring_literals",
825_ => ::core::panicking::unreachable_default_msg()unreachable!(),
826 },
827 );
828 llvm::LLVMSetGlobalConstant(methname_g, llvm::TRUE);
829 llvm::LLVMSetUnnamedAddress(methname_g, llvm::UnnamedAddr::Global);
830self.add_compiler_used_global(methname_g);
831832// See Clang's `CGObjCMac::EmitSelectorAddr`:
833 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5243
834 // And Clang's `CGObjCNonFragileABIMac::EmitSelectorAddr`:
835 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L7586
836let selref_llval = methname_g;
837let selref_llty = self.type_ptr();
838let selref_sym = self.generate_local_symbol_name("OBJC_SELECTOR_REFERENCES_");
839let selref_g = self.define_global(&selref_sym, selref_llty).unwrap_or_else(|| {
840::rustc_span::macros::bug_impl(None,
format_args!("symbol `{0}` is already defined", selref_sym),
Location::caller());bug!("symbol `{}` is already defined", selref_sym);
841 });
842set_global_alignment(self, selref_g, self.tcx.data_layout.pointer_align());
843 llvm::set_initializer(selref_g, selref_llval);
844 llvm::set_externally_initialized(selref_g, true);
845 llvm::set_linkage(
846selref_g,
847match abi_version {
8481 => llvm::Linkage::PrivateLinkage,
8492 => llvm::Linkage::InternalLinkage,
850_ => ::core::panicking::unreachable_default_msg()unreachable!(),
851 },
852 );
853 llvm::set_section(
854selref_g,
855match abi_version {
8561 => c"__OBJC,__message_refs,literal_pointers,no_dead_strip",
8572 => c"__DATA,__objc_selrefs,literal_pointers,no_dead_strip",
858_ => ::core::panicking::unreachable_default_msg()unreachable!(),
859 },
860 );
861self.add_compiler_used_global(selref_g);
862863selrefs.insert(methname, selref_g);
864selref_g865 }
866867// We do our best here to match what Clang does when compiling Objective-C natively.
868 // See Clang's `ObjCTypesHelper`:
869 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5936
870 // And Clang's `CGObjCMac::EmitModuleInfo`:
871 // https://github.com/llvm/llvm-project/blob/llvmorg-20.1.8/clang/lib/CodeGen/CGObjCMac.cpp#L5151
872pub(crate) fn define_objc_module_info(&mut self) {
873{
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);
874875// struct _objc_module {
876 // long version; // Hardcoded to 7 in Clang.
877 // long size; // sizeof(struct _objc_module)
878 // char* name; // Hardcoded to classname "" in Clang.
879 // struct _objc_symtab* symtab; // Null without class or category definitions.
880 // }
881882let llty = self.type_named_struct("struct._objc_module");
883let i32_llty = self.type_i32();
884let ptr_llty = self.type_ptr();
885self.set_struct_body(llty, &[i32_llty, i32_llty, ptr_llty, ptr_llty]);
886887let version = self.const_uint(i32_llty, 7);
888let size = self.const_uint(i32_llty, 16);
889let name = self.define_objc_classname("");
890let symtab = self.const_null(ptr_llty);
891let llval = crate::common::named_struct(llty, &[version, size, name, symtab]);
892893let sym = "OBJC_MODULES";
894let g = self.define_global(sym, llty).unwrap_or_else(|| {
895::rustc_span::macros::bug_impl(None,
format_args!("symbol `{0}` is already defined", sym), Location::caller());bug!("symbol `{}` is already defined", sym);
896 });
897set_global_alignment(self, g, self.tcx.data_layout.pointer_align());
898 llvm::set_initializer(g, llval);
899 llvm::set_linkage(g, llvm::Linkage::PrivateLinkage);
900 llvm::set_section(g, c"__OBJC,__module_info,regular,no_dead_strip");
901902self.add_compiler_used_global(g);
903 }
904}
905906impl<'ll> StaticCodegenMethodsfor CodegenCx<'ll, '_> {
907/// Get a pointer to a global variable.
908 ///
909 /// The pointer will always be in the default address space. If global variables default to a
910 /// different address space, an addrspacecast is inserted.
911fn static_addr_of(&self, alloc: ConstAllocation<'_>, kind: Option<&str>) -> Value<'ll> {
912// FIXME: should we cache `const_alloc_to_llvm` to avoid repeating this for the
913 // same `ConstAllocation`?
914let cv = const_alloc_to_llvm(self, alloc.inner(), IsStatic::No, IsInitOrFini::No);
915916let gv = self.static_addr_of_impl(cv, alloc.inner().align, kind);
917// static_addr_of_impl returns the bare global variable, which might not be in the default
918 // address space. Cast to the default address space if necessary.
919self.const_pointercast(gv, self.type_ptr())
920 }
921922fn codegen_static(&mut self, def_id: DefId) {
923self.codegen_static_item(def_id)
924 }
925}