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