]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_codegen_llvm/src/consts.rs
New upstream version 1.65.0+dfsg1
[rustc.git] / compiler / rustc_codegen_llvm / src / consts.rs
CommitLineData
9fa01778 1use crate::base;
f2b60f7d 2use crate::common::{self, CodegenCx};
dfeec247 3use crate::debuginfo;
ba9703b0 4use crate::llvm::{self, True};
5e7ed085 5use crate::llvm_util;
9fa01778
XL
6use crate::type_::Type;
7use crate::type_of::LayoutLlvmExt;
8use crate::value::Value;
6a06907d 9use cstr::cstr;
8faf50e0 10use libc::c_uint;
dfeec247 11use rustc_codegen_ssa::traits::*;
dfeec247 12use rustc_hir::def_id::DefId;
ba9703b0
XL
13use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
14use rustc_middle::mir::interpret::{
5e7ed085 15 read_target_uint, Allocation, ConstAllocation, ErrorHandled, GlobalAlloc, InitChunk, Pointer,
94222f64 16 Scalar as InterpScalar,
ba9703b0
XL
17};
18use rustc_middle::mir::mono::MonoItem;
c295e0f8 19use rustc_middle::ty::layout::LayoutOf;
ba9703b0
XL
20use rustc_middle::ty::{self, Instance, Ty};
21use rustc_middle::{bug, span_bug};
94222f64 22use rustc_target::abi::{
c295e0f8 23 AddressSpace, Align, HasDataLayout, Primitive, Scalar, Size, WrappingRange,
94222f64
XL
24};
25use std::ops::Range;
e9174d1e 26
5e7ed085
FG
27pub fn const_alloc_to_llvm<'ll>(cx: &CodegenCx<'ll, '_>, alloc: ConstAllocation<'_>) -> &'ll Value {
28 let alloc = alloc.inner();
f2b60f7d 29 let mut llvals = Vec::with_capacity(alloc.provenance().len() + 1);
a1dfa0c6
XL
30 let dl = cx.data_layout();
31 let pointer_size = dl.pointer_size.bytes() as usize;
32
f2b60f7d
FG
33 // Note: this function may call `inspect_with_uninit_and_ptr_outside_interpreter`, so `range`
34 // must be within the bounds of `alloc` and not contain or overlap a pointer provenance.
94222f64
XL
35 fn append_chunks_of_init_and_uninit_bytes<'ll, 'a, 'b>(
36 llvals: &mut Vec<&'ll Value>,
37 cx: &'a CodegenCx<'ll, 'b>,
38 alloc: &'a Allocation,
39 range: Range<usize>,
40 ) {
5e7ed085 41 let chunks = alloc
94222f64
XL
42 .init_mask()
43 .range_as_init_chunks(Size::from_bytes(range.start), Size::from_bytes(range.end));
44
45 let chunk_to_llval = move |chunk| match chunk {
46 InitChunk::Init(range) => {
47 let range = (range.start.bytes() as usize)..(range.end.bytes() as usize);
48 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
49 cx.const_bytes(bytes)
50 }
51 InitChunk::Uninit(range) => {
52 let len = range.end.bytes() - range.start.bytes();
53 cx.const_undef(cx.type_array(cx.type_i8(), len))
54 }
55 };
56
5e7ed085
FG
57 // Generating partially-uninit consts is limited to small numbers of chunks,
58 // to avoid the cost of generating large complex const expressions.
59 // For example, `[(u32, u8); 1024 * 1024]` contains uninit padding in each element,
60 // and would result in `{ [5 x i8] zeroinitializer, [3 x i8] undef, ...repeat 1M times... }`.
61 let max = if llvm_util::get_version() < (14, 0, 0) {
62 // Generating partially-uninit consts inhibits optimizations in LLVM < 14.
63 // See https://github.com/rust-lang/rust/issues/84565.
64 1
65 } else {
064997fb 66 cx.sess().opts.unstable_opts.uninit_const_chunk_threshold
5e7ed085
FG
67 };
68 let allow_uninit_chunks = chunks.clone().take(max.saturating_add(1)).count() <= max;
94222f64 69
5e7ed085 70 if allow_uninit_chunks {
94222f64
XL
71 llvals.extend(chunks.map(chunk_to_llval));
72 } else {
5e7ed085
FG
73 // If this allocation contains any uninit bytes, codegen as if it was initialized
74 // (using some arbitrary value for uninit bytes).
75 let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
76 llvals.push(cx.const_bytes(bytes));
94222f64
XL
77 }
78 }
79
a1dfa0c6 80 let mut next_offset = 0;
f2b60f7d 81 for &(offset, alloc_id) in alloc.provenance().iter() {
a1dfa0c6
XL
82 let offset = offset.bytes();
83 assert_eq!(offset as usize as u64, offset);
84 let offset = offset as usize;
85 if offset > next_offset {
f2b60f7d 86 // This `inspect` is okay since we have checked that there is no provenance, it
e1599b0c 87 // is within the bounds of the allocation, and it doesn't affect interpreter execution
94222f64
XL
88 // (we inspect the result after interpreter execution).
89 append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, next_offset..offset);
a1dfa0c6
XL
90 }
91 let ptr_offset = read_target_uint(
92 dl.endian,
e1599b0c
XL
93 // This `inspect` is okay since it is within the bounds of the allocation, it doesn't
94 // affect interpreter execution (we inspect the result after interpreter execution),
f2b60f7d 95 // and we properly interpret the provenance as a relocation pointer offset.
3dfed10e 96 alloc.inspect_with_uninit_and_ptr_outside_interpreter(offset..(offset + pointer_size)),
dfeec247
XL
97 )
98 .expect("const_alloc_to_llvm: could not read relocation pointer")
99 as u64;
3dfed10e
XL
100
101 let address_space = match cx.tcx.global_alloc(alloc_id) {
102 GlobalAlloc::Function(..) => cx.data_layout().instruction_address_space,
064997fb
FG
103 GlobalAlloc::Static(..) | GlobalAlloc::Memory(..) | GlobalAlloc::VTable(..) => {
104 AddressSpace::DATA
105 }
3dfed10e
XL
106 };
107
a1dfa0c6 108 llvals.push(cx.scalar_to_backend(
136023e0
XL
109 InterpScalar::from_pointer(
110 Pointer::new(alloc_id, Size::from_bytes(ptr_offset)),
111 &cx.tcx,
112 ),
04454e1e
FG
113 Scalar::Initialized {
114 value: Primitive::Pointer,
115 valid_range: WrappingRange::full(dl.pointer_size),
116 },
3dfed10e 117 cx.type_i8p_ext(address_space),
a1dfa0c6
XL
118 ));
119 next_offset = offset + pointer_size;
1a4d82fc 120 }
e1599b0c
XL
121 if alloc.len() >= next_offset {
122 let range = next_offset..alloc.len();
f2b60f7d 123 // This `inspect` is okay since we have check that it is after all provenance, it is
e1599b0c 124 // within the bounds of the allocation, and it doesn't affect interpreter execution (we
94222f64
XL
125 // inspect the result after interpreter execution).
126 append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, range);
a1dfa0c6
XL
127 }
128
129 cx.const_struct(&llvals, true)
1a4d82fc
JJ
130}
131
a2a8927a 132pub fn codegen_static_initializer<'ll, 'tcx>(
a1dfa0c6
XL
133 cx: &CodegenCx<'ll, 'tcx>,
134 def_id: DefId,
5e7ed085 135) -> Result<(&'ll Value, ConstAllocation<'tcx>), ErrorHandled> {
1b1a35ee 136 let alloc = cx.tcx.eval_static_initializer(def_id)?;
a1dfa0c6 137 Ok((const_alloc_to_llvm(cx, alloc), alloc))
3b2f2976
XL
138}
139
a2a8927a 140fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: Align) {
ea8adc8c
XL
141 // The target may require greater alignment for globals than the type does.
142 // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
143 // which can force it to be smaller. Rust doesn't support this yet.
29967ef6 144 if let Some(min) = cx.sess().target.min_global_align {
a1dfa0c6 145 match Align::from_bits(min) {
ff7c6d11 146 Ok(min) => align = align.max(min),
ea8adc8c 147 Err(err) => {
2c00a5a8 148 cx.sess().err(&format!("invalid minimum global alignment: {}", err));
ea8adc8c
XL
149 }
150 }
151 }
152 unsafe {
a1dfa0c6 153 llvm::LLVMSetAlignment(gv, align.bytes() as u32);
ea8adc8c
XL
154 }
155}
156
a2a8927a 157fn check_and_apply_linkage<'ll, 'tcx>(
b7449926 158 cx: &CodegenCx<'ll, 'tcx>,
8faf50e0
XL
159 attrs: &CodegenFnAttrs,
160 ty: Ty<'tcx>,
3dfed10e 161 sym: &str,
f2b60f7d 162 def_id: DefId,
b7449926 163) -> &'ll Value {
8faf50e0
XL
164 let llty = cx.layout_of(ty).llvm_type(cx);
165 if let Some(linkage) = attrs.linkage {
166 debug!("get_static: sym={} linkage={:?}", sym, linkage);
167
168 // If this is a static with a linkage specified, then we need to handle
169 // it a little specially. The typesystem prevents things like &T and
170 // extern "C" fn() from being non-null, so we can't just declare a
171 // static and call it a day. Some linkages (like weak) will make it such
172 // that the static actually has a null value.
1b1a35ee 173 let llty2 = if let ty::RawPtr(ref mt) = ty.kind() {
0bf4aa26
XL
174 cx.layout_of(mt.ty).llvm_type(cx)
175 } else {
dc9dc135 176 cx.sess().span_fatal(
f2b60f7d 177 cx.tcx.def_span(def_id),
dfeec247
XL
178 "must have type `*const T` or `*mut T` due to `#[linkage]` attribute",
179 )
8faf50e0
XL
180 };
181 unsafe {
182 // Declare a symbol `foo` with the desired linkage.
c295e0f8 183 let g1 = cx.declare_global(sym, llty2);
8faf50e0
XL
184 llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
185
186 // Declare an internal global `extern_with_linkage_foo` which
187 // is initialized with the address of `foo`. If `foo` is
188 // discarded during linking (for example, if `foo` has weak
189 // linkage and there are no definitions), then
190 // `extern_with_linkage_foo` will instead be initialized to
191 // zero.
192 let mut real_name = "_rust_extern_with_linkage_".to_string();
c295e0f8 193 real_name.push_str(sym);
dfeec247 194 let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| {
29967ef6 195 cx.sess().span_fatal(
f2b60f7d 196 cx.tcx.def_span(def_id),
29967ef6
XL
197 &format!("symbol `{}` is already defined", &sym),
198 )
8faf50e0
XL
199 });
200 llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
201 llvm::LLVMSetInitializer(g2, g1);
202 g2
203 }
f2b60f7d
FG
204 } else if cx.tcx.sess.target.arch == "x86" &&
205 let Some(dllimport) = common::get_dllimport(cx.tcx, def_id, sym)
206 {
207 cx.declare_global(&common::i686_decorated_name(&dllimport, common::is_mingw_gnu_toolchain(&cx.tcx.sess.target), true), llty)
8faf50e0
XL
208 } else {
209 // Generate an external declaration.
210 // FIXME(nagisa): investigate whether it can be changed into define_global
c295e0f8 211 cx.declare_global(sym, llty)
8faf50e0
XL
212 }
213}
214
a2a8927a 215pub fn ptrcast<'ll>(val: &'ll Value, ty: &'ll Type) -> &'ll Value {
dfeec247 216 unsafe { llvm::LLVMConstPointerCast(val, ty) }
a1dfa0c6 217}
c1a9b12d 218
a2a8927a 219impl<'ll> CodegenCx<'ll, '_> {
923072b8 220 pub(crate) fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
dfeec247 221 unsafe { llvm::LLVMConstBitCast(val, ty) }
a1dfa0c6 222 }
c1a9b12d 223
923072b8 224 pub(crate) fn static_addr_of_mut(
a1dfa0c6
XL
225 &self,
226 cv: &'ll Value,
227 align: Align,
228 kind: Option<&str>,
229 ) -> &'ll Value {
230 unsafe {
231 let gv = match kind {
232 Some(kind) if !self.tcx.sess.fewer_names() => {
233 let name = self.generate_local_symbol_name(kind);
a2a8927a 234 let gv = self.define_global(&name, self.val_ty(cv)).unwrap_or_else(|| {
dfeec247 235 bug!("symbol `{}` is already defined", name);
a1dfa0c6
XL
236 });
237 llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage);
238 gv
dfeec247 239 }
a1dfa0c6
XL
240 _ => self.define_private_global(self.val_ty(cv)),
241 };
242 llvm::LLVMSetInitializer(gv, cv);
c295e0f8 243 set_global_alignment(self, gv, align);
ba9703b0 244 llvm::SetUnnamedAddress(gv, llvm::UnnamedAddr::Global);
a1dfa0c6
XL
245 gv
246 }
247 }
8faf50e0 248
923072b8 249 pub(crate) fn get_static(&self, def_id: DefId) -> &'ll Value {
a1dfa0c6
XL
250 let instance = Instance::mono(self.tcx, def_id);
251 if let Some(&g) = self.instances.borrow().get(&instance) {
252 return g;
253 }
254
dfeec247
XL
255 let defined_in_current_codegen_unit =
256 self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
257 assert!(
258 !defined_in_current_codegen_unit,
259 "consts::get_static() should always hit the cache for \
a1dfa0c6 260 statics defined in the same CGU, but did not for `{:?}`",
dfeec247
XL
261 def_id
262 );
a1dfa0c6 263
3dfed10e 264 let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
e74abb32 265 let sym = self.tcx.symbol_name(instance).name;
5869c6ff 266 let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
a1dfa0c6 267
5869c6ff 268 debug!("get_static: sym={} instance={:?} fn_attrs={:?}", sym, instance, fn_attrs);
a1dfa0c6 269
5869c6ff 270 let g = if def_id.is_local() && !self.tcx.is_foreign_item(def_id) {
a1dfa0c6 271 let llty = self.layout_of(ty).llvm_type(self);
5869c6ff
XL
272 if let Some(g) = self.get_declared_value(sym) {
273 if self.val_ty(g) != self.type_ptr_to(llty) {
274 span_bug!(self.tcx.def_span(def_id), "Conflicting types for static");
a1dfa0c6 275 }
5869c6ff 276 }
a1dfa0c6 277
5869c6ff 278 let g = self.declare_global(sym, llty);
a1dfa0c6 279
5869c6ff
XL
280 if !self.tcx.is_reachable_non_generic(def_id) {
281 unsafe {
282 llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
a1dfa0c6
XL
283 }
284 }
c1a9b12d 285
9e0c209e 286 g
c1a9b12d 287 } else {
c295e0f8 288 check_and_apply_linkage(self, fn_attrs, ty, sym, def_id)
5869c6ff 289 };
a1dfa0c6 290
5869c6ff
XL
291 // Thread-local statics in some other crate need to *always* be linked
292 // against in a thread-local fashion, so we need to be sure to apply the
293 // thread-local attribute locally if it was present remotely. If we
294 // don't do this then linker errors can be generated where the linker
295 // complains that one object files has a thread local version of the
296 // symbol and another one doesn't.
297 if fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
298 llvm::set_thread_local_mode(g, self.tls_model);
299 }
a1dfa0c6 300
5869c6ff 301 if !def_id.is_local() {
dfeec247 302 let needs_dll_storage_attr = self.use_dll_storage_attrs && !self.tcx.is_foreign_item(def_id) &&
a1dfa0c6
XL
303 // ThinLTO can't handle this workaround in all cases, so we don't
304 // emit the attrs. Instead we make them unnecessary by disallowing
9fa01778
XL
305 // dynamic linking when linker plugin based LTO is enabled.
306 !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
a1dfa0c6
XL
307
308 // If this assertion triggers, there's something wrong with commandline
309 // argument validation.
dfeec247
XL
310 debug_assert!(
311 !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
29967ef6 312 && self.tcx.sess.target.is_like_windows
dfeec247
XL
313 && self.tcx.sess.opts.cg.prefer_dynamic)
314 );
a1dfa0c6
XL
315
316 if needs_dll_storage_attr {
0731742a 317 // This item is external but not foreign, i.e., it originates from an external Rust
a1dfa0c6
XL
318 // crate. Since we don't know whether this crate will be linked dynamically or
319 // statically in the final application, we always mark such symbols as 'dllimport'.
320 // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
321 // to make things work.
322 //
323 // However, in some scenarios we defer emission of statics to downstream
324 // crates, so there are cases where a static with an upstream DefId
325 // is actually present in the current crate. We can find out via the
326 // is_codegened_item query.
327 if !self.tcx.is_codegened_item(def_id) {
328 unsafe {
329 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
330 }
331 }
332 }
5869c6ff 333 }
a1dfa0c6
XL
334
335 if self.use_dll_storage_attrs && self.tcx.is_dllimport_foreign_item(def_id) {
336 // For foreign (native) libs we know the exact storage type to use.
337 unsafe {
338 llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
1a4d82fc
JJ
339 }
340 }
c1a9b12d 341
17df50a5
XL
342 unsafe {
343 if self.should_assume_dso_local(g, true) {
344 llvm::LLVMRustSetDSOLocal(g, true);
345 }
346 }
347
a1dfa0c6
XL
348 self.instances.borrow_mut().insert(instance, g);
349 g
350 }
351}
352
a2a8927a 353impl<'ll> StaticMethods for CodegenCx<'ll, '_> {
dfeec247 354 fn static_addr_of(&self, cv: &'ll Value, align: Align, kind: Option<&str>) -> &'ll Value {
a1dfa0c6
XL
355 if let Some(&gv) = self.const_globals.borrow().get(&cv) {
356 unsafe {
357 // Upgrade the alignment in cases where the same constant is used with different
358 // alignment requirements
359 let llalign = align.bytes() as u32;
360 if llalign > llvm::LLVMGetAlignment(gv) {
361 llvm::LLVMSetAlignment(gv, llalign);
362 }
94b46f34 363 }
a1dfa0c6
XL
364 return gv;
365 }
366 let gv = self.static_addr_of_mut(cv, align, kind);
367 unsafe {
368 llvm::LLVMSetGlobalConstant(gv, True);
c1a9b12d 369 }
a1dfa0c6
XL
370 self.const_globals.borrow_mut().insert(cv, gv);
371 gv
372 }
5bcae85e 373
dfeec247 374 fn codegen_static(&self, def_id: DefId, is_mutable: bool) {
a1dfa0c6
XL
375 unsafe {
376 let attrs = self.tcx.codegen_fn_attrs(def_id);
377
5e7ed085 378 let Ok((v, alloc)) = codegen_static_initializer(self, def_id) else {
a1dfa0c6 379 // Error has already been reported
5e7ed085 380 return;
a1dfa0c6 381 };
5e7ed085 382 let alloc = alloc.inner();
a1dfa0c6
XL
383
384 let g = self.get_static(def_id);
385
386 // boolean SSA values are i1, but they have to be stored in i8 slots,
387 // otherwise some LLVM optimization passes don't work as expected
388 let mut val_llty = self.val_ty(v);
389 let v = if val_llty == self.type_i1() {
390 val_llty = self.type_i8();
391 llvm::LLVMConstZExt(v, val_llty)
392 } else {
393 v
394 };
395
396 let instance = Instance::mono(self.tcx, def_id);
3dfed10e 397 let ty = instance.ty(self.tcx, ty::ParamEnv::reveal_all());
a1dfa0c6
XL
398 let llty = self.layout_of(ty).llvm_type(self);
399 let g = if val_llty == llty {
400 g
401 } else {
402 // If we created the global with the wrong type,
403 // correct the type.
60c5eb7d
XL
404 let name = llvm::get_value_name(g).to_vec();
405 llvm::set_value_name(g, b"");
a1dfa0c6
XL
406
407 let linkage = llvm::LLVMRustGetLinkage(g);
408 let visibility = llvm::LLVMRustGetVisibility(g);
409
410 let new_g = llvm::LLVMRustGetOrInsertGlobal(
dfeec247
XL
411 self.llmod,
412 name.as_ptr().cast(),
413 name.len(),
414 val_llty,
415 );
a1dfa0c6
XL
416
417 llvm::LLVMRustSetLinkage(new_g, linkage);
418 llvm::LLVMRustSetVisibility(new_g, visibility);
419
04454e1e
FG
420 // The old global has had its name removed but is returned by
421 // get_static since it is in the instance cache. Provide an
422 // alternative lookup that points to the new global so that
423 // global_asm! can compute the correct mangled symbol name
424 // for the global.
425 self.renamed_statics.borrow_mut().insert(def_id, new_g);
426
a1dfa0c6
XL
427 // To avoid breaking any invariants, we leave around the old
428 // global for the moment; we'll replace all references to it
429 // with the new global later. (See base::codegen_backend.)
430 self.statics_to_rauw.borrow_mut().push((g, new_g));
431 new_g
432 };
c295e0f8 433 set_global_alignment(self, g, self.align_of(ty));
a1dfa0c6
XL
434 llvm::LLVMSetInitializer(g, v);
435
17df50a5
XL
436 if self.should_assume_dso_local(g, true) {
437 llvm::LLVMRustSetDSOLocal(g, true);
438 }
439
a1dfa0c6
XL
440 // As an optimization, all shared statics which do not have interior
441 // mutability are placed into read-only memory.
29967ef6
XL
442 if !is_mutable && self.type_is_freeze(ty) {
443 llvm::LLVMSetGlobalConstant(g, llvm::True);
a1dfa0c6 444 }
5bcae85e 445
5e7ed085 446 debuginfo::build_global_var_di_node(self, def_id, g);
a1dfa0c6
XL
447
448 if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
449 llvm::set_thread_local_mode(g, self.tls_model);
450
451 // Do not allow LLVM to change the alignment of a TLS on macOS.
452 //
453 // By default a global's alignment can be freely increased.
454 // This allows LLVM to generate more performant instructions
0731742a 455 // e.g., using load-aligned into a SIMD register.
a1dfa0c6
XL
456 //
457 // However, on macOS 10.10 or below, the dynamic linker does not
458 // respect any alignment given on the TLS (radar 24221680).
459 // This will violate the alignment assumption, and causing segfault at runtime.
460 //
461 // This bug is very easy to trigger. In `println!` and `panic!`,
462 // the `LOCAL_STDOUT`/`LOCAL_STDERR` handles are stored in a TLS,
463 // which the values would be `mem::replace`d on initialization.
464 // The implementation of `mem::replace` will use SIMD
465 // whenever the size is 32 bytes or higher. LLVM notices SIMD is used
466 // and tries to align `LOCAL_STDOUT`/`LOCAL_STDERR` to a 32-byte boundary,
467 // which macOS's dyld disregarded and causing crashes
468 // (see issues #51794, #51758, #50867, #48866 and #44056).
469 //
470 // To workaround the bug, we trick LLVM into not increasing
471 // the global's alignment by explicitly assigning a section to it
472 // (equivalent to automatically generating a `#[link_section]` attribute).
473 // See the comment in the `GlobalValue::canIncreaseAlignment()` function
474 // of `lib/IR/Globals.cpp` for why this works.
475 //
476 // When the alignment is not increased, the optimized `mem::replace`
477 // will use load-unaligned instructions instead, and thus avoiding the crash.
478 //
479 // We could remove this hack whenever we decide to drop macOS 10.10 support.
29967ef6 480 if self.tcx.sess.target.is_like_osx {
f2b60f7d 481 // The `inspect` method is okay here because we checked for provenance, and
ba9703b0
XL
482 // because we are doing this access to inspect the final interpreter state
483 // (not as part of the interpreter execution).
484 //
485 // FIXME: This check requires that the (arbitrary) value of undefined bytes
486 // happens to be zero. Instead, we should only check the value of defined bytes
487 // and set all undefined bytes to zero if this allocation is headed for the
488 // BSS.
f2b60f7d 489 let all_bytes_are_zero = alloc.provenance().is_empty()
ba9703b0 490 && alloc
3dfed10e 491 .inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len())
e1599b0c 492 .iter()
ba9703b0
XL
493 .all(|&byte| byte == 0);
494
495 let sect_name = if all_bytes_are_zero {
6a06907d 496 cstr!("__DATA,__thread_bss")
a1dfa0c6 497 } else {
6a06907d 498 cstr!("__DATA,__thread_data")
a1dfa0c6
XL
499 };
500 llvm::LLVMSetSection(g, sect_name.as_ptr());
501 }
502 }
503
a1dfa0c6
XL
504 // Wasm statics with custom link sections get special treatment as they
505 // go into custom sections of the wasm executable.
3c0e092e 506 if self.tcx.sess.target.is_like_wasm {
a1dfa0c6
XL
507 if let Some(section) = attrs.link_section {
508 let section = llvm::LLVMMDStringInContext(
509 self.llcx,
e74abb32 510 section.as_str().as_ptr().cast(),
a1dfa0c6
XL
511 section.as_str().len() as c_uint,
512 );
f2b60f7d 513 assert!(alloc.provenance().is_empty());
e1599b0c 514
f2b60f7d 515 // The `inspect` method is okay here because we checked for provenance, and
e1599b0c
XL
516 // because we are doing this access to inspect the final interpreter state (not
517 // as part of the interpreter execution).
dfeec247 518 let bytes =
3dfed10e 519 alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len());
a1dfa0c6
XL
520 let alloc = llvm::LLVMMDStringInContext(
521 self.llcx,
e74abb32 522 bytes.as_ptr().cast(),
e1599b0c 523 bytes.len() as c_uint,
a1dfa0c6
XL
524 );
525 let data = [section, alloc];
526 let meta = llvm::LLVMMDNodeInContext(self.llcx, data.as_ptr(), 2);
527 llvm::LLVMAddNamedMetadataOperand(
528 self.llmod,
e74abb32 529 "wasm.custom_sections\0".as_ptr().cast(),
a1dfa0c6
XL
530 meta,
531 );
532 }
533 } else {
c295e0f8 534 base::set_link_section(g, attrs);
8faf50e0 535 }
8faf50e0 536
a1dfa0c6 537 if attrs.flags.contains(CodegenFnAttrFlags::USED) {
5099ac24
FG
538 // `USED` and `USED_LINKER` can't be used together.
539 assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER));
540
94222f64
XL
541 // The semantics of #[used] in Rust only require the symbol to make it into the
542 // object file. It is explicitly allowed for the linker to strip the symbol if it
064997fb
FG
543 // is dead, which means we are allowed use `llvm.compiler.used` instead of
544 // `llvm.used` here.
545 //
94222f64
XL
546 // Additionally, https://reviews.llvm.org/D97448 in LLVM 13 started emitting unique
547 // sections with SHF_GNU_RETAIN flag for llvm.used symbols, which may trigger bugs
064997fb
FG
548 // in the handling of `.init_array` (the static constructor list) in versions of
549 // the gold linker (prior to the one released with binutils 2.36).
550 //
551 // That said, we only ever emit these when compiling for ELF targets, unless
552 // `#[used(compiler)]` is explicitly requested. This is to avoid similar breakage
553 // on other targets, in particular MachO targets have *their* static constructor
554 // lists broken if `llvm.compiler.used` is emitted rather than llvm.used. However,
555 // that check happens when assigning the `CodegenFnAttrFlags` in `rustc_typeck`,
556 // so we don't need to take care of it here.
94222f64 557 self.add_compiler_used_global(g);
a1dfa0c6 558 }
5099ac24
FG
559 if attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
560 // `USED` and `USED_LINKER` can't be used together.
561 assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED));
562
563 self.add_used_global(g);
564 }
cc61c64b 565 }
1a4d82fc 566 }
3dfed10e
XL
567
568 /// Add a global value to a list to be stored in the `llvm.used` variable, an array of i8*.
569 fn add_used_global(&self, global: &'ll Value) {
570 let cast = unsafe { llvm::LLVMConstPointerCast(global, self.type_i8p()) };
571 self.used_statics.borrow_mut().push(cast);
572 }
94222f64
XL
573
574 /// Add a global value to a list to be stored in the `llvm.compiler.used` variable,
575 /// an array of i8*.
576 fn add_compiler_used_global(&self, global: &'ll Value) {
577 let cast = unsafe { llvm::LLVMConstPointerCast(global, self.type_i8p()) };
578 self.compiler_used_statics.borrow_mut().push(cast);
579 }
1a4d82fc 580}