Skip to main content

rustc_codegen_ssa/
common.rs

1#![allow(non_camel_case_types)]
2
3use rustc_abi::{CanonAbi, X86Call};
4use rustc_attr_ir::PeImportNameType;
5use rustc_attr_ir::lang_items::LangItem;
6use rustc_crate_store::{DllCallingConvention, DllImport, DllImportSymbolType};
7use rustc_middle::mir::interpret::{GlobalAlloc, PointerArithmetic, Scalar};
8use rustc_middle::ty::layout::TyAndLayout;
9use rustc_middle::ty::{self, Instance, ScalarInt, Ty, TyCtxt};
10use rustc_span::{Span, bug, span_bug};
11use rustc_target::callconv::ArgAbi;
12use rustc_target::spec::{Arch, CfgAbi, Env, Os, Target};
13
14use crate::traits::*;
15
16#[derive(#[automatically_derived]impl ::core::marker::Copy for IntPredicate { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for IntPredicate {
}
#[automatically_derived]impl ::core::clone::Clone for IntPredicate {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for IntPredicate {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "IntEQ IntNE IntUGT IntUGE IntULT IntULE IntSGT IntSGE IntSLT IntSLE",
            match self {
                IntPredicate::IntEQ => 0usize,
                IntPredicate::IntNE => 6usize,
                IntPredicate::IntUGT => 12usize,
                IntPredicate::IntUGE => 19usize,
                IntPredicate::IntULT => 26usize,
                IntPredicate::IntULE => 33usize,
                IntPredicate::IntSGT => 40usize,
                IntPredicate::IntSGE => 47usize,
                IntPredicate::IntSLT => 54usize,
                IntPredicate::IntSLE => 61usize,
            })
    }
}Debug)]
17pub enum IntPredicate {
18    IntEQ,
19    IntNE,
20    IntUGT,
21    IntUGE,
22    IntULT,
23    IntULE,
24    IntSGT,
25    IntSGE,
26    IntSLT,
27    IntSLE,
28}
29
30#[derive(#[automatically_derived]impl ::core::marker::Copy for RealPredicate { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for RealPredicate {
}
#[automatically_derived]impl ::core::clone::Clone for RealPredicate {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for RealPredicate {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "RealPredicateFalse RealOEQ RealOGT RealOGE RealOLT RealOLE RealONE RealORD RealUNO RealUEQ RealUGT RealUGE RealULT RealULE RealUNE RealPredicateTrue",
            match self {
                RealPredicate::RealPredicateFalse => 0usize,
                RealPredicate::RealOEQ => 19usize,
                RealPredicate::RealOGT => 27usize,
                RealPredicate::RealOGE => 35usize,
                RealPredicate::RealOLT => 43usize,
                RealPredicate::RealOLE => 51usize,
                RealPredicate::RealONE => 59usize,
                RealPredicate::RealORD => 67usize,
                RealPredicate::RealUNO => 75usize,
                RealPredicate::RealUEQ => 83usize,
                RealPredicate::RealUGT => 91usize,
                RealPredicate::RealUGE => 99usize,
                RealPredicate::RealULT => 107usize,
                RealPredicate::RealULE => 115usize,
                RealPredicate::RealUNE => 123usize,
                RealPredicate::RealPredicateTrue => 131usize,
            })
    }
}Debug)]
31pub enum RealPredicate {
32    RealPredicateFalse,
33    RealOEQ,
34    RealOGT,
35    RealOGE,
36    RealOLT,
37    RealOLE,
38    RealONE,
39    RealORD,
40    RealUNO,
41    RealUEQ,
42    RealUGT,
43    RealUGE,
44    RealULT,
45    RealULE,
46    RealUNE,
47    RealPredicateTrue,
48}
49
50#[derive(#[automatically_derived]impl ::core::marker::Copy for AtomicRmwBinOp { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for AtomicRmwBinOp {
}
#[automatically_derived]impl ::core::clone::Clone for AtomicRmwBinOp {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    AtomicRmwBinOp {
}
#[automatically_derived]impl ::core::cmp::PartialEq for AtomicRmwBinOp {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
            ::core::intrinsics::discriminant_value(other)
    }
}PartialEq, #[automatically_derived]impl ::core::fmt::Debug for AtomicRmwBinOp {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_c_like_enum_write_str(f,
            "AtomicXchg AtomicAdd AtomicSub AtomicAnd AtomicNand AtomicOr AtomicXor AtomicMax AtomicMin AtomicUMax AtomicUMin",
            match self {
                AtomicRmwBinOp::AtomicXchg => 0usize,
                AtomicRmwBinOp::AtomicAdd => 11usize,
                AtomicRmwBinOp::AtomicSub => 21usize,
                AtomicRmwBinOp::AtomicAnd => 31usize,
                AtomicRmwBinOp::AtomicNand => 41usize,
                AtomicRmwBinOp::AtomicOr => 52usize,
                AtomicRmwBinOp::AtomicXor => 61usize,
                AtomicRmwBinOp::AtomicMax => 71usize,
                AtomicRmwBinOp::AtomicMin => 81usize,
                AtomicRmwBinOp::AtomicUMax => 91usize,
                AtomicRmwBinOp::AtomicUMin => 102usize,
            })
    }
}Debug)]
51pub enum AtomicRmwBinOp {
52    AtomicXchg,
53    AtomicAdd,
54    AtomicSub,
55    AtomicAnd,
56    AtomicNand,
57    AtomicOr,
58    AtomicXor,
59    AtomicMax,
60    AtomicMin,
61    AtomicUMax,
62    AtomicUMin,
63}
64
65#[derive(#[automatically_derived]impl ::core::marker::Copy for SynchronizationScope { }Copy, #[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
    for SynchronizationScope {
}
#[automatically_derived]impl ::core::clone::Clone for SynchronizationScope {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for SynchronizationScope {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                SynchronizationScope::SingleThread => "SingleThread",
                SynchronizationScope::CrossThread => "CrossThread",
            })
    }
}Debug)]
66pub enum SynchronizationScope {
67    SingleThread,
68    CrossThread,
69}
70
71// FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
72//            the StableHash trait. Normally DepGraph::with_task() calls are
73//            hidden behind queries, but CGU creation is a special case in two
74//            ways: (1) it's not a query and (2) CGU are output nodes, so their
75//            Fingerprints are not actually needed. It remains to be clarified
76//            how exactly this case will be handled in the red/green system but
77//            for now we content ourselves with providing a no-op StableHash
78//            implementation for CGUs.
79mod temp_stable_hash_impls {
80    use rustc_data_structures::stable_hash::{StableHash, StableHashCtxt, StableHasher};
81
82    use crate::ModuleCodegen;
83
84    impl<M> StableHash for ModuleCodegen<M> {
85        fn stable_hash<Hcx: StableHashCtxt>(&self, _: &mut Hcx, _: &mut StableHasher) {
86            // do nothing
87        }
88    }
89}
90
91pub(crate) fn build_langcall<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
92    bx: &Bx,
93    span: Span,
94    li: LangItem,
95) -> (Bx::FnAbiOfResult, Bx::Value, Instance<'tcx>) {
96    let tcx = bx.tcx();
97    let def_id = tcx.require_lang_item(li, span);
98    let instance = ty::Instance::mono(tcx, def_id);
99    (
100        bx.fn_abi_of_instance(instance, ty::List::empty()),
101        bx.get_fn_addr(instance, tcx.sess.pointer_authentication_functions()),
102        instance,
103    )
104}
105
106pub(crate) fn shift_mask_val<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
107    bx: &mut Bx,
108    llty: Bx::Type,
109    mask_llty: Bx::Type,
110    invert: bool,
111) -> Bx::Value {
112    if let Some(val) = bx.int_width(llty) {
113        // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
114        let val = val - 1;
115        if invert { bx.const_int(mask_llty, !val as i64) } else { bx.const_uint(mask_llty, val) }
116    } else if let Some(element) = bx.vector_element_type(llty) {
117        let (mask_elem, mask_len) =
118            bx.vector_element_type_and_length(llty).expect("mask was not a vector");
119        let mask = shift_mask_val(bx, element, mask_elem, invert);
120        bx.vector_splat(mask_len, mask)
121    } else {
122        ::rustc_span::macros::bug_impl(None,
    format_args!("shift_mask_val: expected Integer or Vector, found {0:?}",
        llty), Location::caller())bug!("shift_mask_val: expected Integer or Vector, found {llty:?}")
123    }
124}
125
126pub fn asm_const_to_str<'tcx>(
127    tcx: TyCtxt<'tcx>,
128    sp: Span,
129    scalar: ScalarInt,
130    ty_and_layout: TyAndLayout<'tcx>,
131) -> String {
132    let value = scalar.to_bits(ty_and_layout.size);
133    match ty_and_layout.ty.kind() {
134        ty::Uint(_) => value.to_string(),
135        ty::Int(int_ty) => match int_ty.normalize(tcx.sess.target.pointer_width) {
136            ty::IntTy::I8 => (value as i8).to_string(),
137            ty::IntTy::I16 => (value as i16).to_string(),
138            ty::IntTy::I32 => (value as i32).to_string(),
139            ty::IntTy::I64 => (value as i64).to_string(),
140            ty::IntTy::I128 => (value as i128).to_string(),
141            ty::IntTy::Isize => ::core::panicking::unreachable_default_msg()unreachable!(),
142        },
143        // For pointers without provenance, just print the unsigned value
144        ty::Ref(..) | ty::RawPtr(..) | ty::FnPtr(..) => value.to_string(),
145        _ => ::rustc_span::macros::bug_impl(Some(sp),
    format_args!("asm const has bad type {0}", ty_and_layout.ty),
    Location::caller())span_bug!(sp, "asm const has bad type {}", ty_and_layout.ty),
146    }
147}
148
149/// "Clean" a const pointer by removing values where the resulting ASM will not be
150/// `<symbol> + <offset>`.
151///
152/// These values are converted to `ScalarInt`.
153pub fn asm_const_ptr_clean<'tcx>(tcx: TyCtxt<'tcx>, scalar: Scalar) -> Scalar {
154    let Scalar::Ptr(ptr, _) = scalar else {
155        return scalar;
156    };
157    let (prov, offset) = ptr.prov_and_relative_offset();
158    let global_alloc = tcx.global_alloc(prov.alloc_id());
159    match global_alloc {
160        GlobalAlloc::TypeId { .. } => {
161            // `TypeId` provenances are not a thing in codegen. Just erase and replace with scalar offset.
162            Scalar::from_u64(offset.bytes())
163        }
164        GlobalAlloc::Memory(alloc) if alloc.inner().len() == 0 => {
165            // ZST const allocations don't actually get global defined when lowered.
166            // Turn them into integer without provenances now.
167            let val = alloc.inner().align.bytes().wrapping_add(offset.bytes());
168            Scalar::from_target_usize(tcx.truncate_to_target_usize(val), &tcx)
169        }
170        // Other types of `GlobalAlloc` are fine.
171        _ => scalar,
172    }
173}
174
175pub fn is_using_dlltool(target: &Target) -> bool {
176    target.os == Os::Windows && target.env == Env::Gnu && target.cfg_abi == CfgAbi::Unspecified
177}
178
179/// Computes the total argument size used for Windows calling-convention
180/// symbol decoration. Each argument is rounded up to the pointer width.
181fn windows_abi_argument_byte_sum<'tcx>(args: &[ArgAbi<'tcx, Ty<'tcx>>], target: &Target) -> u64 {
182    let pointer_bytes = target.pointer_width as u64 / 8;
183
184    args.iter().map(|arg| arg.layout.size.bytes().next_multiple_of(pointer_bytes)).sum()
185}
186
187/// Computes the linker-visible decorated symbol name for supported Windows
188/// calling conventions using the original `FnAbi` argument layouts.
189/// Vectorcall is also decorated on non-Windows targets.
190///
191/// The byte count is computed before backend-specific argument lowering,
192/// which may replace indirectly passed arguments with pointers.
193///
194/// For example, on 32-bit Windows, `extern "fastcall" fn foo(i32, i32)`
195/// is decorated as `@foo@8`. On 64-bit targets,
196/// `extern "vectorcall" fn foo(i32)` is decorated as `foo@@8`.
197///
198/// Returns `None` if no decoration is required or if the name begins with
199/// `\x01` or `?`, indicating that it must not be decorated further.
200///
201/// This function does not add LLVM's `\x01` escape prefix. Backend-specific
202/// handling of that marker is the responsibility of the caller.
203pub fn windows_calling_convention_name<'tcx>(
204    target: &Target,
205    conv: CanonAbi,
206    name: &str,
207    args: &[ArgAbi<'tcx, Ty<'tcx>>],
208) -> Option<String> {
209    if !target.is_like_windows && conv != CanonAbi::X86(X86Call::Vectorcall) {
210        return None;
211    }
212
213    if name.starts_with('\x01') || name.starts_with('?') {
214        return None;
215    }
216
217    let (prefix, suffix) = match (&target.arch, conv) {
218        (Arch::X86, CanonAbi::X86(X86Call::Fastcall)) => ("@", "@"),
219        (Arch::X86, CanonAbi::X86(X86Call::Stdcall)) => ("_", "@"),
220        (Arch::X86 | Arch::X86_64, CanonAbi::X86(X86Call::Vectorcall)) => ("", "@@"),
221        _ => return None,
222    };
223
224    let args_in_bytes = windows_abi_argument_byte_sum(args, target);
225    Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}{3}", prefix, name,
                suffix, args_in_bytes))
    })format!("{prefix}{name}{suffix}{args_in_bytes}"))
