rustc_codegen_ssa/
base.rs

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