Skip to main content

rustc_codegen_llvm/
common.rs

1//! Code that is useful in various codegen modules.
2
3use std::borrow::Borrow;
4
5use libc::{c_char, c_uint};
6use rustc_abi::Primitive::Pointer;
7use rustc_abi::{self as abi, HasDataLayout as _};
8use rustc_ast::Mutability;
9use rustc_codegen_ssa::common::TypeKind;
10use rustc_codegen_ssa::traits::*;
11use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
12use rustc_hashes::Hash128;
13use rustc_hir::def_id::DefId;
14use rustc_middle::bug;
15use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc, PointerArithmetic, Scalar};
16use rustc_middle::ty::TyCtxt;
17use rustc_session::cstore::DllImport;
18use tracing::debug;
19
20use crate::consts::const_alloc_to_llvm;
21pub(crate) use crate::context::CodegenCx;
22use crate::context::{GenericCx, SCx};
23use crate::llvm::{self, BasicBlock, ConstantInt, FALSE, Metadata, TRUE, ToLlvmBool, Type, Value};
24
25/*
26* A note on nomenclature of linking: "extern", "foreign", and "upcall".
27*
28* An "extern" is an LLVM symbol we wind up emitting an undefined external
29* reference to. This means "we don't have the thing in this compilation unit,
30* please make sure you link it in at runtime". This could be a reference to
31* C code found in a C library, or rust code found in a rust crate.
32*
33* Most "externs" are implicitly declared (automatically) as a result of a
34* user declaring an extern _module_ dependency; this causes the rust driver
35* to locate an extern crate, scan its compilation metadata, and emit extern
36* declarations for any symbols used by the declaring crate.
37*
38* A "foreign" is an extern that references C (or other non-rust ABI) code.
39* There is no metadata to scan for extern references so in these cases either
40* a header-digester like bindgen, or manual function prototypes, have to
41* serve as declarators. So these are usually given explicitly as prototype
42* declarations, in rust code, with ABI attributes on them noting which ABI to
43* link via.
44*
45* An "upcall" is a foreign call generated by the compiler (not corresponding
46* to any user-written call in the code) into the runtime library, to perform
47* some helper task such as bringing a task to life, allocating memory, etc.
48*
49*/
50
51/// A structure representing an active landing pad for the duration of a basic
52/// block.
53///
54/// Each `Block` may contain an instance of this, indicating whether the block
55/// is part of a landing pad or not. This is used to make decision about whether
56/// to emit `invoke` instructions (e.g., in a landing pad we don't continue to
57/// use `invoke`) and also about various function call metadata.
58///
59/// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
60/// just a bunch of `None` instances (not too interesting), but for MSVC
61/// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
62/// When inside of a landing pad, each function call in LLVM IR needs to be
63/// annotated with which landing pad it's a part of. This is accomplished via
64/// the `OperandBundleDef` value created for MSVC landing pads.
65pub(crate) struct Funclet<'ll> {
66    cleanuppad: &'ll Value,
67    operand: llvm::OperandBundleBox<'ll>,
68}
69
70impl<'ll> Funclet<'ll> {
71    pub(crate) fn new(cleanuppad: &'ll Value) -> Self {
72        Funclet { cleanuppad, operand: llvm::OperandBundleBox::new("funclet", &[cleanuppad]) }
73    }
74
75    pub(crate) fn cleanuppad(&self) -> &'ll Value {
76        self.cleanuppad
77    }
78
79    pub(crate) fn bundle(&self) -> &llvm::OperandBundle<'ll> {
80        self.operand.as_ref()
81    }
82}
83
84impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericCx<'ll, CX> {
85    type Value = &'ll Value;
86    type Metadata = &'ll Metadata;
87    // FIXME(eddyb) replace this with a `Function` "subclass" of `Value`.
88    type Function = &'ll Value;
89
90    type BasicBlock = &'ll BasicBlock;
91    type Type = &'ll Type;
92    type Funclet = Funclet<'ll>;
93
94    type DIScope = &'ll llvm::debuginfo::DIScope;
95    type DILocation = &'ll llvm::debuginfo::DILocation;
96    type DIVariable = &'ll llvm::debuginfo::DIVariable;
97}
98
99impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
100    pub(crate) fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
101        let len = u64::try_from(elts.len()).expect("LLVMConstArray2 elements len overflow");
102        unsafe { llvm::LLVMConstArray2(ty, elts.as_ptr(), len) }
103    }
104
105    pub(crate) fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
106        bytes_in_context(self.llcx(), bytes)
107    }
108
109    pub(crate) fn null_terminate_const_bytes(&self, bytes: &[u8]) -> &'ll Value {
110        null_terminate_bytes_in_context(self.llcx(), bytes)
111    }
112
113    pub(crate) fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
114        unsafe {
115            let idx = c_uint::try_from(idx).expect("LLVMGetAggregateElement index overflow");
116            let r = llvm::LLVMGetAggregateElement(v, idx).unwrap();
117
118            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_llvm/src/common.rs:118",
                        "rustc_codegen_llvm::common", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/common.rs"),
                        ::tracing_core::__macro_support::Option::Some(118u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::common"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("const_get_elt(v={0:?}, idx={1}, r={2:?})",
                                                    v, idx, r) as &dyn Value))])
            });
    } else { ; }
};debug!("const_get_elt(v={:?}, idx={}, r={:?})", v, idx, r);
119
120            r
121        }
122    }
123
124    pub(crate) fn const_null(&self, t: &'ll Type) -> &'ll Value {
125        unsafe { llvm::LLVMConstNull(t) }
126    }
127
128    pub(crate) fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
129        struct_in_context(self.llcx(), elts, packed)
130    }
131}
132
133impl<'ll, 'tcx> ConstCodegenMethods for CodegenCx<'ll, 'tcx> {
134    fn const_null(&self, t: &'ll Type) -> &'ll Value {
135        unsafe { llvm::LLVMConstNull(t) }
136    }
137
138    fn const_undef(&self, t: &'ll Type) -> &'ll Value {
139        unsafe { llvm::LLVMGetUndef(t) }
140    }
141
142    fn const_poison(&self, t: &'ll Type) -> &'ll Value {
143        unsafe { llvm::LLVMGetPoison(t) }
144    }
145
146    fn const_bool(&self, val: bool) -> &'ll Value {
147        self.const_uint(self.type_i1(), val as u64)
148    }
149
150    fn const_i8(&self, i: i8) -> &'ll Value {
151        self.const_int(self.type_i8(), i as i64)
152    }
153
154    fn const_i16(&self, i: i16) -> &'ll Value {
155        self.const_int(self.type_i16(), i as i64)
156    }
157
158    fn const_i32(&self, i: i32) -> &'ll Value {
159        self.const_int(self.type_i32(), i as i64)
160    }
161
162    fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
163        if true {
    if !(self.type_kind(t) == TypeKind::Integer) {
        {
            ::core::panicking::panic_fmt(format_args!("only allows integer types in const_int"));
        }
    };
};debug_assert!(
164            self.type_kind(t) == TypeKind::Integer,
165            "only allows integer types in const_int"
166        );
167        unsafe { llvm::LLVMConstInt(t, i as u64, TRUE) }
168    }
169
170    fn const_u8(&self, i: u8) -> &'ll Value {
171        self.const_uint(self.type_i8(), i as u64)
172    }
173
174    fn const_u32(&self, i: u32) -> &'ll Value {
175        self.const_uint(self.type_i32(), i as u64)
176    }
177
178    fn const_u64(&self, i: u64) -> &'ll Value {
179        self.const_uint(self.type_i64(), i)
180    }
181
182    fn const_u128(&self, i: u128) -> &'ll Value {
183        self.const_uint_big(self.type_i128(), i)
184    }
185
186    fn const_usize(&self, i: u64) -> &'ll Value {
187        let bit_size = self.data_layout().pointer_size().bits();
188        if bit_size < 64 {
189            // make sure it doesn't overflow
190            if !(i < (1 << bit_size)) {
    ::core::panicking::panic("assertion failed: i < (1 << bit_size)")
};assert!(i < (1 << bit_size));
191        }
192
193        self.const_uint(self.isize_ty, i)
194    }
195
196    fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
197        if true {
    if !(self.type_kind(t) == TypeKind::Integer) {
        {
            ::core::panicking::panic_fmt(format_args!("only allows integer types in const_uint"));
        }
    };
};debug_assert!(
198            self.type_kind(t) == TypeKind::Integer,
199            "only allows integer types in const_uint"
200        );
201        unsafe { llvm::LLVMConstInt(t, i, FALSE) }
202    }
203
204    fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
205        if true {
    if !(self.type_kind(t) == TypeKind::Integer) {
        {
            ::core::panicking::panic_fmt(format_args!("only allows integer types in const_uint_big"));
        }
    };
};debug_assert!(
206            self.type_kind(t) == TypeKind::Integer,
207            "only allows integer types in const_uint_big"
208        );
209        unsafe {
210            let words = [u as u64, (u >> 64) as u64];
211            llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
212        }
213    }
214
215    fn const_real(&self, t: &'ll Type, val: f64) -> &'ll Value {
216        unsafe { llvm::LLVMConstReal(t, val) }
217    }
218
219    fn const_str(&self, s: &str) -> (&'ll Value, &'ll Value) {
220        let mut const_str_cache = self.const_str_cache.borrow_mut();
221        let str_global = const_str_cache.get(s).copied().unwrap_or_else(|| {
222            let sc = self.const_bytes(s.as_bytes());
223            let sym = self.generate_local_symbol_name("str");
224            let g = self.define_global(&sym, self.val_ty(sc)).unwrap_or_else(|| {
225                ::rustc_middle::util::bug::bug_fmt(format_args!("symbol `{0}` is already defined",
        sym));bug!("symbol `{}` is already defined", sym);
226            });
227            llvm::set_initializer(g, sc);
228
229            llvm::set_global_constant(g, true);
230            llvm::set_unnamed_address(g, llvm::UnnamedAddr::Global);
231
232            llvm::set_linkage(g, llvm::Linkage::InternalLinkage);
233            // Cast to default address space if globals are in a different addrspace
234            let g = self.const_pointercast(g, self.type_ptr());
235            const_str_cache.insert(s.to_owned(), g);
236            g
237        });
238        let len = s.len();
239        (str_global, self.const_usize(len as u64))
240    }
241
242    fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
243        struct_in_context(self.llcx, elts, packed)
244    }
245
246    fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
247        let len = c_uint::try_from(elts.len()).expect("LLVMConstVector elements len overflow");
248        unsafe { llvm::LLVMConstVector(elts.as_ptr(), len) }
249    }
250
251    fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
252        try_as_const_integral(v).and_then(|v| unsafe {
253            let mut i = 0u64;
254            let success = llvm::LLVMRustConstIntGetZExtValue(v, &mut i);
255            success.then_some(i)
256        })
257    }
258
259    fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
260        try_as_const_integral(v).and_then(|v| unsafe {
261            let (mut lo, mut hi) = (0u64, 0u64);
262            let success = llvm::LLVMRustConstInt128Get(v, sign_ext, &mut hi, &mut lo);
263            success.then_some(hi_lo_to_u128(lo, hi))
264        })
265    }
266
267    fn scalar_to_backend(&self, cv: Scalar, layout: abi::Scalar, llty: &'ll Type) -> &'ll Value {
268        let bitsize = if layout.is_bool() { 1 } else { layout.size(self).bits() };
269        match cv {
270            Scalar::Int(int) => {
271                let data = int.to_bits(layout.size(self));
272                let llval = self.const_uint_big(self.type_ix(bitsize), data);
273                if #[allow(non_exhaustive_omitted_patterns)] match layout.primitive() {
    Pointer(_) => true,
    _ => false,
}matches!(layout.primitive(), Pointer(_)) {
274                    unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
275                } else {
276                    self.const_bitcast(llval, llty)
277                }
278            }
279            Scalar::Ptr(ptr, _size) => {
280                let (prov, offset) = ptr.prov_and_relative_offset();
281                let global_alloc = self.tcx.global_alloc(prov.alloc_id());
282                let base_addr = match global_alloc {
283                    GlobalAlloc::Memory(alloc) => {
284                        // For ZSTs directly codegen an aligned pointer.
285                        // This avoids generating a zero-sized constant value and actually needing a
286                        // real address at runtime.
287                        if alloc.inner().len() == 0 {
288                            let val = alloc.inner().align.bytes().wrapping_add(offset.bytes());
289                            let llval = self.const_usize(self.tcx.truncate_to_target_usize(val));
290                            return if #[allow(non_exhaustive_omitted_patterns)] match layout.primitive() {
    Pointer(_) => true,
    _ => false,
}matches!(layout.primitive(), Pointer(_)) {
291                                unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
292                            } else {
293                                self.const_bitcast(llval, llty)
294                            };
295                        } else {
296                            let init =
297                                const_alloc_to_llvm(self, alloc.inner(), /*static*/ false);
298                            let alloc = alloc.inner();
299                            let value = match alloc.mutability {
300                                Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
301                                _ => self.static_addr_of_impl(init, alloc.align, None),
302                            };
303                            if !self.sess().fewer_names() && llvm::get_value_name(value).is_empty()
304                            {
305                                let hash = self.tcx.with_stable_hashing_context(|mut hcx| {
306                                    let mut hasher = StableHasher::new();
307                                    alloc.hash_stable(&mut hcx, &mut hasher);
308                                    hasher.finish::<Hash128>()
309                                });
310                                llvm::set_value_name(
311                                    value,
312                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("alloc_{0:032x}", hash))
    })format!("alloc_{hash:032x}").as_bytes(),
313                                );
314                            }
315                            value
316                        }
317                    }
318                    GlobalAlloc::Function { instance, .. } => self.get_fn_addr(instance),
319                    GlobalAlloc::VTable(ty, dyn_ty) => {
320                        let alloc = self
321                            .tcx
322                            .global_alloc(self.tcx.vtable_allocation((
323                                ty,
324                                dyn_ty.principal().map(|principal| {
325                                    self.tcx.instantiate_bound_regions_with_erased(principal)
326                                }),
327                            )))
328                            .unwrap_memory();
329                        let init = const_alloc_to_llvm(self, alloc.inner(), /*static*/ false);
330                        self.static_addr_of_impl(init, alloc.inner().align, None)
331                    }
332                    GlobalAlloc::Static(def_id) => {
333                        if !self.tcx.is_static(def_id) {
    ::core::panicking::panic("assertion failed: self.tcx.is_static(def_id)")
};assert!(self.tcx.is_static(def_id));
334                        if !!self.tcx.is_thread_local_static(def_id) {
    ::core::panicking::panic("assertion failed: !self.tcx.is_thread_local_static(def_id)")
};assert!(!self.tcx.is_thread_local_static(def_id));
335                        self.get_static(def_id)
336                    }
337                    GlobalAlloc::TypeId { .. } => {
338                        // Drop the provenance, the offset contains the bytes of the hash
339                        let llval = self.const_usize(offset.bytes());
340                        return unsafe { llvm::LLVMConstIntToPtr(llval, llty) };
341                    }
342                };
343                let base_addr_space = global_alloc.address_space(self);
344                let llval = unsafe {
345                    llvm::LLVMConstInBoundsGEP2(
346                        self.type_i8(),
347                        // Cast to the required address space if necessary
348                        self.const_pointercast(base_addr, self.type_ptr_ext(base_addr_space)),
349                        &self.const_usize(offset.bytes()),
350                        1,
351                    )
352                };
353                if !#[allow(non_exhaustive_omitted_patterns)] match layout.primitive() {
    Pointer(_) => true,
    _ => false,
}matches!(layout.primitive(), Pointer(_)) {
354                    unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
355                } else {
356                    self.const_bitcast(llval, llty)
357                }
358            }
359        }
360    }
361
362    fn const_data_from_alloc(&self, alloc: ConstAllocation<'_>) -> Self::Value {
363        const_alloc_to_llvm(self, alloc.inner(), /*static*/ false)
364    }
365
366    fn const_ptr_byte_offset(&self, base_addr: Self::Value, offset: abi::Size) -> Self::Value {
367        unsafe {
368            llvm::LLVMConstInBoundsGEP2(
369                self.type_i8(),
370                base_addr,
371                &self.const_usize(offset.bytes()),
372                1,
373            )
374        }
375    }
376}
377
378/// Get the [LLVM type][Type] of a [`Value`].
379pub(crate) fn val_ty(v: &Value) -> &Type {
380    unsafe { llvm::LLVMTypeOf(v) }
381}
382
383pub(crate) fn bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
384    unsafe {
385        let ptr = bytes.as_ptr() as *const c_char;
386        llvm::LLVMConstStringInContext2(llcx, ptr, bytes.len(), TRUE)
387    }
388}
389
390pub(crate) fn null_terminate_bytes_in_context<'ll>(
391    llcx: &'ll llvm::Context,
392    bytes: &[u8],
393) -> &'ll Value {
394    unsafe {
395        let ptr = bytes.as_ptr() as *const c_char;
396        llvm::LLVMConstStringInContext2(llcx, ptr, bytes.len(), FALSE)
397    }
398}
399
400pub(crate) fn named_struct<'ll>(ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
401    let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
402    unsafe { llvm::LLVMConstNamedStruct(ty, elts.as_ptr(), len) }
403}
404
405fn struct_in_context<'ll>(
406    llcx: &'ll llvm::Context,
407    elts: &[&'ll Value],
408    packed: bool,
409) -> &'ll Value {
410    let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
411    unsafe { llvm::LLVMConstStructInContext(llcx, elts.as_ptr(), len, packed.to_llvm_bool()) }
412}
413
414#[inline]
415fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
416    ((hi as u128) << 64) | (lo as u128)
417}
418
419fn try_as_const_integral(v: &Value) -> Option<&ConstantInt> {
420    unsafe { llvm::LLVMIsAConstantInt(v) }
421}
422
423pub(crate) fn get_dllimport<'tcx>(
424    tcx: TyCtxt<'tcx>,
425    id: DefId,
426    name: &str,
427) -> Option<&'tcx DllImport> {
428    tcx.native_library(id)
429        .and_then(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name))
430}
431
432/// Extension trait for explicit casts to `*const c_char`.
433pub(crate) trait AsCCharPtr {
434    /// Equivalent to `self.as_ptr().cast()`, but only casts to `*const c_char`.
435    fn as_c_char_ptr(&self) -> *const c_char;
436}
437
438impl AsCCharPtr for str {
439    fn as_c_char_ptr(&self) -> *const c_char {
440        self.as_ptr().cast()
441    }
442}
443
444impl AsCCharPtr for [u8] {
445    fn as_c_char_ptr(&self) -> *const c_char {
446        self.as_ptr().cast()
447    }
448}