Skip to main content

rustc_codegen_ssa/
base.rs

1use std::collections::BTreeSet;
2use std::sync::Arc;
3use std::time::{Duration, Instant};
4use std::{cmp, iter};
5
6use itertools::Itertools;
7use rustc_abi::FIRST_VARIANT;
8use rustc_ast::expand::allocator::{
9    ALLOC_ERROR_HANDLER, ALLOCATOR_METHODS, AllocatorKind, AllocatorMethod, AllocatorMethodInput,
10    AllocatorTy,
11};
12use rustc_attr_ir::lang_items::LangItem;
13use rustc_attr_ir::target::Target;
14use rustc_attr_ir::{DebuggerVisualizerType, EiiDecl, EiiImpl, find_attr};
15use rustc_crate_store::CrateSourceFlags;
16use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
17use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
18use rustc_data_structures::sync::{IntoDynSyncSend, par_map};
19use rustc_data_structures::unord::UnordMap;
20use rustc_hir as hir;
21use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
22use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
23use rustc_middle::middle::dependency_format::{Dependencies, Linkage};
24use rustc_middle::middle::exported_symbols::{self, SymbolExportKind};
25use rustc_middle::middle::lang_items;
26use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, ErrorHandled, Scalar};
27use rustc_middle::mir::{BinOp, ConstValue};
28use rustc_middle::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem, MonoItemPartitions};
29use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
30use rustc_middle::ty::{self, Instance, PatternKind, Ty, TyCtxt, UintTy, Unnormalized};
31use rustc_session::config::{self, EntryFnType, JobsMode};
32use rustc_span::{DUMMY_SP, Symbol, bug, span_bug};
33use rustc_structures::CrateType;
34use rustc_symbol_mangling::mangle_internal_symbol;
35use rustc_target::spec::{Arch, Os, Target as TargetSpec};
36use rustc_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt};
37use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt};
38use tracing::{debug, info};
39
40use crate::assert_module_sources::CguReuse;
41use crate::back::link::are_upstream_rust_objects_already_included;
42use crate::back::write::{
43    ComputedLtoType, ModuleConfig, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen,
44    submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm,
45};
46use crate::common::{self, IntPredicate, RealPredicate};
47use crate::meth::VirtualIndex;
48use crate::mir::operand::OperandValue;
49use crate::mir::place::PlaceRef;
50use crate::traits::*;
51use crate::{
52    CachedModuleCodegen, CodegenLintLevelSpecs, CrateInfo, EiiLinkageImplInfo, EiiLinkageInfo,
53    ModuleCodegen, ModuleKind, diagnostics, meth, mir,
54};
55
56pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
57    match (op, signed) {
58        (BinOp::Eq, _) => IntPredicate::IntEQ,
59        (BinOp::Ne, _) => IntPredicate::IntNE,
60        (BinOp::Lt, true) => IntPredicate::IntSLT,
61        (BinOp::Lt, false) => IntPredicate::IntULT,
62        (BinOp::Le, true) => IntPredicate::IntSLE,
63        (BinOp::Le, false) => IntPredicate::IntULE,
64        (BinOp::Gt, true) => IntPredicate::IntSGT,
65        (BinOp::Gt, false) => IntPredicate::IntUGT,
66        (BinOp::Ge, true) => IntPredicate::IntSGE,
67        (BinOp::Ge, false) => IntPredicate::IntUGE,
68        op => ::rustc_span::macros::bug_impl(None,
    format_args!("bin_op_to_icmp_predicate: expected comparison operator, found {0:?}",
        op), Location::caller())bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),
69    }
70}
71
72pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
73    match op {
74        BinOp::Eq => RealPredicate::RealOEQ,
75        BinOp::Ne => RealPredicate::RealUNE,
76        BinOp::Lt => RealPredicate::RealOLT,
77        BinOp::Le => RealPredicate::RealOLE,
78        BinOp::Gt => RealPredicate::RealOGT,
79        BinOp::Ge => RealPredicate::RealOGE,
80        op => ::rustc_span::macros::bug_impl(None,
    format_args!("bin_op_to_fcmp_predicate: expected comparison operator, found {0:?}",
        op), Location::caller())bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),
