rustc_codegen_llvm/
consts.rs

1use std::ops::Range;
2
3use rustc_abi::{
4    Align, AlignFromBytesError, HasDataLayout, Primitive, Scalar, Size, WrappingRange,
5};
6use rustc_codegen_ssa::common;
7use rustc_codegen_ssa::traits::*;
8use rustc_hir::LangItem;
9use rustc_hir::def::DefKind;
10use rustc_hir::def_id::DefId;
11use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
12use rustc_middle::mir::interpret::{
13    Allocation, ConstAllocation, ErrorHandled, InitChunk, Pointer, Scalar as InterpScalar,
14    read_target_uint,
15};
16use rustc_middle::mir::mono::{Linkage, MonoItem};
17use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf};
18use rustc_middle::ty::{self, Instance};
19use rustc_middle::{bug, span_bug};
20use tracing::{debug, instrument, trace};
21
22use crate::common::{AsCCharPtr, CodegenCx};
23use crate::errors::{
24    InvalidMinimumAlignmentNotPowerOfTwo, InvalidMinimumAlignmentTooLarge, SymbolAlreadyDefined,
25};
26use crate::llvm::{self, True};
27use crate::type_::Type;
28use crate::type_of::LayoutLlvmExt;
29use crate::value::Value;
30use crate::{base, debuginfo};
31
32pub(crate) fn const_alloc_to_llvm<'ll>(
33    cx: &CodegenCx<'ll, '_>,
34    alloc: ConstAllocation<'_>,
35    is_static: bool,
36) -> &'ll Value {
37    let alloc = alloc.inner();
38    // We expect that callers of const_alloc_to_llvm will instead directly codegen a pointer or
39    // integer for any &ZST where the ZST is a constant (i.e. not a static). We should never be
40    // producing empty LLVM allocations as they're just adding noise to binaries and forcing less
41    // optimal codegen.
42    //
43    // Statics have a guaranteed meaningful address so it's less clear that we want to do
44    // something like this; it's also harder.
45    if !is_static {
46        assert!(alloc.len() != 0);
47    }
48    let mut llvals = Vec::with_capacity(alloc.provenance().ptrs().len() + 1);
49    let dl = cx.data_layout();
50    let pointer_size = dl.pointer_size.bytes() as usize;
51
52    // Note: this function may call `inspect_with_uninit_and_ptr_outside_interpreter`, so `range`
53    // must be within the bounds of `alloc` and not contain or overlap a pointer provenance.
54    fn append_chunks_of_init_and_uninit_bytes<'ll, 'a, 'b>(
55        llvals: &mut Vec<&'ll Value>,
56        cx: &'a CodegenCx<'ll, 'b>,
57        alloc: &'a Allocation,
58        range: Range<usize>,
59    ) {
60        let chunks = alloc.init_mask().range_as_init_chunks(range.clone().into());
61
62        let chunk_to_llval = move |chunk| match chunk {
63            InitChunk::Init(range) => {
64                let range = (range.start.bytes() as usize)..(range.end.bytes() as usize);
65                let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
66                cx.const_bytes(bytes)
67            }
68            InitChunk::Uninit(range) => {
69                let len = range.end.bytes() - range.start.bytes();
70                cx.const_undef(cx.type_array(cx.type_i8(), len))
71            }
72        };
73
74        // Generating partially-uninit consts is limited to small numbers of chunks,
75        // to avoid the cost of generating large complex const expressions.
76        // For example, `[(u32, u8); 1024 * 1024]` contains uninit padding in each element, and
77        // would result in `{ [5 x i8] zeroinitializer, [3 x i8] undef, ...repeat 1M times... }`.
78        let max = cx.sess().opts.unstable_opts.uninit_const_chunk_threshold;
79        let allow_uninit_chunks = chunks.clone().take(max.saturating_add(1)).count() <= max;
80
81        if allow_uninit_chunks {
82            llvals.extend(chunks.map(chunk_to_llval));
83        } else {
84            // If this allocation contains any uninit bytes, codegen as if it was initialized
85            // (using some arbitrary value for uninit bytes).
86            let bytes = alloc.inspect_with_uninit_and_ptr_outside_interpreter(range);
87            llvals.push(cx.const_bytes(bytes));
88        }
89    }
90
91    let mut next_offset = 0;
92    for &(offset, prov) in alloc.provenance().ptrs().iter() {
93        let offset = offset.bytes();
94        assert_eq!(offset as usize as u64, offset);
95        let offset = offset as usize;
96        if offset > next_offset {
97            // This `inspect` is okay since we have checked that there is no provenance, it
98            // is within the bounds of the allocation, and it doesn't affect interpreter execution
99            // (we inspect the result after interpreter execution).
100            append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, next_offset..offset);
101        }
102        let ptr_offset = read_target_uint(
103            dl.endian,
104            // This `inspect` is okay since it is within the bounds of the allocation, it doesn't
105            // affect interpreter execution (we inspect the result after interpreter execution),
106            // and we properly interpret the provenance as a relocation pointer offset.
107            alloc.inspect_with_uninit_and_ptr_outside_interpreter(offset..(offset + pointer_size)),
108        )
109        .expect("const_alloc_to_llvm: could not read relocation pointer")
110            as u64;
111
112        let address_space = cx.tcx.global_alloc(prov.alloc_id()).address_space(cx);
113
114        llvals.push(cx.scalar_to_backend(
115            InterpScalar::from_pointer(Pointer::new(prov, Size::from_bytes(ptr_offset)), &cx.tcx),
116            Scalar::Initialized {
117                value: Primitive::Pointer(address_space),
118                valid_range: WrappingRange::full(dl.pointer_size),
119            },
120            cx.type_ptr_ext(address_space),
121        ));
122        next_offset = offset + pointer_size;
123    }
124    if alloc.len() >= next_offset {
125        let range = next_offset..alloc.len();
126        // This `inspect` is okay since we have check that it is after all provenance, it is
127        // within the bounds of the allocation, and it doesn't affect interpreter execution (we
128        // inspect the result after interpreter execution).
129        append_chunks_of_init_and_uninit_bytes(&mut llvals, cx, alloc, range);
130    }
131
132    cx.const_struct(&llvals, true)
133}
134
135fn codegen_static_initializer<'ll, 'tcx>(
136    cx: &CodegenCx<'ll, 'tcx>,
137    def_id: DefId,
138) -> Result<(&'ll Value, ConstAllocation<'tcx>), ErrorHandled> {
139    let alloc = cx.tcx.eval_static_initializer(def_id)?;
140    Ok((const_alloc_to_llvm(cx, alloc, /*static*/ true), alloc))
141}
142
143fn set_global_alignment<'ll>(cx: &CodegenCx<'ll, '_>, gv: &'ll Value, mut align: Align) {
144    // The target may require greater alignment for globals than the type does.
145    // Note: GCC and Clang also allow `__attribute__((aligned))` on variables,
146    // which can force it to be smaller. Rust doesn't support this yet.
147    if let Some(min) = cx.sess().target.min_global_align {
148        match Align::from_bits(min) {
149            Ok(min) => align = align.max(min),
150            Err(err) => match err {
151                AlignFromBytesError::NotPowerOfTwo(align) => {
152                    cx.sess().dcx().emit_err(InvalidMinimumAlignmentNotPowerOfTwo { align });
153                }
154                AlignFromBytesError::TooLarge(align) => {
155                    cx.sess().dcx().emit_err(InvalidMinimumAlignmentTooLarge { align });
156                }
157            },
158        }
159    }
160    unsafe {
161        llvm::LLVMSetAlignment(gv, align.bytes() as u32);
162    }
163}
164
165fn check_and_apply_linkage<'ll, 'tcx>(
166    cx: &CodegenCx<'ll, 'tcx>,
167    attrs: &CodegenFnAttrs,
168    llty: &'ll Type,
169    sym: &str,
170    def_id: DefId,
171) -> &'ll Value {
172    if let Some(linkage) = attrs.import_linkage {
173        debug!("get_static: sym={} linkage={:?}", sym, linkage);
174
175        // Declare a symbol `foo`. If `foo` is an extern_weak symbol, we declare
176        // an extern_weak function, otherwise a global with the desired linkage.
177        let g1 = if matches!(attrs.import_linkage, Some(Linkage::ExternalWeak)) {
178            // An `extern_weak` function is represented as an `Option<unsafe extern ...>`,
179            // we extract the function signature and declare it as an extern_weak function
180            // instead of an extern_weak i8.
181            let instance = Instance::mono(cx.tcx, def_id);
182            if let ty::Adt(struct_def, args) = instance.ty(cx.tcx, cx.typing_env()).kind()
183                && cx.tcx.is_lang_item(struct_def.did(), LangItem::Option)
184                && let ty::FnPtr(sig, header) = args.type_at(0).kind()
185            {
186                let fn_sig = sig.with(*header);
187
188                let fn_abi = cx.fn_abi_of_fn_ptr(fn_sig, ty::List::empty());
189                cx.declare_fn(sym, &fn_abi, None)
190            } else {
191                cx.declare_global(sym, cx.type_i8())
192            }
193        } else {
194            cx.declare_global(sym, cx.type_i8())
195        };
196        llvm::set_linkage(g1, base::linkage_to_llvm(linkage));
197
198        // Declare an internal global `extern_with_linkage_foo` which
199        // is initialized with the address of `foo`. If `foo` is
200        // discarded during linking (for example, if `foo` has weak
201        // linkage and there are no definitions), then
202        // `extern_with_linkage_foo` will instead be initialized to
203        // zero.
204        let mut real_name = "_rust_extern_with_linkage_".to_string();
205        real_name.push_str(sym);
206        let g2 = cx.define_global(&real_name, llty).unwrap_or_else(|| {
207            cx.sess().dcx().emit_fatal(SymbolAlreadyDefined {
208                span: cx.tcx.def_span(def_id),
209                symbol_name: sym,
210            })
211        });
212        llvm::set_linkage(g2, llvm::Linkage::InternalLinkage);
213        llvm::set_initializer(g2, g1);
214        g2
215    } else if cx.tcx.sess.target.arch == "x86"
216        && common::is_mingw_gnu_toolchain(&cx.tcx.sess.target)
217        && let Some(dllimport) = crate::common::get_dllimport(cx.tcx, def_id, sym)
218    {
219        cx.declare_global(&common::i686_decorated_name(dllimport, true, true, false), llty)
220    } else {
221        // Generate an external declaration.
222        // FIXME(nagisa): investigate whether it can be changed into define_global
223        cx.declare_global(sym, llty)
224    }
225}
226
227impl<'ll> CodegenCx<'ll, '_> {
228    pub(crate) fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
229        unsafe { llvm::LLVMConstBitCast(val, ty) }
230    }
231
232    pub(crate) fn const_pointercast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
233        unsafe { llvm::LLVMConstPointerCast(val, ty) }
234    }
235
236    /// Create a global variable.
237    ///
238    /// The returned global variable is a pointer in the default address space for globals.
239    /// Fails if a symbol with the given name already exists.
240    pub(crate) fn static_addr_of_mut(
241        &self,
242        cv: &'ll Value,
243        align: Align,
244        kind: Option<&str>,
245    ) -> &'ll Value {
246        let gv = match kind {
247            Some(kind) if !self.tcx.sess.fewer_names() => {
248                let name = self.generate_local_symbol_name(kind);
249                let gv = self.define_global(&name, self.val_ty(cv)).unwrap_or_else(|| {
250                    bug!("symbol `{}` is already defined", name);
251                });
252                llvm::set_linkage(gv, llvm::Linkage::PrivateLinkage);
253                gv
254            }
255            _ => self.define_private_global(self.val_ty(cv)),
256        };
257        llvm::set_initializer(gv, cv);
258        set_global_alignment(self, gv, align);
259        llvm::SetUnnamedAddress(gv, llvm::UnnamedAddr::Global);
260        gv
261    }
262
263    /// Create a global constant.
264    ///
265    /// The returned global variable is a pointer in the default address space for globals.
266    pub(crate) fn static_addr_of_impl(
267        &self,
268        cv: &'ll Value,
269        align: Align,
270        kind: Option<&str>,
271    ) -> &'ll Value {
272        if let Some(&gv) = self.const_globals.borrow().get(&cv) {
273            unsafe {
274                // Upgrade the alignment in cases where the same constant is used with different
275                // alignment requirements
276                let llalign = align.bytes() as u32;
277                if llalign > llvm::LLVMGetAlignment(gv) {
278                    llvm::LLVMSetAlignment(gv, llalign);
279                }
280            }
281            return gv;
282        }
283        let gv = self.static_addr_of_mut(cv, align, kind);
284        unsafe {
285            llvm::LLVMSetGlobalConstant(gv, True);
286        }
287        self.const_globals.borrow_mut().insert(cv, gv);
288        gv
289    }
290
291    #[instrument(level = "debug", skip(self))]
292    pub(crate) fn get_static(&self, def_id: DefId) -> &'ll Value {
293        let instance = Instance::mono(self.tcx, def_id);
294        trace!(?instance);
295
296        let DefKind::Static { nested, .. } = self.tcx.def_kind(def_id) else { bug!() };
297        // Nested statics do not have a type, so pick a dummy type and let `codegen_static` figure
298        // out the llvm type from the actual evaluated initializer.
299        let llty = if nested {
300            self.type_i8()
301        } else {
302            let ty = instance.ty(self.tcx, self.typing_env());
303            trace!(?ty);
304            self.layout_of(ty).llvm_type(self)
305        };
306        self.get_static_inner(def_id, llty)
307    }
308
309    #[instrument(level = "debug", skip(self, llty))]
310    fn get_static_inner(&self, def_id: DefId, llty: &'ll Type) -> &'ll Value {
311        let instance = Instance::mono(self.tcx, def_id);
312        if let Some(&g) = self.instances.borrow().get(&instance) {
313            trace!("used cached value");
314            return g;
315        }
316
317        let defined_in_current_codegen_unit =
318            self.codegen_unit.items().contains_key(&MonoItem::Static(def_id));
319        assert!(
320            !defined_in_current_codegen_unit,
321            "consts::get_static() should always hit the cache for \
322                 statics defined in the same CGU, but did not for `{def_id:?}`"
323        );
324
325        let sym = self.tcx.symbol_name(instance).name;
326        let fn_attrs = self.tcx.codegen_fn_attrs(def_id);
327
328        debug!(?sym, ?fn_attrs);
329
330        let g = if def_id.is_local() && !self.tcx.is_foreign_item(def_id) {
331            if let Some(g) = self.get_declared_value(sym) {
332                if self.val_ty(g) != self.type_ptr() {
333                    span_bug!(self.tcx.def_span(def_id), "Conflicting types for static");
334                }
335            }
336
337            let g = self.declare_global(sym, llty);
338
339            if !self.tcx.is_reachable_non_generic(def_id) {
340                llvm::set_visibility(g, llvm::Visibility::Hidden);
341            }
342
343            g
344        } else {
345            check_and_apply_linkage(self, fn_attrs, llty, sym, def_id)
346        };
347
348        // Thread-local statics in some other crate need to *always* be linked
349        // against in a thread-local fashion, so we need to be sure to apply the
350        // thread-local attribute locally if it was present remotely. If we
351        // don't do this then linker errors can be generated where the linker
352        // complains that one object files has a thread local version of the
353        // symbol and another one doesn't.
354        if fn_attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
355            llvm::set_thread_local_mode(g, self.tls_model);
356        }
357
358        let dso_local = self.assume_dso_local(g, true);
359
360        if !def_id.is_local() {
361            let needs_dll_storage_attr = self.use_dll_storage_attrs
362                && !self.tcx.is_foreign_item(def_id)
363                // Local definitions can never be imported, so we must not apply
364                // the DLLImport annotation.
365                && !dso_local
366                // Linker plugin ThinLTO doesn't create the self-dllimport Rust uses for rlibs
367                // as the code generation happens out of process. Instead we assume static linkage
368                // and disallow dynamic linking when linker plugin based LTO is enabled.
369                // Regular in-process ThinLTO doesn't need this workaround.
370                && !self.tcx.sess.opts.cg.linker_plugin_lto.enabled();
371
372            // If this assertion triggers, there's something wrong with commandline
373            // argument validation.
374            assert!(
375                !(self.tcx.sess.opts.cg.linker_plugin_lto.enabled()
376                    && self.tcx.sess.target.is_like_windows
377                    && self.tcx.sess.opts.cg.prefer_dynamic)
378            );
379
380            if needs_dll_storage_attr {
381                // This item is external but not foreign, i.e., it originates from an external Rust
382                // crate. Since we don't know whether this crate will be linked dynamically or
383                // statically in the final application, we always mark such symbols as 'dllimport'.
384                // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs
385                // to make things work.
386                //
387                // However, in some scenarios we defer emission of statics to downstream
388                // crates, so there are cases where a static with an upstream DefId
389                // is actually present in the current crate. We can find out via the
390                // is_codegened_item query.
391                if !self.tcx.is_codegened_item(def_id) {
392                    llvm::set_dllimport_storage_class(g);
393                }
394            }
395        }
396
397        if self.use_dll_storage_attrs
398            && let Some(library) = self.tcx.native_library(def_id)
399            && library.kind.is_dllimport()
400        {
401            // For foreign (native) libs we know the exact storage type to use.
402            llvm::set_dllimport_storage_class(g);
403        }
404
405        self.instances.borrow_mut().insert(instance, g);
406        g
407    }
408
409    fn codegen_static_item(&self, def_id: DefId) {
410        unsafe {
411            assert!(
412                llvm::LLVMGetInitializer(
413                    self.instances.borrow().get(&Instance::mono(self.tcx, def_id)).unwrap()
414                )
415                .is_none()
416            );
417            let attrs = self.tcx.codegen_fn_attrs(def_id);
418
419            let Ok((v, alloc)) = codegen_static_initializer(self, def_id) else {
420                // Error has already been reported
421                return;
422            };
423            let alloc = alloc.inner();
424
425            let val_llty = self.val_ty(v);
426
427            let g = self.get_static_inner(def_id, val_llty);
428            let llty = llvm::LLVMGlobalGetValueType(g);
429
430            let g = if val_llty == llty {
431                g
432            } else {
433                // codegen_static_initializer creates the global value just from the
434                // `Allocation` data by generating one big struct value that is just
435                // all the bytes and pointers after each other. This will almost never
436                // match the type that the static was declared with. Unfortunately
437                // we can't just LLVMConstBitCast our way out of it because that has very
438                // specific rules on what can be cast. So instead of adding a new way to
439                // generate static initializers that match the static's type, we picked
440                // the easier option and retroactively change the type of the static item itself.
441                let name = llvm::get_value_name(g).to_vec();
442                llvm::set_value_name(g, b"");
443
444                let linkage = llvm::get_linkage(g);
445                let visibility = llvm::get_visibility(g);
446
447                let new_g = llvm::LLVMRustGetOrInsertGlobal(
448                    self.llmod,
449                    name.as_c_char_ptr(),
450                    name.len(),
451                    val_llty,
452                );
453
454                llvm::set_linkage(new_g, linkage);
455                llvm::set_visibility(new_g, visibility);
456
457                // The old global has had its name removed but is returned by
458                // get_static since it is in the instance cache. Provide an
459                // alternative lookup that points to the new global so that
460                // global_asm! can compute the correct mangled symbol name
461                // for the global.
462                self.renamed_statics.borrow_mut().insert(def_id, new_g);
463
464                // To avoid breaking any invariants, we leave around the old
465                // global for the moment; we'll replace all references to it
466                // with the new global later. (See base::codegen_backend.)
467                self.statics_to_rauw.borrow_mut().push((g, new_g));
468                new_g
469            };
470            set_global_alignment(self, g, alloc.align);
471            llvm::set_initializer(g, v);
472
473            self.assume_dso_local(g, true);
474
475            // Forward the allocation's mutability (picked by the const interner) to LLVM.
476            if alloc.mutability.is_not() {
477                llvm::LLVMSetGlobalConstant(g, llvm::True);
478            }
479
480            debuginfo::build_global_var_di_node(self, def_id, g);
481
482            if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
483                llvm::set_thread_local_mode(g, self.tls_model);
484            }
485
486            // Wasm statics with custom link sections get special treatment as they
487            // go into custom sections of the wasm executable. The exception to this
488            // is the `.init_array` section which are treated specially by the wasm linker.
489            if self.tcx.sess.target.is_like_wasm
490                && attrs
491                    .link_section
492                    .map(|link_section| !link_section.as_str().starts_with(".init_array"))
493                    .unwrap_or(true)
494            {
495                if let Some(section) = attrs.link_section {
496                    let section = llvm::LLVMMDStringInContext2(
497                        self.llcx,
498                        section.as_str().as_c_char_ptr(),
499                        section.as_str().len(),
500                    );
501                    assert!(alloc.provenance().ptrs().is_empty());
502
503                    // The `inspect` method is okay here because we checked for provenance, and
504                    // because we are doing this access to inspect the final interpreter state (not
505                    // as part of the interpreter execution).
506                    let bytes =
507                        alloc.inspect_with_uninit_and_ptr_outside_interpreter(0..alloc.len());
508                    let alloc =
509                        llvm::LLVMMDStringInContext2(self.llcx, bytes.as_c_char_ptr(), bytes.len());
510                    let data = [section, alloc];
511                    let meta = llvm::LLVMMDNodeInContext2(self.llcx, data.as_ptr(), data.len());
512                    let val = self.get_metadata_value(meta);
513                    llvm::LLVMAddNamedMetadataOperand(
514                        self.llmod,
515                        c"wasm.custom_sections".as_ptr(),
516                        val,
517                    );
518                }
519            } else {
520                base::set_link_section(g, attrs);
521            }
522
523            base::set_variable_sanitizer_attrs(g, attrs);
524
525            if attrs.flags.contains(CodegenFnAttrFlags::USED) {
526                // `USED` and `USED_LINKER` can't be used together.
527                assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER));
528
529                // The semantics of #[used] in Rust only require the symbol to make it into the
530                // object file. It is explicitly allowed for the linker to strip the symbol if it
531                // is dead, which means we are allowed to use `llvm.compiler.used` instead of
532                // `llvm.used` here.
533                //
534                // Additionally, https://reviews.llvm.org/D97448 in LLVM 13 started emitting unique
535                // sections with SHF_GNU_RETAIN flag for llvm.used symbols, which may trigger bugs
536                // in the handling of `.init_array` (the static constructor list) in versions of
537                // the gold linker (prior to the one released with binutils 2.36).
538                //
539                // That said, we only ever emit these when compiling for ELF targets, unless
540                // `#[used(compiler)]` is explicitly requested. This is to avoid similar breakage
541                // on other targets, in particular MachO targets have *their* static constructor
542                // lists broken if `llvm.compiler.used` is emitted rather than `llvm.used`. However,
543                // that check happens when assigning the `CodegenFnAttrFlags` in
544                // `rustc_hir_analysis`, so we don't need to take care of it here.
545                self.add_compiler_used_global(g);
546            }
547            if attrs.flags.contains(CodegenFnAttrFlags::USED_LINKER) {
548                // `USED` and `USED_LINKER` can't be used together.
549                assert!(!attrs.flags.contains(CodegenFnAttrFlags::USED));
550
551                self.add_used_global(g);
552            }
553        }
554    }
555}
556
557impl<'ll> StaticCodegenMethods for CodegenCx<'ll, '_> {
558    /// Get a pointer to a global variable.
559    ///
560    /// The pointer will always be in the default address space. If global variables default to a
561    /// different address space, an addrspacecast is inserted.
562    fn static_addr_of(&self, cv: &'ll Value, align: Align, kind: Option<&str>) -> &'ll Value {
563        let gv = self.static_addr_of_impl(cv, align, kind);
564        // static_addr_of_impl returns the bare global variable, which might not be in the default
565        // address space. Cast to the default address space if necessary.
566        self.const_pointercast(gv, self.type_ptr())
567    }
568
569    fn codegen_static(&self, def_id: DefId) {
570        self.codegen_static_item(def_id)
571    }
572
573    /// Add a global value to a list to be stored in the `llvm.used` variable, an array of ptr.
574    fn add_used_global(&self, global: &'ll Value) {
575        self.used_statics.borrow_mut().push(global);
576    }
577
578    /// Add a global value to a list to be stored in the `llvm.compiler.used` variable,
579    /// an array of ptr.
580    fn add_compiler_used_global(&self, global: &'ll Value) {
581        self.compiler_used_statics.borrow_mut().push(global);
582    }
583}