226}
227
228pub fn i686_decorated_name(
229    dll_import: &DllImport,
230    mingw: bool,
231    disable_name_mangling: bool,
232    force_fully_decorated: bool,
233) -> String {
234    let name = dll_import.name.as_str();
235
236    let (add_prefix, add_suffix) = match (force_fully_decorated, dll_import.import_name_type) {
237        // No prefix is a bit weird, in that LLVM/ar_archive_writer won't emit it, so we will
238        // ignore `force_fully_decorated` and always partially decorate it.
239        (_, Some(PeImportNameType::NoPrefix)) => (false, true),
240        (false, Some(PeImportNameType::Undecorated)) => (false, false),
241        _ => (true, true),
242    };
243
244    // Worst case: +1 for disable name mangling, +1 for prefix, +4 for suffix (@@__).
245    let mut decorated_name = String::with_capacity(name.len() + 6);
246
247    if disable_name_mangling {
248        // LLVM uses a binary 1 ('\x01') prefix to a name to indicate that mangling needs to be
249        // disabled.
250        decorated_name.push('\x01');
251    }
252
253    let prefix = if add_prefix && dll_import.symbol_type == DllImportSymbolType::Function {
254        match dll_import.calling_convention {
255            DllCallingConvention::C | DllCallingConvention::Vectorcall(_) => None,
256            DllCallingConvention::Stdcall(_) => (!mingw
257                || dll_import.import_name_type == Some(PeImportNameType::Decorated))
258            .then_some('_'),
259            DllCallingConvention::Fastcall(_) => Some('@'),
260        }
261    } else if dll_import.symbol_type != DllImportSymbolType::Function && !mingw {
262        // For static variables, prefix with '_' on MSVC.
263        Some('_')
264    } else {
265        None
266    };
267    if let Some(prefix) = prefix {
268        decorated_name.push(prefix);
269    }
270
271    decorated_name.push_str(name);
272
273    if add_suffix && dll_import.symbol_type == DllImportSymbolType::Function {
274        use std::fmt::Write;
275
276        match dll_import.calling_convention {
277            DllCallingConvention::C => {}
278            DllCallingConvention::Stdcall(arg_list_size)
279            | DllCallingConvention::Fastcall(arg_list_size) => {
280                (&mut decorated_name).write_fmt(format_args!("@{0}", arg_list_size))write!(&mut decorated_name, "@{arg_list_size}").unwrap();
281            }
282            DllCallingConvention::Vectorcall(arg_list_size) => {
283                (&mut decorated_name).write_fmt(format_args!("@@{0}", arg_list_size))write!(&mut decorated_name, "@@{arg_list_size}").unwrap();
284            }
285        }
286    }
287
288    decorated_name
289}