81    }
82}
83
84pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
85    bx: &mut Bx,
86    lhs: Bx::Value,
87    rhs: Bx::Value,
88    t: Ty<'tcx>,
89    ret_ty: Bx::Type,
90    op: BinOp,
91) -> Bx::Value {
92    let signed = match t.kind() {
93        ty::Float(_) => {
94            let cmp = bin_op_to_fcmp_predicate(op);
95            let cmp = bx.fcmp(cmp, lhs, rhs);
96            return bx.sext(cmp, ret_ty);
97        }
98        ty::Uint(_) => false,
99        ty::Int(_) => true,
100        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("compare_simd_types: invalid SIMD type"), Location::caller())bug!("compare_simd_types: invalid SIMD type"),
101    };
102
103    let cmp = bin_op_to_icmp_predicate(op, signed);
104    let cmp = bx.icmp(cmp, lhs, rhs);
105    // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
106    // to get the correctly sized type. This will compile to a single instruction
107    // once the IR is converted to assembly if the SIMD instruction is supported
108    // by the target architecture.
109    bx.sext(cmp, ret_ty)
110}
111
112/// Codegen takes advantage of the additional assumption, where if the
113/// principal trait def id of what's being casted doesn't change,
114/// then we don't need to adjust the vtable at all. This
115/// corresponds to the fact that `dyn Tr<A>: Unsize<dyn Tr<B>>`
116/// requires that `A = B`; we don't allow *upcasting* objects
117/// between the same trait with different args. If we, for
118/// some reason, were to relax the `Unsize` trait, it could become
119/// unsound, so let's validate here that the trait refs are subtypes.
120pub fn validate_trivial_unsize<'tcx>(
121    tcx: TyCtxt<'tcx>,
122    source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
123    target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
124) -> bool {
125    match (source_data.principal(), target_data.principal()) {
126        (Some(hr_source_principal), Some(hr_target_principal)) => {
127            let (infcx, param_env) =
128                tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
129            let universe = infcx.universe();
130            let ocx = ObligationCtxt::new(&infcx);
131            infcx.enter_forall(hr_target_principal, |target_principal| {
132                let source_principal = infcx.instantiate_binder_with_fresh_vars(
133                    DUMMY_SP,
134                    BoundRegionConversionTime::HigherRankedType,
135                    hr_source_principal,
136                );
137                let Ok(()) = ocx.eq(
138                    &ObligationCause::dummy(),
139                    param_env,
140                    target_principal,
141                    source_principal,
142                ) else {
143                    return false;
144                };
145                if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
146                    return false;
147                }
148                infcx.leak_check(universe, None).is_ok()
149            })
150        }
151        (_, None) => true,
152        _ => false,
153    }
154}
155
156/// Retrieves the information we are losing (making dynamic) in an unsizing
157/// adjustment.
158///
159/// The `old_info` argument is a bit odd. It is intended for use in an upcast,
160/// where the new vtable for an object will be derived from the old one.
161fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
162    bx: &mut Bx,
163    source: Ty<'tcx>,
164    target: Ty<'tcx>,
165    old_info: Option<Bx::Value>,
166) -> Bx::Value {
167    let cx = bx.cx();
168    let (source, target) =
169        cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
170    match (source.kind(), target.kind()) {
171        (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
172            len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
173        ),
174        (&ty::Dynamic(data_a, _), &ty::Dynamic(data_b, _)) => {
175            let old_info =
176                old_info.expect("unsized_info: missing old info for trait upcasting coercion");
177            let b_principal_def_id = data_b.principal_def_id();
178            if data_a.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {
179                // Codegen takes advantage of the additional assumption, where if the
180                // principal trait def id of what's being casted doesn't change,
181                // then we don't need to adjust the vtable at all. This
182                // corresponds to the fact that `dyn Tr<A>: Unsize<dyn Tr<B>>`
183                // requires that `A = B`; we don't allow *upcasting* objects
184                // between the same trait with different args. If we, for
185                // some reason, were to relax the `Unsize` trait, it could become
186                // unsound, so let's assert here that the trait refs are *equal*.
187                if true {
    if !validate_trivial_unsize(cx.tcx(), data_a, data_b) {
        {
            ::core::panicking::panic_fmt(format_args!("NOP unsize vtable changed principal trait ref: {0} -> {1}",
                    data_a, data_b));
        }
    };
};debug_assert!(
188                    validate_trivial_unsize(cx.tcx(), data_a, data_b),
189                    "NOP unsize vtable changed principal trait ref: {data_a} -> {data_b}"
190                );
191
192                // A NOP cast that doesn't actually change anything, let's avoid any
193                // unnecessary work. This relies on the assumption that if the principal
194                // traits are equal, then the associated type bounds (`dyn Trait<Assoc=T>`)
195                // are also equal, which is ensured by the fact that normalization is
196                // a function and we do not allow overlapping impls.
197                return old_info;
198            }
199
200            // trait upcasting coercion
201
202            let vptr_entry_idx = cx.tcx().supertrait_vtable_slot((source, target));
203
204            if let Some(entry_idx) = vptr_entry_idx.map(VirtualIndex::from_index) {
205                entry_idx.get_data_ptr(bx, old_info, true)
206            } else {
207                old_info
208            }
209        }
210        (_, ty::Dynamic(data, _)) => meth::get_vtable(
211            cx,
212            source,
213            data.principal()
214                .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),
215        ),
216        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unsized_info: invalid unsizing {0:?} -> {1:?}", source,
        target), Location::caller())bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
