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