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_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
13use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
14use rustc_data_structures::sync::{IntoDynSyncSend, par_map};
15use rustc_data_structures::unord::UnordMap;
16use rustc_hir::attrs::{DebuggerVisualizerType, EiiDecl, EiiImpl, OptimizeAttr};
17use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
18use rustc_hir::lang_items::LangItem;
19use rustc_hir::{ItemId, Target, find_attr};
20use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
21use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
22use rustc_middle::middle::dependency_format::{Dependencies, Linkage};
23use rustc_middle::middle::exported_symbols::{self, SymbolExportKind};
24use rustc_middle::middle::lang_items;
25use rustc_middle::mir::BinOp;
26use rustc_middle::mir::interpret::ErrorHandled;
27use rustc_middle::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem, MonoItemPartitions};
28use rustc_middle::query::Providers;
29use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
30use rustc_middle::ty::{self, Instance, PatternKind, Ty, TyCtxt, Unnormalized};
31use rustc_middle::{bug, span_bug};
32use rustc_session::Session;
33use rustc_session::config::{self, CrateType, EntryFnType};
34use rustc_span::{DUMMY_SP, Symbol};
35use rustc_symbol_mangling::mangle_internal_symbol;
36use rustc_target::spec::{Arch, Os};
37use rustc_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt};
38use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt};
39use tracing::{debug, info};
40
41use crate::assert_module_sources::CguReuse;
42use crate::back::link::are_upstream_rust_objects_already_included;
43use crate::back::write::{
44 ComputedLtoType, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen,
45 submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm,
46};
47use crate::common::{self, IntPredicate, RealPredicate, TypeKind};
48use crate::meth::load_vtable;
49use crate::mir::operand::OperandValue;
50use crate::mir::place::PlaceRef;
51use crate::traits::*;
52use crate::{
53 CachedModuleCodegen, CodegenLintLevelSpecs, CrateInfo, EiiLinkageImplInfo, EiiLinkageInfo,
54 ModuleCodegen, errors, meth, mir,
55};
56
57pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
58 match (op, signed) {
59 (BinOp::Eq, _) => IntPredicate::IntEQ,
60 (BinOp::Ne, _) => IntPredicate::IntNE,
61 (BinOp::Lt, true) => IntPredicate::IntSLT,
62 (BinOp::Lt, false) => IntPredicate::IntULT,
63 (BinOp::Le, true) => IntPredicate::IntSLE,
64 (BinOp::Le, false) => IntPredicate::IntULE,
65 (BinOp::Gt, true) => IntPredicate::IntSGT,
66 (BinOp::Gt, false) => IntPredicate::IntUGT,
67 (BinOp::Ge, true) => IntPredicate::IntSGE,
68 (BinOp::Ge, false) => IntPredicate::IntUGE,
69 op => ::rustc_middle::util::bug::bug_fmt(format_args!("bin_op_to_icmp_predicate: expected comparison operator, found {0:?}",
op))bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),
70 }
71}
72
73pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
74 match op {
75 BinOp::Eq => RealPredicate::RealOEQ,
76 BinOp::Ne => RealPredicate::RealUNE,
77 BinOp::Lt => RealPredicate::RealOLT,
78 BinOp::Le => RealPredicate::RealOLE,
79 BinOp::Gt => RealPredicate::RealOGT,
80 BinOp::Ge => RealPredicate::RealOGE,
81 op => ::rustc_middle::util::bug::bug_fmt(format_args!("bin_op_to_fcmp_predicate: expected comparison operator, found {0:?}",
op))bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),
82 }
83}
84
85pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
86 bx: &mut Bx,
87 lhs: Bx::Value,
88 rhs: Bx::Value,
89 t: Ty<'tcx>,
90 ret_ty: Bx::Type,
91 op: BinOp,
92) -> Bx::Value {
93 let signed = match t.kind() {
94 ty::Float(_) => {
95 let cmp = bin_op_to_fcmp_predicate(op);
96 let cmp = bx.fcmp(cmp, lhs, rhs);
97 return bx.sext(cmp, ret_ty);
98 }
99 ty::Uint(_) => false,
100 ty::Int(_) => true,
101 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("compare_simd_types: invalid SIMD type"))bug!("compare_simd_types: invalid SIMD type"),
102 };
103
104 let cmp = bin_op_to_icmp_predicate(op, signed);
105 let cmp = bx.icmp(cmp, lhs, rhs);
106 bx.sext(cmp, ret_ty)
111}
112
113pub fn validate_trivial_unsize<'tcx>(
122 tcx: TyCtxt<'tcx>,
123 source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
124 target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
125) -> bool {
126 match (source_data.principal(), target_data.principal()) {
127 (Some(hr_source_principal), Some(hr_target_principal)) => {
128 let (infcx, param_env) =
129 tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
130 let universe = infcx.universe();
131 let ocx = ObligationCtxt::new(&infcx);
132 infcx.enter_forall(hr_target_principal, |target_principal| {
133 let source_principal = infcx.instantiate_binder_with_fresh_vars(
134 DUMMY_SP,
135 BoundRegionConversionTime::HigherRankedType,
136 hr_source_principal,
137 );
138 let Ok(()) = ocx.eq(
139 &ObligationCause::dummy(),
140 param_env,
141 target_principal,
142 source_principal,
143 ) else {
144 return false;
145 };
146 if !ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
147 return false;
148 }
149 infcx.leak_check(universe, None).is_ok()
150 })
151 }
152 (_, None) => true,
153 _ => false,
154 }
155}
156
157fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
163 bx: &mut Bx,
164 source: Ty<'tcx>,
165 target: Ty<'tcx>,
166 old_info: Option<Bx::Value>,
167) -> Bx::Value {
168 let cx = bx.cx();
169 let (source, target) =
170 cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
171 match (source.kind(), target.kind()) {
172 (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
173 len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
174 ),
175 (&ty::Dynamic(data_a, _), &ty::Dynamic(data_b, _)) => {
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 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!(
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 return old_info;
199 }
200
201 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 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unsized_info: invalid unsizing {0:?} -> {1:?}",
source, target))bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
220 }
221}
222
223pub(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 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/base.rs:231",
"rustc_codegen_ssa::base", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/base.rs"),
::tracing_core::__macro_support::Option::Some(231u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("unsize_ptr: {0:?} => {1:?}",
src_ty, dst_ty) as &dyn Value))])
});
} else { ; }
};debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
232 match (src_ty.kind(), dst_ty.kind()) {
233 (&ty::Pat(a, _), &ty::Pat(b, _)) => unsize_ptr(bx, src, a, b, old_info),
234 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
235 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
236 {
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());
237 (src, unsized_info(bx, a, b, old_info))
238 }
239 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
240 {
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); let src_layout = bx.cx().layout_of(src_ty);
242 let dst_layout = bx.cx().layout_of(dst_ty);
243 if src_ty == dst_ty {
244 return (src, old_info.unwrap());
245 }
246 let mut result = None;
247 for i in 0..src_layout.fields.count() {
248 let src_f = src_layout.field(bx.cx(), i);
249 if src_f.is_1zst() {
250 continue;
252 }
253
254 {
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);
255 {
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);
256 {
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);
257
258 let dst_f = dst_layout.field(bx.cx(), i);
259 {
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);
260 {
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);
261 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
262 }
263 result.unwrap()
264 }
265 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unsize_ptr: called on bad types"))bug!("unsize_ptr: called on bad types"),
266 }
267}
268
269pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
272 bx: &mut Bx,
273 src: PlaceRef<'tcx, Bx::Value>,
274 dst: PlaceRef<'tcx, Bx::Value>,
275) {
276 let src_ty = src.layout.ty;
277 let dst_ty = dst.layout.ty;
278 match (src_ty.kind(), dst_ty.kind()) {
279 (&ty::Pat(s, sp), &ty::Pat(d, dp))
280 if let (PatternKind::NotNull, PatternKind::NotNull) = (*sp, *dp) =>
281 {
282 let src = src.project_type(bx, s);
283 let dst = dst.project_type(bx, d);
284 coerce_unsized_into(bx, src, dst)
285 }
286 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
287 let (base, info) = match bx.load_operand(src).val {
288 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
289 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
290 OperandValue::Ref(..) | OperandValue::ZeroSized => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
291 };
292 OperandValue::Pair(base, info).store(bx, dst);
293 }
294
295 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
296 {
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); for i in def_a.variant(FIRST_VARIANT).fields.indices() {
299 let src_f = src.project_field(bx, i.as_usize());
300 let dst_f = dst.project_field(bx, i.as_usize());
301
302 if dst_f.layout.is_zst() {
303 continue;
305 }
306
307 if src_f.layout.ty == dst_f.layout.ty {
308 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
309 } else {
310 coerce_unsized_into(bx, src_f, dst_f);
311 }
312 }
313 }
314 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("coerce_unsized_into: invalid coercion {0:?} -> {1:?}",
src_ty, dst_ty))bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
315 }
316}
317
318pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
334 bx: &mut Bx,
335 lhs: Bx::Value,
336 mut rhs: Bx::Value,
337 is_unchecked: bool,
338) -> Bx::Value {
339 let mut rhs_llty = bx.cx().val_ty(rhs);
341 let mut lhs_llty = bx.cx().val_ty(lhs);
342
343 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
344 if !is_unchecked {
345 rhs = bx.and(rhs, mask);
346 }
347
348 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
349 rhs_llty = bx.cx().element_type(rhs_llty)
350 }
351 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
352 lhs_llty = bx.cx().element_type(lhs_llty)
353 }
354 let rhs_sz = bx.cx().int_width(rhs_llty);
355 let lhs_sz = bx.cx().int_width(lhs_llty);
356 if lhs_sz < rhs_sz {
357 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
358 } else if lhs_sz > rhs_sz {
359 if !(lhs_sz <= 256) {
::core::panicking::panic("assertion failed: lhs_sz <= 256")
};assert!(lhs_sz <= 256);
366 bx.zext(rhs, lhs_llty)
367 } else {
368 rhs
369 }
370}
371
372pub fn wants_wasm_eh(sess: &Session) -> bool {
376 sess.target.is_like_wasm
377}
378
379pub fn wants_msvc_seh(sess: &Session) -> bool {
385 sess.target.is_like_msvc
386}
387
388pub(crate) fn wants_new_eh_instructions(sess: &Session) -> bool {
392 wants_wasm_eh(sess) || wants_msvc_seh(sess)
393}
394
395pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
396 cx: &'a Bx::CodegenCx,
397 instance: Instance<'tcx>,
398) {
399 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/base.rs:402",
"rustc_codegen_ssa::base", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/base.rs"),
::tracing_core::__macro_support::Option::Some(402u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("codegen_instance({0})",
instance) as &dyn Value))])
});
} else { ; }
};info!("codegen_instance({})", instance);
403
404 mir::codegen_mir::<Bx>(cx, instance);
405}
406
407pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: ItemId)
408where
409 Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + AsmCodegenMethods<'tcx>,
410{
411 let item = cx.tcx().hir_item(item_id);
412 if let rustc_hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
413 let operands: Vec<_> = asm
414 .operands
415 .iter()
416 .map(|(op, op_sp)| match *op {
417 rustc_hir::InlineAsmOperand::Const { ref anon_const } => {
418 match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) {
419 Ok(const_value) => {
420 let ty =
421 cx.tcx().typeck_body(anon_const.body).node_type(anon_const.hir_id);
422 let string = common::asm_const_to_str(
423 cx.tcx(),
424 *op_sp,
425 const_value,
426 cx.layout_of(ty),
427 );
428 GlobalAsmOperandRef::Const { string }
429 }
430 Err(ErrorHandled::Reported { .. }) => {
431 GlobalAsmOperandRef::Const { string: String::new() }
436 }
437 Err(ErrorHandled::TooGeneric(_)) => {
438 ::rustc_middle::util::bug::span_bug_fmt(*op_sp,
format_args!("asm const cannot be resolved; too generic"))span_bug!(*op_sp, "asm const cannot be resolved; too generic")
439 }
440 }
441 }
442 rustc_hir::InlineAsmOperand::SymFn { expr } => {
443 let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
444 let instance = match ty.kind() {
445 &ty::FnDef(def_id, args) => Instance::expect_resolve(
446 cx.tcx(),
447 ty::TypingEnv::fully_monomorphized(),
448 def_id,
449 args,
450 expr.span,
451 ),
452 _ => ::rustc_middle::util::bug::span_bug_fmt(*op_sp,
format_args!("asm sym is not a function"))span_bug!(*op_sp, "asm sym is not a function"),
453 };
454
455 GlobalAsmOperandRef::SymFn { instance }
456 }
457 rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
458 GlobalAsmOperandRef::SymStatic { def_id }
459 }
460 rustc_hir::InlineAsmOperand::In { .. }
461 | rustc_hir::InlineAsmOperand::Out { .. }
462 | rustc_hir::InlineAsmOperand::InOut { .. }
463 | rustc_hir::InlineAsmOperand::SplitInOut { .. }
464 | rustc_hir::InlineAsmOperand::Label { .. } => {
465 ::rustc_middle::util::bug::span_bug_fmt(*op_sp,
format_args!("invalid operand type for global_asm!"))span_bug!(*op_sp, "invalid operand type for global_asm!")
466 }
467 })
468 .collect();
469
470 cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans);
471 } else {
472 ::rustc_middle::util::bug::span_bug_fmt(item.span,
format_args!("Mismatch between hir::Item type and MonoItem type"))span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
473 }
474}
475
476pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
479 cx: &'a Bx::CodegenCx,
480 cgu: &CodegenUnit<'tcx>,
481) -> Option<Bx::Function> {
482 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
483 let main_is_local = main_def_id.is_local();
484 let instance = Instance::mono(cx.tcx(), main_def_id);
485
486 if main_is_local {
487 if !cgu.contains_item(&MonoItem::Fn(instance)) {
490 return None;
491 }
492 } else if !cgu.is_primary() {
493 return None;
495 }
496
497 let main_llfn = cx.get_fn_addr(instance, Some(PacMetadata::default()));
498
499 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
500 return Some(entry_fn);
501
502 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
503 cx: &'a Bx::CodegenCx,
504 rust_main: Bx::Value,
505 rust_main_def_id: DefId,
506 entry_type: EntryFnType,
507 ) -> Bx::Function {
508 let llfty = if cx.sess().target.os == Os::Uefi {
511 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
512 } else if cx.sess().target.main_needs_argc_argv {
513 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
514 } else {
515 cx.type_func(&[], cx.type_int())
516 };
517
518 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
519 let main_ret_ty = cx.tcx().normalize_erasing_regions(
525 cx.typing_env(),
526 Unnormalized::new_wip(main_ret_ty.no_bound_vars().unwrap()),
527 );
528
529 let Some(llfn) = cx.declare_c_main(llfty) else {
530 let span = cx.tcx().def_span(rust_main_def_id);
532 cx.tcx().dcx().emit_fatal(errors::MultipleMainFunctions { span });
533 };
534
535 cx.set_frame_pointer_type(llfn);
537 cx.apply_target_cpu_attr(llfn);
538
539 let llbb = Bx::append_block(cx, llfn, "top");
540 let mut bx = Bx::build(cx, llbb);
541
542 bx.insert_reference_to_gdb_debug_scripts_section_global();
543
544 let isize_ty = cx.type_isize();
545 let ptr_ty = cx.type_ptr();
546 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
547
548 let EntryFnType::Main { sigpipe } = entry_type;
549 let (start_fn, start_ty, args, instance) = {
550 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, DUMMY_SP);
551 let start_instance = ty::Instance::expect_resolve(
552 cx.tcx(),
553 cx.typing_env(),
554 start_def_id,
555 cx.tcx().mk_args(&[main_ret_ty.into()]),
556 DUMMY_SP,
557 );
558 let start_fn = cx.get_fn_addr(start_instance, Some(PacMetadata::default()));
559
560 let i8_ty = cx.type_i8();
561 let arg_sigpipe = bx.const_u8(sigpipe);
562
563 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
564 (
565 start_fn,
566 start_ty,
567 ::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],
568 Some(start_instance),
569 )
570 };
571
572 let result = bx.call(start_ty, None, None, start_fn, &args, None, instance);
573 if cx.sess().target.os == Os::Uefi {
574 bx.ret(result);
575 } else {
576 let cast = bx.intcast(result, cx.type_int(), true);
577 bx.ret(cast);
578 }
579
580 llfn
581 }
582}
583
584fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
587 if bx.cx().sess().target.os == Os::Uefi {
588 let param_handle = bx.get_param(0);
590 let param_system_table = bx.get_param(1);
591 let ptr_size = bx.tcx().data_layout.pointer_size();
592 let ptr_align = bx.tcx().data_layout.pointer_align().abi;
593 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
594 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
595 bx.store(param_handle, arg_argv, ptr_align);
596 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
597 bx.store(param_system_table, arg_argv_el1, ptr_align);
598 (arg_argc, arg_argv)
599 } else if bx.cx().sess().target.main_needs_argc_argv {
600 let param_argc = bx.get_param(0);
602 let param_argv = bx.get_param(1);
603 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
604 let arg_argv = param_argv;
605 (arg_argc, arg_argv)
606 } else {
607 let arg_argc = bx.const_int(bx.cx().type_int(), 0);
609 let arg_argv = bx.const_null(bx.cx().type_ptr());
610 (arg_argc, arg_argv)
611 }
612}
613
614pub fn collect_debugger_visualizers_transitive(
618 tcx: TyCtxt<'_>,
619 visualizer_type: DebuggerVisualizerType,
620) -> BTreeSet<DebuggerVisualizerFile> {
621 tcx.debugger_visualizers(LOCAL_CRATE)
622 .iter()
623 .chain(
624 tcx.crates(())
625 .iter()
626 .filter(|&cnum| {
627 let used_crate_source = tcx.used_crate_source(*cnum);
628 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
629 })
630 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
631 )
632 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
633 .cloned()
634 .collect::<BTreeSet<_>>()
635}
636
637pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
641 let all_crate_types_any_dynamic_crate = tcx.dependency_formats(()).iter().all(|(_, list)| {
651 use rustc_middle::middle::dependency_format::Linkage;
652 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
653 });
654 if all_crate_types_any_dynamic_crate { None } else { tcx.allocator_kind(()) }
655}
656
657pub(crate) fn needs_allocator_shim_for_linking(
661 dependency_formats: &Dependencies,
662 crate_type: CrateType,
663) -> bool {
664 use rustc_middle::middle::dependency_format::Linkage;
665 let any_dynamic_crate =
666 dependency_formats[&crate_type].iter().any(|&linkage| linkage == Linkage::Dynamic);
667 !any_dynamic_crate
668}
669
670pub fn allocator_shim_contents(tcx: TyCtxt<'_>, kind: AllocatorKind) -> Vec<AllocatorMethod> {
671 let mut methods = Vec::new();
672
673 if kind == AllocatorKind::Default {
674 methods.extend(ALLOCATOR_METHODS.into_iter().copied());
675 }
676
677 if tcx.alloc_error_handler_kind(()).unwrap() == AllocatorKind::Default {
680 methods.push(AllocatorMethod {
681 name: ALLOC_ERROR_HANDLER,
682 special: None,
683 inputs: &[AllocatorMethodInput { name: "layout", ty: AllocatorTy::Layout }],
684 output: AllocatorTy::Never,
685 });
686 }
687
688 methods
689}
690
691pub fn codegen_crate<
692 B: ExtraBackendMethods<Module = M> + WriteBackendMethods<Module = M>,
693 M: Send,
694>(
695 backend: B,
696 tcx: TyCtxt<'_>,
697) -> OngoingCodegen<B> {
698 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
699 tcx.dcx().emit_fatal(errors::CpuRequired);
701 }
702
703 if let Some(target_cpu) = &tcx.sess.opts.cg.target_cpu
704 && tcx.sess.target.unsupported_cpus.contains(&target_cpu.into())
705 {
706 tcx.dcx().emit_fatal(errors::CpuUnsupported { target_cpu: target_cpu.clone() });
708 }
709
710 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
711
712 let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());
715
716 if tcx.dep_graph.is_fully_enabled() {
722 for cgu in codegen_units {
723 tcx.ensure_ok().codegen_unit(cgu.name());
724 }
725 }
726
727 let allocator_module = if let Some(kind) = allocator_kind_for_codegen(tcx) {
729 let llmod_id =
730 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
731
732 tcx.sess.time("write_allocator_module", || {
733 let module =
734 backend.codegen_allocator(tcx, &llmod_id, &allocator_shim_contents(tcx, kind));
735 Some(ModuleCodegen::new_allocator(llmod_id, module))
736 })
737 } else {
738 None
739 };
740
741 let ongoing_codegen = start_async_codegen(backend.clone(), tcx, allocator_module);
742
743 let codegen_units: Vec<_> = {
755 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
756 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
757
758 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
759 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
760 };
761
762 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
764 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
765 });
766
767 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
768 for (i, cgu) in codegen_units.iter().enumerate() {
769 let cgu_reuse = cgu_reuse[i];
770 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
771 }
772 });
773
774 let mut total_codegen_time = Duration::new(0, 0);
775 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
776
777 let mut pre_compiled_cgus = if let Some(threads) = tcx.sess.threads() {
788 tcx.sess.time("compile_first_CGU_batch", || {
789 let cgus: Vec<_> = cgu_reuse
791 .iter()
792 .enumerate()
793 .filter(|&(_, reuse)| reuse == &CguReuse::No)
794 .take(threads)
795 .collect();
796
797 let start_time = Instant::now();
799
800 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
801 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
802 (i, IntoDynSyncSend(module))
803 });
804
805 total_codegen_time += start_time.elapsed();
806
807 pre_compiled_cgus
808 })
809 } else {
810 FxHashMap::default()
811 };
812
813 for (i, cgu) in codegen_units.iter().enumerate() {
814 ongoing_codegen.wait_for_signal_to_codegen_item();
815 ongoing_codegen.check_for_errors(tcx.sess);
816
817 let cgu_reuse = cgu_reuse[i];
818
819 match cgu_reuse {
820 CguReuse::No => {
821 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
822 cgu.0
823 } else {
824 let start_time = Instant::now();
825 let module = backend.compile_codegen_unit(tcx, cgu.name());
826 total_codegen_time += start_time.elapsed();
827 module
828 };
829 tcx.dcx().abort_if_errors();
833
834 submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);
835 }
836 CguReuse::PreLto => {
837 submit_pre_lto_module_to_llvm(
838 tcx,
839 &ongoing_codegen.coordinator,
840 CachedModuleCodegen {
841 name: cgu.name().to_string(),
842 source: cgu.previous_work_product(tcx),
843 },
844 );
845 }
846 CguReuse::PostLto => {
847 submit_post_lto_module_to_llvm(
848 &ongoing_codegen.coordinator,
849 CachedModuleCodegen {
850 name: cgu.name().to_string(),
851 source: cgu.previous_work_product(tcx),
852 },
853 );
854 }
855 }
856 }
857
858 ongoing_codegen.codegen_finished(tcx);
859
860 if tcx.sess.opts.unstable_opts.time_passes {
863 let end_rss = get_resident_set_size();
864
865 print_time_passes_entry(
866 "codegen_to_LLVM_IR",
867 total_codegen_time,
868 start_rss.unwrap(),
869 end_rss,
870 tcx.sess.opts.unstable_opts.time_passes_format,
871 );
872 }
873
874 ongoing_codegen.check_for_errors(tcx.sess);
875 ongoing_codegen
876}
877
878pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
892 tcx: TyCtxt<'tcx>,
893 instance: Instance<'tcx>,
894) -> bool {
895 fn is_llvm_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
896 if let Some(name) = tcx.codegen_fn_attrs(def_id).symbol_name {
897 name.as_str().starts_with("llvm.")
898 } else {
899 false
900 }
901 }
902
903 fn is_extern_call_to_local_crate<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool {
904 tcx.is_foreign_item(instance.def_id())
905 && tcx.exported_non_generic_symbols(LOCAL_CRATE).iter().any(|(sym, _info)| {
906 sym.symbol_name_for_local_instance(tcx) == tcx.symbol_name(instance)
907 })
908 }
909
910 let def_id = instance.def_id();
911 !def_id.is_local()
912 && tcx.is_compiler_builtins(LOCAL_CRATE)
913 && !is_llvm_intrinsic(tcx, def_id)
914 && !tcx.should_codegen_locally(instance)
915 && !is_extern_call_to_local_crate(tcx, instance)
916}
917
918fn collect_eii_linkage(tcx: TyCtxt<'_>) -> Vec<EiiLinkageInfo> {
919 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for FoundImpl {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "FoundImpl",
"imp", &self.imp, "impl_crate", &&self.impl_crate)
}
}Debug)]
920 struct FoundImpl {
921 imp: EiiImpl,
922 impl_crate: CrateNum,
923 }
924
925 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for FoundEii {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f, "FoundEii",
"decl", &self.decl, "impls", &&self.impls)
}
}Debug)]
926 struct FoundEii {
927 decl: EiiDecl,
928 impls: FxIndexMap<DefId, FoundImpl>,
929 }
930
931 let mut eiis = FxIndexMap::<DefId, FoundEii>::default();
932
933 for &cnum in tcx.crates(()).iter().chain(iter::once(&LOCAL_CRATE)) {
934 for (&did, &(decl, ref impls)) in tcx.externally_implementable_items(cnum) {
935 eiis.entry(did)
936 .or_insert_with(|| FoundEii { decl, impls: Default::default() })
937 .impls
938 .extend(
939 impls
940 .into_iter()
941 .map(|(&did, &imp)| (did, FoundImpl { imp, impl_crate: cnum })),
942 );
943 }
944 }
945
946 eiis.into_iter()
947 .filter_map(|(_, FoundEii { decl, impls })| {
948 let mut explicit_impls = Vec::new();
949 let mut default_impl = None;
950
951 for (impl_did, FoundImpl { imp, impl_crate }) in impls {
952 let impl_info = EiiLinkageImplInfo { span: tcx.def_span(impl_did), impl_crate };
953 if imp.is_default {
954 default_impl = Some(impl_info);
955 } else {
956 explicit_impls.push(impl_info);
957 }
958 }
959
960 if let Some(default_impl) = default_impl {
963 Some(EiiLinkageInfo {
964 name: decl.name.name,
965 impls: explicit_impls,
966 default_impl: Some(default_impl),
967 })
968 } else {
969 None
970 }
971 })
972 .collect()
973}
974
975fn eii_linkage_needed(dependency_formats: &Dependencies) -> bool {
976 dependency_formats.values().any(|formats| {
977 formats
978 .iter()
979 .any(|&linkage| #[allow(non_exhaustive_omitted_patterns)] match linkage {
Linkage::Dynamic | Linkage::IncludedFromDylib => true,
_ => false,
}matches!(linkage, Linkage::Dynamic | Linkage::IncludedFromDylib))
980 })
981}
982
983impl CrateInfo {
984 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
985 let crate_types = tcx.crate_types().to_vec();
986 let exported_symbols = crate_types
987 .iter()
988 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
989 .collect();
990 let linked_symbols =
991 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
992 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
993 let windows_subsystem = {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(WindowsSubsystem(kind)) => {
break 'done Some(*kind);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(tcx, crate, WindowsSubsystem(kind) => *kind);
994 let dependency_formats = Arc::clone(tcx.dependency_formats(()));
995 let eii_linkage = if eii_linkage_needed(&dependency_formats) {
996 collect_eii_linkage(tcx)
997 } else {
998 Vec::new()
999 };
1000
1001 let mut compiler_builtins = None;
1010 let mut used_crates: Vec<_> = tcx
1011 .postorder_cnums(())
1012 .iter()
1013 .rev()
1014 .copied()
1015 .filter(|&cnum| {
1016 let link = !tcx.crate_dep_kind(cnum).macros_only();
1017 if link && tcx.is_compiler_builtins(cnum) {
1018 compiler_builtins = Some(cnum);
1019 return false;
1020 }
1021 link
1022 })
1023 .collect();
1024 used_crates.extend(compiler_builtins);
1026
1027 let crates = tcx.crates(());
1028 let n_crates = crates.len();
1029 let mut info = CrateInfo {
1030 target_cpu,
1031 target_features: tcx.global_backend_features(()).clone(),
1032 crate_types,
1033 exported_symbols,
1034 linked_symbols,
1035 local_crate_name,
1036 compiler_builtins,
1037 profiler_runtime: None,
1038 is_no_builtins: Default::default(),
1039 native_libraries: Default::default(),
1040 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
1041 crate_name: UnordMap::with_capacity(n_crates),
1042 used_crates,
1043 used_crate_source: UnordMap::with_capacity(n_crates),
1044 dependency_formats,
1045 eii_linkage,
1046 windows_subsystem,
1047 natvis_debugger_visualizers: Default::default(),
1048 lint_level_specs: CodegenLintLevelSpecs::from_tcx(tcx),
1049 metadata_symbol: exported_symbols::metadata_symbol_name(tcx),
1050 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)),
1051 each_linked_rlib_file_for_lto: Default::default(),
1052 exported_symbols_for_lto: Default::default(),
1053 };
1054
1055 info.native_libraries.reserve(n_crates);
1056
1057 for &cnum in crates.iter() {
1058 info.native_libraries
1059 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
1060 info.crate_name.insert(cnum, tcx.crate_name(cnum));
1061
1062 let used_crate_source = tcx.used_crate_source(cnum);
1063 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
1064 if tcx.is_profiler_runtime(cnum) {
1065 info.profiler_runtime = Some(cnum);
1066 }
1067 if tcx.is_no_builtins(cnum) {
1068 info.is_no_builtins.insert(cnum);
1069 }
1070 }
1071
1072 let target = &tcx.sess.target;
1081 if !are_upstream_rust_objects_already_included(tcx.sess) {
1082 let add_prefix = match (target.is_like_windows, &target.arch) {
1083 (true, Arch::X86) => |name: String, _: SymbolExportKind| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_{0}", name))
})format!("_{name}"),
1084 (true, Arch::Arm64EC) => {
1085 |name: String, export_kind: SymbolExportKind| match export_kind {
1087 SymbolExportKind::Text => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#{0}", name))
})format!("#{name}"),
1088 _ => name,
1089 }
1090 }
1091 _ => |name: String, _: SymbolExportKind| name,
1092 };
1093 let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info
1094 .used_crates
1095 .iter()
1096 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
1097 .filter(|l| l.is_weak())
1098 .filter_map(|&l| {
1099 let name = l.link_name()?;
1100 let export_kind = match l.target() {
1101 Target::ForeignFn | Target::Fn => SymbolExportKind::Text,
1102 Target::Static => SymbolExportKind::Data,
1103 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Don\'t know what the export kind is for lang item of kind {0:?}",
l.target()))bug!(
1104 "Don't know what the export kind is for lang item of kind {:?}",
1105 l.target()
1106 ),
1107 };
1108 lang_items::required(tcx, l).then_some((name, export_kind))
1109 })
1110 .collect();
1111
1112 #[allow(rustc::potential_query_instability)]
1115 info.linked_symbols
1116 .iter_mut()
1117 .filter(|(crate_type, _)| {
1118 !#[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib)
1119 })
1120 .for_each(|(_, linked_symbols)| {
1121 let mut symbols = missing_weak_lang_items
1122 .iter()
1123 .map(|(item, export_kind)| {
1124 (
1125 add_prefix(
1126 mangle_internal_symbol(tcx, item.as_str()),
1127 *export_kind,
1128 ),
1129 *export_kind,
1130 )
1131 })
1132 .collect::<Vec<_>>();
1133 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1134 linked_symbols.extend(symbols);
1135 });
1136 }
1137
1138 let mut each_linked_rlib_for_lto = Vec::new();
1139 let mut each_linked_rlib_file_for_lto = Vec::new();
1140 if tcx.sess.lto() != config::Lto::No && tcx.sess.lto() != config::Lto::ThinLocal {
1141 drop(crate::back::link::each_linked_rlib(&info, None, &mut |cnum, path| {
1142 if crate::back::link::ignored_for_lto(tcx.sess, &info, cnum) {
1143 return;
1144 }
1145
1146 each_linked_rlib_for_lto.push(cnum);
1147 each_linked_rlib_file_for_lto.push(path.to_path_buf());
1148 }));
1149 }
1150 info.each_linked_rlib_file_for_lto = each_linked_rlib_file_for_lto;
1151
1152 info.exported_symbols_for_lto =
1155 crate::back::lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto);
1156
1157 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1158 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1159 true
1162 }
1163 CrateType::ProcMacro => {
1164 false
1168 }
1169 CrateType::StaticLib | CrateType::Rlib => {
1170 false
1173 }
1174 });
1175
1176 if target.is_like_msvc && embed_visualizers {
1177 info.natvis_debugger_visualizers =
1178 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1179 }
1180
1181 info
1182 }
1183}
1184
1185pub(crate) fn provide(providers: &mut Providers) {
1186 providers.backend_optimization_level = |tcx, cratenum| {
1187 let for_speed = match tcx.sess.opts.optimize {
1188 config::OptLevel::No => return config::OptLevel::No,
1195 config::OptLevel::Less => return config::OptLevel::Less,
1197 config::OptLevel::More => return config::OptLevel::More,
1198 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1199 config::OptLevel::Size => config::OptLevel::More,
1202 config::OptLevel::SizeMin => config::OptLevel::More,
1203 };
1204
1205 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1206
1207 let any_for_speed = defids.items().any(|id| {
1208 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1209 #[allow(non_exhaustive_omitted_patterns)] match optimize {
OptimizeAttr::Speed => true,
_ => false,
}matches!(optimize, OptimizeAttr::Speed)
1210 });
1211
1212 if any_for_speed {
1213 return for_speed;
1214 }
1215
1216 tcx.sess.opts.optimize
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 return CguReuse::No;
1232 }
1233
1234 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 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}