217    }
218}
219
220/// Coerces `src` to `dst_ty`. `src_ty` must be a pointer.
221pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
222    bx: &mut Bx,
223    src: Bx::Value,
224    src_ty: Ty<'tcx>,
225    dst_ty: Ty<'tcx>,
226    old_info: Option<Bx::Value>,
227) -> (Bx::Value, Bx::Value) {
228    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/base.rs:228",
                        "rustc_codegen_ssa::base", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/base.rs"),
                        ::tracing_core::__macro_support::Option::Some(228u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::base"),
                        ::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!("unsize_ptr: {0:?} => {1:?}",
                                                    src_ty, dst_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
229    match (src_ty.kind(), dst_ty.kind()) {
230        (&ty::Pat(a, _), &ty::Pat(b, _)) => unsize_ptr(bx, src, a, b, old_info),
231        (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
232        | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
233            {
    match (&bx.cx().type_is_sized(a), &old_info.is_none()) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(bx.cx().type_is_sized(a), old_info.is_none());
234            (src, unsized_info(bx, a, b, old_info))
235        }
236        (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
237            {
    match (&def_a, &def_b) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(def_a, def_b); // implies same number of fields
238            let src_layout = bx.cx().layout_of(src_ty);
239            let dst_layout = bx.cx().layout_of(dst_ty);
240            if src_ty == dst_ty {
241                return (src, old_info.unwrap());
242            }
243            let mut result = None;
244            for i in 0..src_layout.fields.count() {
245                let src_f = src_layout.field(bx.cx(), i);
246                if src_f.is_1zst() {
247                    // We are looking for the one non-1-ZST field; this is not it.
248                    continue;
249                }
250
251                {
    match (&src_layout.fields.offset(i).bytes(), &0) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(src_layout.fields.offset(i).bytes(), 0);
252                {
    match (&dst_layout.fields.offset(i).bytes(), &0) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
253                {
    match (&src_layout.size, &src_f.size) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(src_layout.size, src_f.size);
254
255                let dst_f = dst_layout.field(bx.cx(), i);
256                {
    match (&src_f.ty, &dst_f.ty) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_ne!(src_f.ty, dst_f.ty);
257                {
    match (&result, &None) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(result, None);
258                result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
259            }
260            result.unwrap()
261        }
262        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("unsize_ptr: called on bad types"), Location::caller())bug!("unsize_ptr: called on bad types"),
263    }
264}
265
266/// Coerces `src`, which is a reference to a value of type `src_ty`,
267/// to a value of type `dst_ty`, and stores the result in `dst`.
268pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
269    bx: &mut Bx,
270    src: PlaceRef<'tcx, Bx::Value>,
271    dst: PlaceRef<'tcx, Bx::Value>,
272) {
273    let src_ty = src.layout.ty;
274    let dst_ty = dst.layout.ty;
275    match (src_ty.kind(), dst_ty.kind()) {
276        (&ty::Pat(s, sp), &ty::Pat(d, dp))
277            if let (PatternKind::NotNull, PatternKind::NotNull) = (*sp, *dp) =>
278        {
279            let src = src.project_type(bx, s);
280            let dst = dst.project_type(bx, d);
281            coerce_unsized_into(bx, src, dst)
282        }
283        (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
284            let (base, info) = match bx.load_operand(src).val {
285                OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
286                OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
287                OperandValue::Ref(..) | OperandValue::ZeroSized => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
288            };
289            OperandValue::Pair(base, info).store(bx, dst);
290        }
291
292        (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
293            {
    match (&def_a, &def_b) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(def_a, def_b); // implies same number of fields
294
295            for i in def_a.variant(FIRST_VARIANT).fields.indices() {
296                let src_f = src.project_field(bx, i.as_usize());
297                let dst_f = dst.project_field(bx, i.as_usize());
298
299                if dst_f.layout.is_zst() {
300                    // No data here, nothing to copy/coerce.
301                    continue;
302                }
303
304                if src_f.layout.ty == dst_f.layout.ty {
305                    bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
306                } else {
307                    coerce_unsized_into(bx, src_f, dst_f);
308                }
309            }
310        }
311        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("coerce_unsized_into: invalid coercion {0:?} -> {1:?}",
        src_ty, dst_ty), Location::caller())bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
312    }
313}
314
315/// Returns `rhs` sufficiently masked, truncated, and/or extended so that it can be used to shift
316/// `lhs`: it has the same size as `lhs`, and the value, when interpreted unsigned (no matter its
317/// type), will not exceed the size of `lhs`.
318///
319/// Shifts in MIR are all allowed to have mismatched LHS & RHS types, and signed RHS.
320/// The shift methods in `BuilderMethods`, however, are fully homogeneous
321/// (both parameters and the return type are all the same size) and assume an unsigned RHS.
322///
323/// If `is_unchecked` is false, this masks the RHS to ensure it stays in-bounds,
324/// as the `BuilderMethods` shifts are UB for out-of-bounds shift amounts.
325/// For 32- and 64-bit types, this matches the semantics
326/// of Java. (See related discussion on #1877 and #10183.)
327///
328/// If `is_unchecked` is true, this does no masking, and adds sufficient `assume`
329/// calls or operation flags to preserve as much freedom to optimize as possible.
330pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
331    bx: &mut Bx,
332    lhs: Bx::Value,
333    mut rhs: Bx::Value,
334    is_unchecked: bool,
335) -> Bx::Value {
336    // Shifts may have any size int on the rhs
337    let mut rhs_llty = bx.cx().val_ty(rhs);
338    let mut lhs_llty = bx.cx().val_ty(lhs);
339
340    let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
341    if !is_unchecked {
342        rhs = bx.and(rhs, mask);
343    }
344
345    if let Some(element) = bx.cx().vector_element_type(rhs_llty) {
346        rhs_llty = element;
347    }
348    if let Some(element) = bx.cx().vector_element_type(lhs_llty) {
349        lhs_llty = element;
350    }
351    let rhs_sz = bx.cx().int_width(rhs_llty).expect("rhs is not an integer");
352    let lhs_sz = bx.cx().int_width(lhs_llty).expect("lhs is not an integer");
353    if lhs_sz < rhs_sz {
354        if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
355    } else if lhs_sz > rhs_sz {
356        // We zero-extend even if the RHS is signed. So e.g. `(x: i32) << -1i8` will zero-extend the
357        // RHS to `255i32`. But then we mask the shift amount to be within the size of the LHS
358        // anyway so the result is `31` as it should be. All the extra bits introduced by zext
359        // are masked off so their value does not matter.
360        // FIXME: if we ever support 512bit integers, this will be wrong! For such large integers,
361        // the extra bits introduced by zext are *not* all masked away any more.
362        if !(lhs_sz <= 256) {
    ::core::panicking::panic("assertion failed: lhs_sz <= 256")
};assert!(lhs_sz <= 256);
363        bx.zext(rhs, lhs_llty)
364    } else {
365        rhs
366    }
367}
368
369// Returns `true` if this session's target will use native wasm
370// exceptions. This means that the VM does the unwinding for
371// us
372pub fn wants_wasm_eh(target: &TargetSpec) -> bool {
373    target.is_like_wasm
374}
375
376/// Returns `true` if this session's target will use SEH-based unwinding.
377///
378/// This is only true for MSVC targets, and even then the 64-bit MSVC target
379/// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
380/// 64-bit MinGW) instead of "full SEH".
381pub fn wants_msvc_seh(target: &TargetSpec) -> bool {
382    target.is_like_msvc
383}
384
385/// Returns `true` if this session's target requires the new exception
386/// handling LLVM IR instructions (catchpad / cleanuppad / ... instead
387/// of landingpad)
388pub(crate) fn wants_new_eh_instructions(target: &TargetSpec) -> bool {
389    wants_wasm_eh(target) || wants_msvc_seh(target)
390}
391
392pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
393    cx: &'a Bx::CodegenCx,
394    instance: Instance<'tcx>,
395) {
396    // this is an info! to allow collecting monomorphization statistics
397    // and to allow finding the last function before LLVM aborts from
398    // release builds.
399    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/base.rs:399",
                        "rustc_codegen_ssa::base", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/base.rs"),
                        ::tracing_core::__macro_support::Option::Some(399u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::base"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("codegen_instance({0})",
                                                    instance) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("codegen_instance({})", instance);
400
401    mir::codegen_mir::<Bx>(cx, instance);
402}
403
404pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: hir::ItemId)
405where
406    Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + AsmCodegenMethods<'tcx>,
407{
408    let item = cx.tcx().hir_item(item_id);
409    if let rustc_hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
410        let operands: Vec<_> = asm
411            .operands
412            .iter()
413            .map(|(op, op_sp)| match *op {
414                rustc_hir::InlineAsmOperand::Const { ref anon_const } => {
415                    match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) {
416                        Ok(const_value) => {
417                            let ty =
418                                cx.tcx().typeck_body(anon_const.body).node_type(anon_const.hir_id);
419                            let ConstValue::Scalar(scalar) = const_value else {
420                                ::rustc_span::macros::bug_impl(Some(*op_sp),
    format_args!("expected Scalar for promoted asm const, but got {0:#?}",
        const_value), Location::caller())span_bug!(
421                                    *op_sp,
422                                    "expected Scalar for promoted asm const, but got {:#?}",
423                                    const_value
424                                )
425                            };
426                            GlobalAsmOperandRef::Const {
427                                value: common::asm_const_ptr_clean(cx.tcx(), scalar),
428                                ty,
429                            }
430                        }
431                        Err(ErrorHandled::Reported { .. }) => {
432                            // An error has already been reported and
433                            // compilation is guaranteed to fail if execution
434                            // hits this path. So anything will suffice.
435                            GlobalAsmOperandRef::Const {
436                                value: Scalar::from_u32(0),
437                                ty: Ty::new_uint(cx.tcx(), UintTy::U32),
438                            }
439                        }
440                        Err(ErrorHandled::TooGeneric(_)) => {
441                            ::rustc_span::macros::bug_impl(Some(*op_sp),
    format_args!("asm const cannot be resolved; too generic"),
    Location::caller())span_bug!(*op_sp, "asm const cannot be resolved; too generic")
442                        }
443                    }
444                }
445                rustc_hir::InlineAsmOperand::SymFn { expr } => {
446                    let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
447                    let instance = match ty.kind() {
448                        &ty::FnDef(def_id, args) => Instance::expect_resolve(
449                            cx.tcx(),
450                            cx.typing_env(),
451                            def_id,
452                            args.no_bound_vars().unwrap(),
453                            expr.span,
454                        ),
455                        _ => ::rustc_span::macros::bug_impl(Some(*op_sp),
    format_args!("asm sym is not a function"), Location::caller())span_bug!(*op_sp, "asm sym is not a function"),
456                    };
457
458                    GlobalAsmOperandRef::Const {
459                        value: Scalar::from_pointer(
460                            cx.tcx().reserve_and_set_fn_alloc(instance, CTFE_ALLOC_SALT).into(),
461                            cx,
462                        ),
463                        ty: Ty::new_fn_ptr(cx.tcx(), ty.fn_sig(cx.tcx())),
464                    }
465                }
466                rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
467                    if cx.tcx().is_thread_local_static(def_id) {
468                        GlobalAsmOperandRef::SymThreadLocalStatic { def_id }
469                    } else {
470                        GlobalAsmOperandRef::Const {
471                            value: Scalar::from_pointer(
472                                cx.tcx().reserve_and_set_static_alloc(def_id).into(),
473                                cx,
474                            ),
475                            ty: cx.tcx().static_ptr_ty(def_id, cx.typing_env()),
476                        }
477                    }
478                }
479                rustc_hir::InlineAsmOperand::In { .. }
480                | rustc_hir::InlineAsmOperand::Out { .. }
481                | rustc_hir::InlineAsmOperand::InOut { .. }
482                | rustc_hir::InlineAsmOperand::SplitInOut { .. }
483                | rustc_hir::InlineAsmOperand::Label { .. } => {
484                    ::rustc_span::macros::bug_impl(Some(*op_sp),
    format_args!("invalid operand type for global_asm!"), Location::caller())span_bug!(*op_sp, "invalid operand type for global_asm!")
485                }
486            })
487            .collect();
488
489        cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans, &[]);
490    } else {
491        ::rustc_span::macros::bug_impl(Some(item.span),
    format_args!("Mismatch between hir::Item type and MonoItem type"),
    Location::caller())span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
492    }
493}
494
495/// Creates the `main` function which will initialize the rust runtime and call
496/// users main function.
497pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
498    cx: &'a Bx::CodegenCx,
499    cgu: &CodegenUnit<'tcx>,
500) -> Option<Bx::Function> {
501    let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
502    let main_is_local = main_def_id.is_local();
503    let instance = Instance::mono(cx.tcx(), main_def_id);
504
505    if main_is_local {
506        // We want to create the wrapper in the same codegen unit as Rust's main
507        // function.
508        if !cgu.contains_item(&MonoItem::Fn(instance)) {
509            return None;
510        }
511    } else if !cgu.is_primary() {
512        // We want to create the wrapper only when the codegen unit is the primary one
513        return None;
514    }
515
516    let main_llfn = cx.get_fn_addr(instance, cx.sess().pointer_authentication_functions());
517
518    let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
519    return Some(entry_fn);
520
521    fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
522        cx: &'a Bx::CodegenCx,
523        rust_main: Bx::Value,
524        rust_main_def_id: DefId,
525        entry_type: EntryFnType,
526    ) -> Bx::Function {
527        // The entry function is either `int main(void)` or `int main(int argc, char **argv)`, or
528        // `usize efi_main(void *handle, void *system_table)` depending on the target.
529        let llfty = if cx.sess().target.os == Os::Uefi {
530            cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
531        } else if cx.sess().target.main_needs_argc_argv {
532            cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
533        } else {
534            cx.type_func(&[], cx.type_int())
535        };
536
537        let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
538        // Given that `main()` has no arguments,
539        // then its return type cannot have
540        // late-bound regions, since late-bound
541        // regions must appear in the argument
542        // listing.
543        let main_ret_ty = cx.tcx().normalize_erasing_regions(
544            cx.typing_env(),
545            Unnormalized::new_wip(main_ret_ty.no_bound_vars().unwrap()),
546        );
547
548        let Some(llfn) = cx.declare_c_main(llfty) else {
549            // FIXME: We should be smart and show a better diagnostic here.
550            let span = cx.tcx().def_span(rust_main_def_id);
551            cx.tcx().dcx().emit_fatal(diagnostics::MultipleMainFunctions { span });
552        };
553
554        // `main` should respect same config for frame pointer elimination as rest of code
555        cx.set_frame_pointer_type(llfn);
556        cx.apply_target_cpu_attr(llfn);
557        // The shim has no item behind it, so it does not go through the per-item attribute path.
558        cx.apply_default_optimisation_attrs(llfn);
559
560        let llbb = Bx::append_block(cx, llfn, "top");
561        let mut bx = Bx::build(cx, llbb);
562
563        bx.insert_reference_to_gdb_debug_scripts_section_global();
564
565        let isize_ty = cx.type_isize();
566        let ptr_ty = cx.type_ptr();
567        let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
568
569        let EntryFnType::Main { sigpipe } = entry_type;
570        let (start_fn, start_ty, args, instance) = {
571            let start_def_id = cx.tcx().require_lang_item(LangItem::Start, DUMMY_SP);
572            let start_instance = ty::Instance::expect_resolve(
573                cx.tcx(),
574                cx.typing_env(),
575                start_def_id,
576                cx.tcx().mk_args(&[main_ret_ty.into()]),
577                DUMMY_SP,
578            );
579            let start_fn =
580                cx.get_fn_addr(start_instance, cx.sess().pointer_authentication_functions());
581
582            let i8_ty = cx.type_i8();
583            let arg_sigpipe = bx.const_u8(sigpipe);
584
585            let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
586            (
587                start_fn,
588                start_ty,
589                ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [rust_main, arg_argc, arg_argv, arg_sigpipe]))vec![rust_main, arg_argc, arg_argv, arg_sigpipe],
590                Some(start_instance),
591            )
592        };
593
594        let result =
595            bx.call(start_ty, None, None, start_fn, ReturnSlot::Direct, &args, None, instance);
596        if cx.sess().target.os == Os::Uefi {
597            bx.ret(result);
598        } else {
599            let cast = bx.intcast(result, cx.type_int(), true);
600            bx.ret(cast);
601        }
602
603        llfn
604    }
605}
606
607/// Obtain the `argc` and `argv` values to pass to the rust start function
608/// (i.e., the "start" lang item).
609fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
610    if bx.cx().sess().target.os == Os::Uefi {
611        // Params for UEFI
612        let param_handle = bx.get_param(0);
613        let param_system_table = bx.get_param(1);
614        let ptr_size = bx.tcx().data_layout.pointer_size();
615        let ptr_align = bx.tcx().data_layout.pointer_align();
616        let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
617        let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
618        bx.store(param_handle, arg_argv, ptr_align);
619        let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
620        bx.store(param_system_table, arg_argv_el1, ptr_align);
621        (arg_argc, arg_argv)
622    } else if bx.cx().sess().target.main_needs_argc_argv {
623        // Params from native `main()` used as args for rust start function
624        let param_argc = bx.get_param(0);
625        let param_argv = bx.get_param(1);
626        let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
627        let arg_argv = param_argv;
628        (arg_argc, arg_argv)
629    } else {
630        // The Rust start function doesn't need `argc` and `argv`, so just pass zeros.
631        let arg_argc = bx.const_int(bx.cx().type_int(), 0);
632        let arg_argv = bx.const_null(bx.cx().type_ptr());
633        (arg_argc, arg_argv)
634    }
635}
636
637/// This function returns all of the debugger visualizers specified for the
638/// current crate as well as all upstream crates transitively that match the
639/// `visualizer_type` specified.
640pub fn collect_debugger_visualizers_transitive(
641    tcx: TyCtxt<'_>,
642    visualizer_type: DebuggerVisualizerType,
643) -> BTreeSet<DebuggerVisualizerFile> {
644    tcx.debugger_visualizers(LOCAL_CRATE)
645        .iter()
646        .chain(
647            tcx.crates(())
648                .iter()
649                .filter(|&cnum| {
650                    tcx.used_crate_source_flags(*cnum)
651                        .intersects(CrateSourceFlags::RMETA | CrateSourceFlags::RLIB)
652                })
653                .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
654        )
655        .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
656        .cloned()
657        .collect::<BTreeSet<_>>()
658}
659
660/// Decide allocator kind to codegen. If `Some(_)` this will be the same as
661/// `tcx.allocator_kind`, but it may be `None` in more cases (e.g. if using
662/// allocator definitions from a dylib dependency).
663pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
664    // If the crate doesn't have an `allocator_kind` set then there's definitely
665    // no shim to generate. Otherwise we also check our dependency graph for all
666    // our output crate types. If anything there looks like its a `Dynamic`
667    // linkage for all crate types we may link as, then it's already got an
668    // allocator shim and we'll be using that one instead. If nothing exists
669    // then it's our job to generate the allocator! If crate types disagree
670    // about whether an allocator shim is necessary or not, we generate one
671    // and let needs_allocator_shim_for_linking decide at link time whether or
672    // not to use it for any particular linker invocation.
673    let all_crate_types_any_dynamic_crate = tcx.dependency_formats(()).iter().all(|(_, list)| {
674        use rustc_middle::middle::dependency_format::Linkage;
675        list.iter().any(|&linkage| linkage == Linkage::Dynamic)
676    });
677    if all_crate_types_any_dynamic_crate { None } else { tcx.allocator_kind(()) }
678}
679
680/// Decide if this particular crate type needs an allocator shim linked in.
681/// This may return true even when allocator_kind_for_codegen returns false. In
682/// this case no allocator shim shall be linked.
683pub(crate) fn needs_allocator_shim_for_linking(
684    dependency_formats: &Dependencies,
685    crate_type: CrateType,
686) -> bool {
687    use rustc_middle::middle::dependency_format::Linkage;
688    let any_dynamic_crate =
689        dependency_formats[&crate_type].iter().any(|&linkage| linkage == Linkage::Dynamic);
690    !any_dynamic_crate
691}
692
693pub fn allocator_shim_contents(tcx: TyCtxt<'_>, kind: AllocatorKind) -> Vec<AllocatorMethod> {
694    let mut methods = Vec::new();
695
696    if kind == AllocatorKind::Default {
697        methods.extend(ALLOCATOR_METHODS.into_iter().copied());
698    }
699
700    // If the return value of allocator_kind_for_codegen is Some then
701    // alloc_error_handler_kind must also be Some.
702    if tcx.alloc_error_handler_kind(()).unwrap() == AllocatorKind::Default {
703        methods.push(AllocatorMethod {
704            name: ALLOC_ERROR_HANDLER,
705            special: None,
706            inputs: &[AllocatorMethodInput { name: "layout", ty: AllocatorTy::Layout }],
707            output: AllocatorTy::Never,
708        });
709    }
710
711    methods
712}
713
714pub fn codegen_crate<
715    B: ExtraBackendMethods<Module = M> + WriteBackendMethods<Module = M>,
716    M: Send,
717>(
718    backend: B,
719    tcx: TyCtxt<'_>,
720) -> OngoingCodegen<B> {
721    if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
722        // The target has no default cpu, but none is set explicitly
723        tcx.dcx().emit_fatal(diagnostics::CpuRequired);
724    }
725
726    if let Some(target_cpu) = &tcx.sess.opts.cg.target_cpu
727        && tcx.sess.target.unsupported_cpus.contains(&target_cpu.into())
728    {
729        // The target cpu is explicitly listed as an unsupported cpu
730        tcx.dcx().emit_fatal(diagnostics::CpuUnsupported { target_cpu: target_cpu.clone() });
731    }
732
733    let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
734
735    // Run the monomorphization collector and partition the collected items into
736    // codegen units.
737    let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());
738
739    // Force all codegen_unit queries so they are already either red or green
740    // when compile_codegen_unit accesses them. We are not able to re-execute
741    // the codegen_unit query from just the DepNode, so an unknown color would
742    // lead to having to re-execute compile_codegen_unit, possibly
743    // unnecessarily.
744    if tcx.dep_graph.is_fully_enabled() {
745        for cgu in codegen_units {
746            tcx.ensure_ok().codegen_unit(cgu.name());
747        }
748    }
749
750    // Codegen an allocator shim, if necessary.
751    let allocator_module = if let Some(kind) = allocator_kind_for_codegen(tcx) {
752        let llmod_id =
753            cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
754
755        tcx.sess.time("write_allocator_module", || {
756            let module =
757                backend.codegen_allocator(tcx, &llmod_id, &allocator_shim_contents(tcx, kind));
758            Some(ModuleCodegen::new_allocator(llmod_id, module))
759        })
760    } else {
761        None
762    };
763
764    let no_builtins = {
        'done:
            {
            for i in tcx.hir_krate_attrs() {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(NoBuiltins) => {
                        break 'done Some(());
                    }
                    ::rustc_attr_ir::Attribute::Tool { .. } |
                        ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }.is_some()find_attr!(tcx, crate, NoBuiltins);
765    let regular_module_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
766    let bitcode_needed = regular_module_config.bitcode_needed();
767    let allocator_module_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
768
769    let ongoing_codegen = start_async_codegen(
770        backend.clone(),
771        tcx,
772        Arc::new(regular_module_config),
773        Arc::new(allocator_module_config),
774        allocator_module,
775    );
776
777    // For better throughput during parallel processing by LLVM, we used to sort
778    // CGUs largest to smallest. This would lead to better thread utilization
779    // by, for example, preventing a large CGU from being processed last and
780    // having only one LLVM thread working while the rest remained idle.
781    //
782    // However, this strategy would lead to high memory usage, as it meant the
783    // LLVM-IR for all of the largest CGUs would be resident in memory at once.
784    //
785    // Instead, we can compromise by ordering CGUs such that the largest and
786    // smallest are first, second largest and smallest are next, etc. If there
787    // are large size variations, this can reduce memory usage significantly.
788    let codegen_units: Vec<_> = {
789        let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
790        sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
791
792        let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
793        first_half.iter().interleave(second_half.iter().rev()).copied().collect()
794    };
795
796    // Calculate the CGU reuse
797    let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
798        codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
799    });
800
801    crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
802        for (i, cgu) in codegen_units.iter().enumerate() {
803            let cgu_reuse = cgu_reuse[i];
804            cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
805        }
806    });
807
808    let mut total_codegen_time = Duration::new(0, 0);
809    let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
810
811    // The non-parallel compiler can only translate codegen units to LLVM IR
812    // on a single thread, leading to a staircase effect where the N LLVM
813    // threads have to wait on the single codegen threads to generate work
814    // for them. The parallel compiler does not have this restriction, so
815    // we can pre-load the LLVM queue in parallel before handing off
816    // coordination to the OnGoingCodegen scheduler.
817    //
818    // This likely is a temporary measure. Once we don't have to support the
819    // non-parallel compiler anymore, we can compile CGUs end-to-end in
820    // parallel and get rid of the complicated scheduling logic.
821    let mut pre_compiled_cgus = if let JobsMode::Parallel(threads) = tcx.sess.opts.jobs.frontend {
822        tcx.sess.time("compile_first_CGU_batch", || {
823            // Try to find one CGU to compile per thread.
824            let cgus: Vec<_> = cgu_reuse
825                .iter()
826                .enumerate()
827                .filter(|&(_, reuse)| reuse == &CguReuse::No)
828                .take(threads.get())
829                .collect();
830
831            // Compile the found CGUs in parallel.
832            let start_time = Instant::now();
833
834            let pre_compiled_cgus = par_map(cgus, |(i, _)| {
835                let module =
836                    backend.compile_codegen_unit(tcx, codegen_units[i].name(), bitcode_needed);
837                (i, IntoDynSyncSend(module))
838            });
839
840            total_codegen_time += start_time.elapsed();
841
842            pre_compiled_cgus
843        })
844    } else {
845        FxHashMap::default()
846    };
847
848    for (i, cgu) in codegen_units.iter().enumerate() {
849        ongoing_codegen.wait_for_signal_to_codegen_item();
850        ongoing_codegen.check_for_errors(tcx.sess);
851
852        let cgu_reuse = cgu_reuse[i];
853
854        match cgu_reuse {
855            CguReuse::No => {
856                let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
857                    cgu.0
858                } else {
859                    let start_time = Instant::now();
860                    let module = backend.compile_codegen_unit(tcx, cgu.name(), bitcode_needed);
861                    total_codegen_time += start_time.elapsed();
862                    module
863                };
864                // This will unwind if there are errors, which triggers our `AbortCodegenOnDrop`
865                // guard. Unfortunately, just skipping the `submit_codegened_module_to_llvm` makes
866                // compilation hang on post-monomorphization errors.
867                tcx.dcx().abort_if_errors();
868
869                submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);
870            }
871            CguReuse::PreLto => {
872                submit_pre_lto_module_to_llvm(
873                    tcx.sess,
874                    tcx.incr_comp_session.unwrap(),
875                    &ongoing_codegen.coordinator,
876                    CachedModuleCodegen {
877                        name: cgu.name().to_string(),
878                        source: cgu.previous_work_product(tcx),
879                    },
880                );
881                // This will unwind if there are errors, which triggers our `AbortCodegenOnDrop`
882                // guard. Unfortunately, just skipping the `submit_pre_lto_module_to_llvm` makes
883                // compilation hang on post-monomorphization errors.
884                tcx.dcx().abort_if_errors();
885            }
886            CguReuse::PostLto => {
887                submit_post_lto_module_to_llvm(
888                    &ongoing_codegen.coordinator,
889                    CachedModuleCodegen {
890                        name: cgu.name().to_string(),
891                        source: cgu.previous_work_product(tcx),
892                    },
893                );
894            }
895        }
896    }
897
898    ongoing_codegen.codegen_finished(tcx);
899
900    // Since the main thread is sometimes blocked during codegen, we keep track
901    // -Ztime-passes output manually.
902    if tcx.sess.opts.unstable_opts.time_passes {
903        let end_rss = get_resident_set_size();
904
905        print_time_passes_entry(
906            "codegen_to_LLVM_IR",
907            total_codegen_time,
908            start_rss.unwrap(),
909            end_rss,
910            tcx.sess.opts.unstable_opts.time_passes_format,
911        );
912    }
913
914    ongoing_codegen.check_for_errors(tcx.sess);
915    ongoing_codegen
916}
917
918/// Returns whether a call from the current crate to the [`Instance`] would produce a call
919/// from `compiler_builtins` to a symbol the linker must resolve.
920///
921/// Such calls from `compiler_builtins` are effectively impossible for the linker to handle. Some
922/// linkers will optimize such that dead calls to unresolved symbols are not an error, but this is
923/// not guaranteed. So we use this function in codegen backends to ensure we do not generate any
924/// unlinkable calls.
925///
926/// Note that calls to LLVM intrinsics are uniquely okay because they won't make it to the linker.
927/// Note also that calls to foreign items that are actually exported by the local crate are also
928/// okay. This situation arises because compiler-builtins calls functions in core that are
929/// `#[inline]` wrappers for `extern "C"` declarations in core, which resolve to a symbol exported
930/// by compiler-builtins.
931pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
932    tcx: TyCtxt<'tcx>,
933    instance: Instance<'tcx>,
934) -> bool {
935    if let ty::InstanceKind::LlvmIntrinsic(_) = instance.def {
936        return false;
937    }
938
939    fn is_extern_call_to_local_crate<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool {
940        tcx.is_foreign_item(instance.def_id())
941            && tcx.exported_non_generic_symbols(LOCAL_CRATE).iter().any(|(sym, _info)| {
942                sym.symbol_name_for_local_instance(tcx) == tcx.symbol_name(instance)
943            })
944    }
945
946    let def_id = instance.def_id();
947    !def_id.is_local()
948        && tcx.is_compiler_builtins(LOCAL_CRATE)
949        && !tcx.should_codegen_locally(instance)
950        && !is_extern_call_to_local_crate(tcx, instance)
951}
952
953fn collect_eii_linkage(tcx: TyCtxt<'_>) -> Vec<EiiLinkageInfo> {
954    #[derive(#[automatically_derived]impl ::core::fmt::Debug for FoundImpl {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "FoundImpl imp impl_crate", &self.imp, &&self.impl_crate)
    }
}Debug)]
955    struct FoundImpl {
956        imp: EiiImpl,
957        impl_crate: CrateNum,
958    }
959
960    #[derive(#[automatically_derived]impl ::core::fmt::Debug for FoundEii {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "FoundEii decl impls", &self.decl, &&self.impls)
    }
}Debug)]
961    struct FoundEii {
962        decl: EiiDecl,
963        impls: FxIndexMap<DefId, FoundImpl>,
964    }
965
966    let mut eiis = FxIndexMap::<DefId, FoundEii>::default();
967
968    for &cnum in tcx.crates(()).iter().chain(iter::once(&LOCAL_CRATE)) {
969        for (&did, &(decl, ref impls)) in tcx.externally_implementable_items(cnum) {
970            eiis.entry(did)
971                .or_insert_with(|| FoundEii { decl, impls: Default::default() })
972                .impls
973                .extend(
974                    impls
975                        .into_iter()
976                        .map(|(&did, &imp)| (did, FoundImpl { imp, impl_crate: cnum })),
977                );
978        }
979    }
980
981    eiis.into_iter()
982        .filter_map(|(_, FoundEii { decl, impls })| {
983            let mut explicit_impls = Vec::new();
984            let mut default_impl = None;
985
986            for (impl_did, FoundImpl { imp, impl_crate }) in impls {
987                let impl_info = EiiLinkageImplInfo { span: tcx.def_span(impl_did), impl_crate };
988                if imp.is_default {
989                    default_impl = Some(impl_info);
990                } else {
991                    explicit_impls.push(impl_info);
992                }
993            }
994
995            // Link time check is only needed when there may be a default impl in a dylib.
996            // Other cases emit an error in `rustc_passes` already.
997            if let Some(default_impl) = default_impl {
998                Some(EiiLinkageInfo {
999                    name: decl.name.name,
1000                    impls: explicit_impls,
1001                    default_impl: Some(default_impl),
1002                })
1003            } else {
1004                None
1005            }
1006        })
1007        .collect()
1008}
1009
1010fn eii_linkage_needed(dependency_formats: &Dependencies) -> bool {
1011    dependency_formats.values().any(|formats| {
1012        formats
1013            .iter()
1014            .any(|&linkage| #[allow(non_exhaustive_omitted_patterns)] match linkage {
    Linkage::Dynamic | Linkage::IncludedFromDylib => true,
    _ => false,
}matches!(linkage, Linkage::Dynamic | Linkage::IncludedFromDylib))
1015    })
1016}
1017
1018impl CrateInfo {
1019    pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
1020        let crate_types = tcx.crate_types().to_vec();
1021        let exported_symbols = crate_types
1022            .iter()
1023            .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
1024            .collect();
1025        let linked_symbols =
1026            crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
1027        let local_crate_name = tcx.crate_name(LOCAL_CRATE);
1028        let windows_subsystem = {
    'done:
        {
        for i in tcx.hir_krate_attrs() {
            #[allow(unused_imports)]
            use ::rustc_attr_ir::AttributeKind::*;
            let i: &::rustc_attr_ir::Attribute = i;
            match i {
                ::rustc_attr_ir::Attribute::Parsed(WindowsSubsystem(kind)) =>
                    {
                    break 'done Some(*kind);
                }
                ::rustc_attr_ir::Attribute::Tool { .. } |
                    ::rustc_attr_ir::Attribute::DeriveHelper(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(tcx, crate, WindowsSubsystem(kind) => *kind);
1029        let dependency_formats = Arc::clone(tcx.dependency_formats(()));
1030        let eii_linkage = if eii_linkage_needed(&dependency_formats) {
1031            collect_eii_linkage(tcx)
1032        } else {
1033            Vec::new()
1034        };
1035
1036        // This list is used when generating the command line to pass through to
1037        // system linker. The linker expects undefined symbols on the left of the
1038        // command line to be defined in libraries on the right, not the other way
1039        // around. For more info, see some comments in the add_used_library function
1040        // below.
1041        //
1042        // In order to get this left-to-right dependency ordering, we use the reverse
1043        // postorder of all crates putting the leaves at the rightmost positions.
1044        let mut compiler_builtins = None;
1045        let mut used_crates: Vec<_> = tcx
1046            .postorder_cnums(())
1047            .iter()
1048            .rev()
1049            .copied()
1050            .filter(|&cnum| {
1051                let link = !tcx.crate_dep_kind(cnum).macros_only();
1052                if link && tcx.is_compiler_builtins(cnum) {
1053                    compiler_builtins = Some(cnum);
1054                    return false;
1055                }
1056                link
1057            })
1058            .collect();
1059        // `compiler_builtins` are always placed last to ensure that they're linked correctly.
1060        used_crates.extend(compiler_builtins);
1061
1062        let crates = tcx.crates(());
1063        let n_crates = crates.len();
1064        let mut info = CrateInfo {
1065            target_cpu,
1066            target_features: tcx.sess.global_backend_features.clone(),
1067            crate_types,
1068            exported_symbols,
1069            linked_symbols,
1070            local_crate_name,
1071            compiler_builtins,
1072            profiler_runtime: None,
1073            is_no_builtins: Default::default(),
1074            native_libraries: Default::default(),
1075            used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
1076            crate_name: UnordMap::with_capacity(n_crates),
1077            used_crates,
1078            used_crate_source: UnordMap::with_capacity(n_crates),
1079            dependency_formats,
1080            eii_linkage,
1081            windows_subsystem,
1082            natvis_debugger_visualizers: Default::default(),
1083            lint_level_specs: CodegenLintLevelSpecs::from_tcx(tcx),
1084            metadata_symbol: exported_symbols::metadata_symbol_name(tcx),
1085            symbol_rename_suffix: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(".rs{0:x}",
                tcx.stable_crate_id(LOCAL_CRATE)))
    })format!(".rs{:x}", tcx.stable_crate_id(LOCAL_CRATE)),
1086            each_linked_rlib_file_for_lto: Default::default(),
1087            exported_symbols_for_lto: Default::default(),
1088        };
1089
1090        info.native_libraries.reserve(n_crates);
1091
1092        for &cnum in crates.iter() {
1093            info.native_libraries
1094                .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
1095            info.crate_name.insert(cnum, tcx.crate_name(cnum));
1096
1097            let used_crate_source = tcx.used_crate_source(cnum);
1098            info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
1099            if tcx.is_profiler_runtime(cnum) {
1100                info.profiler_runtime = Some(cnum);
1101            }
1102            if tcx.is_no_builtins(cnum) {
1103                info.is_no_builtins.insert(cnum);
1104            }
1105        }
1106
1107        // Handle circular dependencies in the standard library.
1108        // See comment before `add_linked_symbol_object` function for the details.
1109        // If global LTO is enabled then almost everything (*) is glued into a single object file,
1110        // so this logic is not necessary and can cause issues on some targets (due to weak lang
1111        // item symbols being "privatized" to that object file), so we disable it.
1112        // (*) Native libs, and `#[compiler_builtins]` and `#[no_builtins]` crates are not glued,
1113        // and we assume that they cannot define weak lang items. This is not currently enforced
1114        // by the compiler, but that's ok because all this stuff is unstable anyway.
1115        let target = &tcx.sess.target;
1116        if !are_upstream_rust_objects_already_included(tcx.sess) {
1117            let add_prefix = match (target.is_like_windows, &target.arch) {
1118                (true, Arch::X86) => |name: String, _: SymbolExportKind| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("_{0}", name))
    })format!("_{name}"),
1119                (true, Arch::Arm64EC) => {
1120                    // Only functions are decorated for arm64ec.
1121                    |name: String, export_kind: SymbolExportKind| match export_kind {
1122                        SymbolExportKind::Text => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("#{0}", name))
    })format!("#{name}"),
1123                        _ => name,
1124                    }
1125                }
1126                _ => |name: String, _: SymbolExportKind| name,
1127            };
1128            let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info
1129                .used_crates
1130                .iter()
1131                .flat_map(|&cnum| tcx.missing_lang_items(cnum))
1132                .filter(|l| l.is_weak())
1133                .filter_map(|&l| {
1134                    let name = l.link_name()?;
1135                    let export_kind = match l.target() {
1136                        Target::ForeignFn | Target::Fn => SymbolExportKind::Text,
1137                        Target::Static => SymbolExportKind::Data,
1138                        _ => ::rustc_span::macros::bug_impl(None,
    format_args!("Don\'t know what the export kind is for lang item of kind {0:?}",
        l.target()), Location::caller())bug!(
1139                            "Don't know what the export kind is for lang item of kind {:?}",
1140                            l.target()
1141                        ),
1142                    };
1143                    lang_items::required(tcx, l).then_some((name, export_kind))
1144                })
1145                .collect();
1146
1147            // This loop only adds new items to values of the hash map, so the order in which we
1148            // iterate over the values is not important.
1149            #[allow(rustc::potential_query_instability)]
1150            info.linked_symbols
1151                .iter_mut()
1152                .filter(|(crate_type, _)| {
1153                    !#[allow(non_exhaustive_omitted_patterns)] match crate_type {
    CrateType::Rlib | CrateType::StaticLib => true,
    _ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib)
1154                })
1155                .for_each(|(_, linked_symbols)| {
1156                    let mut symbols = missing_weak_lang_items
1157                        .iter()
1158                        .map(|(item, export_kind)| {
1159                            (
1160                                add_prefix(
1161                                    mangle_internal_symbol(tcx, item.as_str()),
1162                                    *export_kind,
1163                                ),
1164                                *export_kind,
1165                            )
1166                        })
1167                        .collect::<Vec<_>>();
1168                    symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1169                    linked_symbols.extend(symbols);
1170                });
1171        }
1172
1173        let mut each_linked_rlib_for_lto = Vec::new();
1174        let mut each_linked_rlib_file_for_lto = Vec::new();
1175        if tcx.sess.lto() != config::Lto::No && tcx.sess.lto() != config::Lto::ThinLocal {
1176            drop(crate::back::link::each_linked_rlib(&info, None, &mut |cnum, path| {
1177                if crate::back::link::ignored_for_lto(tcx.sess, &info, cnum) {
1178                    return;
1179                }
1180
1181                each_linked_rlib_for_lto.push(cnum);
1182                each_linked_rlib_file_for_lto.push(path.to_path_buf());
1183            }));
1184        }
1185        info.each_linked_rlib_file_for_lto = each_linked_rlib_file_for_lto;
1186
1187        // FIXME move to -Zlink-only half such that each_linked_rlib_file_for_lto can be moved there too
1188        // Compute the set of symbols we need to retain when doing LTO (if we need to)
1189        info.exported_symbols_for_lto =
1190            crate::back::lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto);
1191
1192        let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1193            CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1194                // These are crate types for which we invoke the linker and can embed
1195                // NatVis visualizers.
1196                true
1197            }
1198            CrateType::ProcMacro => {
1199                // We could embed NatVis for proc macro crates too (to improve the debugging
1200                // experience for them) but it does not seem like a good default, since
1201                // this is a rare use case and we don't want to slow down the common case.
1202                false
1203            }
1204            CrateType::StaticLib | CrateType::Rlib => {
1205                // We don't invoke the linker for these, so we don't need to collect the NatVis for
1206                // them.
1207                false
1208            }
1209        });
1210
1211        if target.is_like_msvc && embed_visualizers {
1212            info.natvis_debugger_visualizers =
1213                collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1214        }
1215
1216        info
1217    }
1218}
1219
1220pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1221    if !tcx.dep_graph.is_fully_enabled()
1222        || tcx.sess.opts.unstable_opts.disable_incr_comp_backend_caching
1223    {
1224        return CguReuse::No;
1225    }
1226
1227    let work_product_id = &cgu.work_product_id();
1228    if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1229        // We don't have anything cached for this CGU. This can happen
1230        // if the CGU did not exist in the previous session.
1231        return CguReuse::No;
1232    }
1233
1234    // Try to mark the CGU as green. If it we can do so, it means that nothing
1235    // affecting the LLVM module has changed and we can re-use a cached version.
1236    // If we compile with any kind of LTO, this means we can re-use the bitcode
1237    // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
1238    // know that later). If we are not doing LTO, there is only one optimized
1239    // version of each module, so we re-use that.
1240    let dep_node = cgu.codegen_dep_node(tcx);
1241    tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(tcx.sess, &dep_node, || {
1242        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("CompileCodegenUnit dep-node for CGU `{0}` already exists before marking.",
                cgu.name()))
    })format!(
1243            "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1244            cgu.name()
1245        )
1246    });
1247
1248    if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
1249        // We can re-use either the pre- or the post-thinlto state. If no LTO is
1250        // being performed then we can use post-LTO artifacts, otherwise we must
1251        // reuse pre-LTO artifacts
1252        match compute_per_cgu_lto_type(
1253            &tcx.sess.lto(),
1254            tcx.sess.opts.cg.linker_plugin_lto.enabled(),
1255            tcx.crate_types(),
1256        ) {
1257            ComputedLtoType::No => CguReuse::PostLto,
1258            _ => CguReuse::PreLto,
1259        }
1260    } else {
1261        CguReuse::No
1262    }
1263}