1use std::collections::BTreeSet;
2use std::sync::Arc;
3use std::time::{Duration, Instant};
4use std::{cmp, iter};
5
6use itertools::Itertools;
7use rustc_abi::FIRST_VARIANT;
8use rustc_ast::expand::allocator::{
9 ALLOC_ERROR_HANDLER, ALLOCATOR_METHODS, AllocatorKind, AllocatorMethod, AllocatorMethodInput,
10 AllocatorTy,
11};
12use rustc_attr_ir::lang_items::LangItem;
13use rustc_attr_ir::target::Target;
14use rustc_attr_ir::{DebuggerVisualizerType, EiiDecl, EiiImpl, OptimizeAttr, find_attr};
15use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
16use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
17use rustc_data_structures::sync::{IntoDynSyncSend, par_map};
18use rustc_data_structures::unord::UnordMap;
19use rustc_hir as hir;
20use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
21use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
22use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
23use rustc_middle::middle::dependency_format::{Dependencies, Linkage};
24use rustc_middle::middle::exported_symbols::{self, SymbolExportKind};
25use rustc_middle::middle::lang_items;
26use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, ErrorHandled, Scalar};
27use rustc_middle::mir::{BinOp, ConstValue};
28use rustc_middle::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem, MonoItemPartitions};
29use rustc_middle::query::Providers;
30use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
31use rustc_middle::ty::{self, Instance, PatternKind, Ty, TyCtxt, UintTy, Unnormalized};
32use rustc_session::config::{self, EntryFnType};
33use rustc_span::{DUMMY_SP, Symbol, bug, span_bug};
34use rustc_structures::CrateType;
35use rustc_symbol_mangling::mangle_internal_symbol;
36use rustc_target::spec::{Arch, Os, Target as TargetSpec};
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, ModuleConfig, 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};
48use crate::meth::VirtualIndex;
49use crate::mir::operand::OperandValue;
50use crate::mir::place::PlaceRef;
51use crate::traits::*;
52use crate::{
53 CachedModuleCodegen, CodegenLintLevelSpecs, CrateInfo, EiiLinkageImplInfo, EiiLinkageInfo,
54 ModuleCodegen, ModuleKind, diagnostics, 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_span::macros::bug_impl(None,
format_args!("bin_op_to_icmp_predicate: expected comparison operator, found {0:?}",
op), Location::caller())bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),
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_span::macros::bug_impl(None,
format_args!("bin_op_to_fcmp_predicate: expected comparison operator, found {0:?}",
op), Location::caller())bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),
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_span::macros::bug_impl(None,
format_args!("compare_simd_types: invalid SIMD type"), Location::caller())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().no_errors() {
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.map(VirtualIndex::from_index) {
206 entry_idx.get_data_ptr(bx, old_info, true)
207 } else {
208 old_info
209 }
210 }
211 (_, ty::Dynamic(data, _)) => meth::get_vtable(
212 cx,
213 source,
214 data.principal()
215 .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),
216 ),
217 _ => ::rustc_span::macros::bug_impl(None,
format_args!("unsized_info: invalid unsizing {0:?} -> {1:?}", source,
target), Location::caller())bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
218 }
219}
220
221pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
223 bx: &mut Bx,
224 src: Bx::Value,
225 src_ty: Ty<'tcx>,
226 dst_ty: Ty<'tcx>,
227 old_info: Option<Bx::Value>,
228) -> (Bx::Value, Bx::Value) {
229 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/base.rs:229",
"rustc_codegen_ssa::base", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/base.rs"),
::tracing_core::__macro_support::Option::Some(229u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::base"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("unsize_ptr: {0:?} => {1:?}",
src_ty, dst_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
230 match (src_ty.kind(), dst_ty.kind()) {
231 (&ty::Pat(a, _), &ty::Pat(b, _)) => unsize_ptr(bx, src, a, b, old_info),
232 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
233 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
234 {
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());
235 (src, unsized_info(bx, a, b, old_info))
236 }
237 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
238 {
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);
240 let dst_layout = bx.cx().layout_of(dst_ty);
241 if src_ty == dst_ty {
242 return (src, old_info.unwrap());
243 }
244 let mut result = None;
245 for i in 0..src_layout.fields.count() {
246 let src_f = src_layout.field(bx.cx(), i);
247 if src_f.is_1zst() {
248 continue;
250 }
251
252 {
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);
253 {
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);
254 {
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);
255
256 let dst_f = dst_layout.field(bx.cx(), i);
257 {
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);
258 {
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);
259 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
260 }
261 result.unwrap()
262 }
263 _ => ::rustc_span::macros::bug_impl(None,
format_args!("unsize_ptr: called on bad types"), Location::caller())bug!("unsize_ptr: called on bad types"),
264 }
265}
266
267pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
270 bx: &mut Bx,
271 src: PlaceRef<'tcx, Bx::Value>,
272 dst: PlaceRef<'tcx, Bx::Value>,
273) {
274 let src_ty = src.layout.ty;
275 let dst_ty = dst.layout.ty;
276 match (src_ty.kind(), dst_ty.kind()) {
277 (&ty::Pat(s, sp), &ty::Pat(d, dp))
278 if let (PatternKind::NotNull, PatternKind::NotNull) = (*sp, *dp) =>
279 {
280 let src = src.project_type(bx, s);
281 let dst = dst.project_type(bx, d);
282 coerce_unsized_into(bx, src, dst)
283 }
284 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
285 let (base, info) = match bx.load_operand(src).val {
286 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
287 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
288 OperandValue::Ref(..) | OperandValue::ZeroSized => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
Location::caller())bug!(),
289 };
290 OperandValue::Pair(base, info).store(bx, dst);
291 }
292
293 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
294 {
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() {
297 let src_f = src.project_field(bx, i.as_usize());
298 let dst_f = dst.project_field(bx, i.as_usize());
299
300 if dst_f.layout.is_zst() {
301 continue;
303 }
304
305 if src_f.layout.ty == dst_f.layout.ty {
306 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
307 } else {
308 coerce_unsized_into(bx, src_f, dst_f);
309 }
310 }
311 }
312 _ => ::rustc_span::macros::bug_impl(None,
format_args!("coerce_unsized_into: invalid coercion {0:?} -> {1:?}",
src_ty, dst_ty), Location::caller())bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
313 }
314}
315
316pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
332 bx: &mut Bx,
333 lhs: Bx::Value,
334 mut rhs: Bx::Value,
335 is_unchecked: bool,
336) -> Bx::Value {
337 let mut rhs_llty = bx.cx().val_ty(rhs);
339 let mut lhs_llty = bx.cx().val_ty(lhs);
340
341 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
342 if !is_unchecked {
343 rhs = bx.and(rhs, mask);
344 }
345
346 if let Some(element) = bx.cx().vector_element_type(rhs_llty) {
347 rhs_llty = element;
348 }
349 if let Some(element) = bx.cx().vector_element_type(lhs_llty) {
350 lhs_llty = element;
351 }
352 let rhs_sz = bx.cx().int_width(rhs_llty).expect("rhs is not an integer");
353 let lhs_sz = bx.cx().int_width(lhs_llty).expect("lhs is not an integer");
354 if lhs_sz < rhs_sz {
355 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
356 } else if lhs_sz > rhs_sz {
357 if !(lhs_sz <= 256) {
::core::panicking::panic("assertion failed: lhs_sz <= 256")
};assert!(lhs_sz <= 256);
364 bx.zext(rhs, lhs_llty)
365 } else {
366 rhs
367 }
368}
369
370pub fn wants_wasm_eh(target: &TargetSpec) -> bool {
374 target.is_like_wasm
375}
376
377pub fn wants_msvc_seh(target: &TargetSpec) -> bool {
383 target.is_like_msvc
384}
385
386pub(crate) fn wants_new_eh_instructions(target: &TargetSpec) -> bool {
390 wants_wasm_eh(target) || wants_msvc_seh(target)
391}
392
393pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
394 cx: &'a Bx::CodegenCx,
395 instance: Instance<'tcx>,
396) {
397 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/base.rs:400",
"rustc_codegen_ssa::base", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/249c1e4e31111b54ad2483cfd4cea06c7020c653/compiler/rustc_codegen_ssa/src/base.rs"),
::tracing_core::__macro_support::Option::Some(400u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::base"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("codegen_instance({0})",
instance) as &dyn ::tracing::field::Value))])
});
} else { ; }
};info!("codegen_instance({})", instance);
401
402 mir::codegen_mir::<Bx>(cx, instance);
403}
404
405pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: hir::ItemId)
406where
407 Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + AsmCodegenMethods<'tcx>,
408{
409 let item = cx.tcx().hir_item(item_id);
410 if let rustc_hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
411 let operands: Vec<_> = asm
412 .operands
413 .iter()
414 .map(|(op, op_sp)| match *op {
415 rustc_hir::InlineAsmOperand::Const { ref anon_const } => {
416 match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) {
417 Ok(const_value) => {
418 let ty =
419 cx.tcx().typeck_body(anon_const.body).node_type(anon_const.hir_id);
420 let ConstValue::Scalar(scalar) = const_value else {
421 ::rustc_span::macros::bug_impl(Some(*op_sp),
format_args!("expected Scalar for promoted asm const, but got {0:#?}",
const_value), Location::caller())span_bug!(
422 *op_sp,
423 "expected Scalar for promoted asm const, but got {:#?}",
424 const_value
425 )
426 };
427 GlobalAsmOperandRef::Const {
428 value: common::asm_const_ptr_clean(cx.tcx(), scalar),
429 ty,
430 }
431 }
432 Err(ErrorHandled::Reported { .. }) => {
433 GlobalAsmOperandRef::Const {
437 value: Scalar::from_u32(0),
438 ty: Ty::new_uint(cx.tcx(), UintTy::U32),
439 }
440 }
441 Err(ErrorHandled::TooGeneric(_)) => {
442 ::rustc_span::macros::bug_impl(Some(*op_sp),
format_args!("asm const cannot be resolved; too generic"),
Location::caller())span_bug!(*op_sp, "asm const cannot be resolved; too generic")
443 }
444 }
445 }
446 rustc_hir::InlineAsmOperand::SymFn { expr } => {
447 let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
448 let instance = match ty.kind() {
449 &ty::FnDef(def_id, args) => Instance::expect_resolve(
450 cx.tcx(),
451 cx.typing_env(),
452 def_id,
453 args.no_bound_vars().unwrap(),
454 expr.span,
455 ),
456 _ => ::rustc_span::macros::bug_impl(Some(*op_sp),
format_args!("asm sym is not a function"), Location::caller())span_bug!(*op_sp, "asm sym is not a function"),
457 };
458
459 GlobalAsmOperandRef::Const {
460 value: Scalar::from_pointer(
461 cx.tcx().reserve_and_set_fn_alloc(instance, CTFE_ALLOC_SALT).into(),
462 cx,
463 ),
464 ty: Ty::new_fn_ptr(cx.tcx(), ty.fn_sig(cx.tcx())),
465 }
466 }
467 rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
468 if cx.tcx().is_thread_local_static(def_id) {
469 GlobalAsmOperandRef::SymThreadLocalStatic { def_id }
470 } else {
471 GlobalAsmOperandRef::Const {
472 value: Scalar::from_pointer(
473 cx.tcx().reserve_and_set_static_alloc(def_id).into(),
474 cx,
475 ),
476 ty: cx.tcx().static_ptr_ty(def_id, cx.typing_env()),
477 }
478 }
479 }
480 rustc_hir::InlineAsmOperand::In { .. }
481 | rustc_hir::InlineAsmOperand::Out { .. }
482 | rustc_hir::InlineAsmOperand::InOut { .. }
483 | rustc_hir::InlineAsmOperand::SplitInOut { .. }
484 | rustc_hir::InlineAsmOperand::Label { .. } => {
485 ::rustc_span::macros::bug_impl(Some(*op_sp),
format_args!("invalid operand type for global_asm!"), Location::caller())span_bug!(*op_sp, "invalid operand type for global_asm!")
486 }
487 })
488 .collect();
489
490 cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans, &[]);
491 } else {
492 ::rustc_span::macros::bug_impl(Some(item.span),
format_args!("Mismatch between hir::Item type and MonoItem type"),
Location::caller())span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
493 }
494}
495
496pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
499 cx: &'a Bx::CodegenCx,
500 cgu: &CodegenUnit<'tcx>,
501) -> Option<Bx::Function> {
502 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
503 let main_is_local = main_def_id.is_local();
504 let instance = Instance::mono(cx.tcx(), main_def_id);
505
506 if main_is_local {
507 if !cgu.contains_item(&MonoItem::Fn(instance)) {
510 return None;
511 }
512 } else if !cgu.is_primary() {
513 return None;
515 }
516
517 let main_llfn = cx.get_fn_addr(instance, cx.sess().pointer_authentication_functions());
518
519 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
520 return Some(entry_fn);
521
522 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
523 cx: &'a Bx::CodegenCx,
524 rust_main: Bx::Value,
525 rust_main_def_id: DefId,
526 entry_type: EntryFnType,
527 ) -> Bx::Function {
528 let llfty = if cx.sess().target.os == Os::Uefi {
531 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
532 } else if cx.sess().target.main_needs_argc_argv {
533 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
534 } else {
535 cx.type_func(&[], cx.type_int())
536 };
537
538 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
539 let main_ret_ty = cx.tcx().normalize_erasing_regions(
545 cx.typing_env(),
546 Unnormalized::new_wip(main_ret_ty.no_bound_vars().unwrap()),
547 );
548
549 let Some(llfn) = cx.declare_c_main(llfty) else {
550 let span = cx.tcx().def_span(rust_main_def_id);
552 cx.tcx().dcx().emit_fatal(diagnostics::MultipleMainFunctions { span });
553 };
554
555 cx.set_frame_pointer_type(llfn);
557 cx.apply_target_cpu_attr(llfn);
558
559 let llbb = Bx::append_block(cx, llfn, "top");
560 let mut bx = Bx::build(cx, llbb);
561
562 bx.insert_reference_to_gdb_debug_scripts_section_global();
563
564 let isize_ty = cx.type_isize();
565 let ptr_ty = cx.type_ptr();
566 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
567
568 let EntryFnType::Main { sigpipe } = entry_type;
569 let (start_fn, start_ty, args, instance) = {
570 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, DUMMY_SP);
571 let start_instance = ty::Instance::expect_resolve(
572 cx.tcx(),
573 cx.typing_env(),
574 start_def_id,
575 cx.tcx().mk_args(&[main_ret_ty.into()]),
576 DUMMY_SP,
577 );
578 let start_fn =
579 cx.get_fn_addr(start_instance, cx.sess().pointer_authentication_functions());
580
581 let i8_ty = cx.type_i8();
582 let arg_sigpipe = bx.const_u8(sigpipe);
583
584 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
585 (
586 start_fn,
587 start_ty,
588 ::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],
589 Some(start_instance),
590 )
591 };
592
593 let result =
594 bx.call(start_ty, None, None, start_fn, ReturnSlot::Direct, &args, None, instance);
595 if cx.sess().target.os == Os::Uefi {
596 bx.ret(result);
597 } else {
598 let cast = bx.intcast(result, cx.type_int(), true);
599 bx.ret(cast);
600 }
601
602 llfn
603 }
604}
605
606fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
609 if bx.cx().sess().target.os == Os::Uefi {
610 let param_handle = bx.get_param(0);
612 let param_system_table = bx.get_param(1);
613 let ptr_size = bx.tcx().data_layout.pointer_size();
614 let ptr_align = bx.tcx().data_layout.pointer_align();
615 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
616 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
617 bx.store(param_handle, arg_argv, ptr_align);
618 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
619 bx.store(param_system_table, arg_argv_el1, ptr_align);
620 (arg_argc, arg_argv)
621 } else if bx.cx().sess().target.main_needs_argc_argv {
622 let param_argc = bx.get_param(0);
624 let param_argv = bx.get_param(1);
625 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
626 let arg_argv = param_argv;
627 (arg_argc, arg_argv)
628 } else {
629 let arg_argc = bx.const_int(bx.cx().type_int(), 0);
631 let arg_argv = bx.const_null(bx.cx().type_ptr());
632 (arg_argc, arg_argv)
633 }
634}
635
636pub fn collect_debugger_visualizers_transitive(
640 tcx: TyCtxt<'_>,
641 visualizer_type: DebuggerVisualizerType,
642) -> BTreeSet<DebuggerVisualizerFile> {
643 tcx.debugger_visualizers(LOCAL_CRATE)
644 .iter()
645 .chain(
646 tcx.crates(())
647 .iter()
648 .filter(|&cnum| {
649 let used_crate_source = tcx.used_crate_source(*cnum);
650 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
651 })
652 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
653 )
654 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
655 .cloned()
656 .collect::<BTreeSet<_>>()
657}
658
659pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
663 let all_crate_types_any_dynamic_crate = tcx.dependency_formats(()).iter().all(|(_, list)| {
673 use rustc_middle::middle::dependency_format::Linkage;
674 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
675 });
676 if all_crate_types_any_dynamic_crate { None } else { tcx.allocator_kind(()) }
677}
678
679pub(crate) fn needs_allocator_shim_for_linking(
683 dependency_formats: &Dependencies,
684 crate_type: CrateType,
685) -> bool {
686 use rustc_middle::middle::dependency_format::Linkage;
687 let any_dynamic_crate =
688 dependency_formats[&crate_type].iter().any(|&linkage| linkage == Linkage::Dynamic);
689 !any_dynamic_crate
690}
691
692pub fn allocator_shim_contents(tcx: TyCtxt<'_>, kind: AllocatorKind) -> Vec<AllocatorMethod> {
693 let mut methods = Vec::new();
694
695 if kind == AllocatorKind::Default {
696 methods.extend(ALLOCATOR_METHODS.into_iter().copied());
697 }
698
699 if tcx.alloc_error_handler_kind(()).unwrap() == AllocatorKind::Default {
702 methods.push(AllocatorMethod {
703 name: ALLOC_ERROR_HANDLER,
704 special: None,
705 inputs: &[AllocatorMethodInput { name: "layout", ty: AllocatorTy::Layout }],
706 output: AllocatorTy::Never,
707 });
708 }
709
710 methods
711}
712
713pub fn codegen_crate<
714 B: ExtraBackendMethods<Module = M> + WriteBackendMethods<Module = M>,
715 M: Send,
716>(
717 backend: B,
718 tcx: TyCtxt<'_>,
719) -> OngoingCodegen<B> {
720 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
721 tcx.dcx().emit_fatal(diagnostics::CpuRequired);
723 }
724
725 if let Some(target_cpu) = &tcx.sess.opts.cg.target_cpu
726 && tcx.sess.target.unsupported_cpus.contains(&target_cpu.into())
727 {
728 tcx.dcx().emit_fatal(diagnostics::CpuUnsupported { target_cpu: target_cpu.clone() });
730 }
731
732 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
733
734 let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());
737
738 if tcx.dep_graph.is_fully_enabled() {
744 for cgu in codegen_units {
745 tcx.ensure_ok().codegen_unit(cgu.name());
746 }
747 }
748
749 let allocator_module = if let Some(kind) = allocator_kind_for_codegen(tcx) {
751 let llmod_id =
752 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
753
754 tcx.sess.time("write_allocator_module", || {
755 let module =
756 backend.codegen_allocator(tcx, &llmod_id, &allocator_shim_contents(tcx, kind));
757 Some(ModuleCodegen::new_allocator(llmod_id, module))
758 })
759 } else {
760 None
761 };
762
763 let no_builtins = {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NoBuiltins) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(tcx, crate, NoBuiltins);
764 let regular_module_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
765 let bitcode_needed = regular_module_config.bitcode_needed();
766 let allocator_module_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
767
768 let ongoing_codegen = start_async_codegen(
769 backend.clone(),
770 tcx,
771 Arc::new(regular_module_config),
772 Arc::new(allocator_module_config),
773 allocator_module,
774 );
775
776 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 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 let mut pre_compiled_cgus = if let Some(threads) = tcx.sess.opts.jobs.frontend {
821 tcx.sess.time("compile_first_CGU_batch", || {
822 let cgus: Vec<_> = cgu_reuse
824 .iter()
825 .enumerate()
826 .filter(|&(_, reuse)| reuse == &CguReuse::No)
827 .take(threads.get())
828 .collect();
829
830 let start_time = Instant::now();
832
833 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
834 let module =
835 backend.compile_codegen_unit(tcx, codegen_units[i].name(), bitcode_needed);
836 (i, IntoDynSyncSend(module))
837 });
838
839 total_codegen_time += start_time.elapsed();
840
841 pre_compiled_cgus
842 })
843 } else {
844 FxHashMap::default()
845 };
846
847 for (i, cgu) in codegen_units.iter().enumerate() {
848 ongoing_codegen.wait_for_signal_to_codegen_item();
849 ongoing_codegen.check_for_errors(tcx.sess);
850
851 let cgu_reuse = cgu_reuse[i];
852
853 match cgu_reuse {
854 CguReuse::No => {
855 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
856 cgu.0
857 } else {
858 let start_time = Instant::now();
859 let module = backend.compile_codegen_unit(tcx, cgu.name(), bitcode_needed);
860 total_codegen_time += start_time.elapsed();
861 module
862 };
863 tcx.dcx().abort_if_errors();
867
868 submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);
869 }
870 CguReuse::PreLto => {
871 submit_pre_lto_module_to_llvm(
872 tcx,
873 &ongoing_codegen.coordinator,
874 CachedModuleCodegen {
875 name: cgu.name().to_string(),
876 source: cgu.previous_work_product(tcx),
877 },
878 );
879 tcx.dcx().abort_if_errors();
883 }
884 CguReuse::PostLto => {
885 submit_post_lto_module_to_llvm(
886 &ongoing_codegen.coordinator,
887 CachedModuleCodegen {
888 name: cgu.name().to_string(),
889 source: cgu.previous_work_product(tcx),
890 },
891 );
892 }
893 }
894 }
895
896 ongoing_codegen.codegen_finished(tcx);
897
898 if tcx.sess.opts.unstable_opts.time_passes {
901 let end_rss = get_resident_set_size();
902
903 print_time_passes_entry(
904 "codegen_to_LLVM_IR",
905 total_codegen_time,
906 start_rss.unwrap(),
907 end_rss,
908 tcx.sess.opts.unstable_opts.time_passes_format,
909 );
910 }
911
912 ongoing_codegen.check_for_errors(tcx.sess);
913 ongoing_codegen
914}
915
916pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
930 tcx: TyCtxt<'tcx>,
931 instance: Instance<'tcx>,
932) -> bool {
933 if let ty::InstanceKind::LlvmIntrinsic(_) = instance.def {
934 return false;
935 }
936
937 fn is_extern_call_to_local_crate<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool {
938 tcx.is_foreign_item(instance.def_id())
939 && tcx.exported_non_generic_symbols(LOCAL_CRATE).iter().any(|(sym, _info)| {
940 sym.symbol_name_for_local_instance(tcx) == tcx.symbol_name(instance)
941 })
942 }
943
944 let def_id = instance.def_id();
945 !def_id.is_local()
946 && tcx.is_compiler_builtins(LOCAL_CRATE)
947 && !tcx.should_codegen_locally(instance)
948 && !is_extern_call_to_local_crate(tcx, instance)
949}
950
951fn collect_eii_linkage(tcx: TyCtxt<'_>) -> Vec<EiiLinkageInfo> {
952 #[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 impl_crate", &self.imp, &&self.impl_crate)
}
}Debug)]
953 struct FoundImpl {
954 imp: EiiImpl,
955 impl_crate: CrateNum,
956 }
957
958 #[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 impls", &self.decl, &&self.impls)
}
}Debug)]
959 struct FoundEii {
960 decl: EiiDecl,
961 impls: FxIndexMap<DefId, FoundImpl>,
962 }
963
964 let mut eiis = FxIndexMap::<DefId, FoundEii>::default();
965
966 for &cnum in tcx.crates(()).iter().chain(iter::once(&LOCAL_CRATE)) {
967 for (&did, &(decl, ref impls)) in tcx.externally_implementable_items(cnum) {
968 eiis.entry(did)
969 .or_insert_with(|| FoundEii { decl, impls: Default::default() })
970 .impls
971 .extend(
972 impls
973 .into_iter()
974 .map(|(&did, &imp)| (did, FoundImpl { imp, impl_crate: cnum })),
975 );
976 }
977 }
978
979 eiis.into_iter()
980 .filter_map(|(_, FoundEii { decl, impls })| {
981 let mut explicit_impls = Vec::new();
982 let mut default_impl = None;
983
984 for (impl_did, FoundImpl { imp, impl_crate }) in impls {
985 let impl_info = EiiLinkageImplInfo { span: tcx.def_span(impl_did), impl_crate };
986 if imp.is_default {
987 default_impl = Some(impl_info);
988 } else {
989 explicit_impls.push(impl_info);
990 }
991 }
992
993 if let Some(default_impl) = default_impl {
996 Some(EiiLinkageInfo {
997 name: decl.name.name,
998 impls: explicit_impls,
999 default_impl: Some(default_impl),
1000 })
1001 } else {
1002 None
1003 }
1004 })
1005 .collect()
1006}
1007
1008fn eii_linkage_needed(dependency_formats: &Dependencies) -> bool {
1009 dependency_formats.values().any(|formats| {
1010 formats
1011 .iter()
1012 .any(|&linkage| #[allow(non_exhaustive_omitted_patterns)] match linkage {
Linkage::Dynamic | Linkage::IncludedFromDylib => true,
_ => false,
}matches!(linkage, Linkage::Dynamic | Linkage::IncludedFromDylib))
1013 })
1014}
1015
1016impl CrateInfo {
1017 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
1018 let crate_types = tcx.crate_types().to_vec();
1019 let exported_symbols = crate_types
1020 .iter()
1021 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
1022 .collect();
1023 let linked_symbols =
1024 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
1025 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
1026 let windows_subsystem = {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(WindowsSubsystem(kind)) =>
{
break 'done Some(*kind);
}
::rustc_attr_ir::Attribute::Tool(..) |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(tcx, crate, WindowsSubsystem(kind) => *kind);
1027 let dependency_formats = Arc::clone(tcx.dependency_formats(()));
1028 let eii_linkage = if eii_linkage_needed(&dependency_formats) {
1029 collect_eii_linkage(tcx)
1030 } else {
1031 Vec::new()
1032 };
1033
1034 let mut compiler_builtins = None;
1043 let mut used_crates: Vec<_> = tcx
1044 .postorder_cnums(())
1045 .iter()
1046 .rev()
1047 .copied()
1048 .filter(|&cnum| {
1049 let link = !tcx.crate_dep_kind(cnum).macros_only();
1050 if link && tcx.is_compiler_builtins(cnum) {
1051 compiler_builtins = Some(cnum);
1052 return false;
1053 }
1054 link
1055 })
1056 .collect();
1057 used_crates.extend(compiler_builtins);
1059
1060 let crates = tcx.crates(());
1061 let n_crates = crates.len();
1062 let mut info = CrateInfo {
1063 target_cpu,
1064 target_features: tcx.sess.global_backend_features.clone(),
1065 crate_types,
1066 exported_symbols,
1067 linked_symbols,
1068 local_crate_name,
1069 compiler_builtins,
1070 profiler_runtime: None,
1071 is_no_builtins: Default::default(),
1072 native_libraries: Default::default(),
1073 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
1074 crate_name: UnordMap::with_capacity(n_crates),
1075 used_crates,
1076 used_crate_source: UnordMap::with_capacity(n_crates),
1077 dependency_formats,
1078 eii_linkage,
1079 windows_subsystem,
1080 natvis_debugger_visualizers: Default::default(),
1081 lint_level_specs: CodegenLintLevelSpecs::from_tcx(tcx),
1082 metadata_symbol: exported_symbols::metadata_symbol_name(tcx),
1083 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)),
1084 each_linked_rlib_file_for_lto: Default::default(),
1085 exported_symbols_for_lto: Default::default(),
1086 };
1087
1088 info.native_libraries.reserve(n_crates);
1089
1090 for &cnum in crates.iter() {
1091 info.native_libraries
1092 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
1093 info.crate_name.insert(cnum, tcx.crate_name(cnum));
1094
1095 let used_crate_source = tcx.used_crate_source(cnum);
1096 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
1097 if tcx.is_profiler_runtime(cnum) {
1098 info.profiler_runtime = Some(cnum);
1099 }
1100 if tcx.is_no_builtins(cnum) {
1101 info.is_no_builtins.insert(cnum);
1102 }
1103 }
1104
1105 let target = &tcx.sess.target;
1114 if !are_upstream_rust_objects_already_included(tcx.sess) {
1115 let add_prefix = match (target.is_like_windows, &target.arch) {
1116 (true, Arch::X86) => |name: String, _: SymbolExportKind| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_{0}", name))
})format!("_{name}"),
1117 (true, Arch::Arm64EC) => {
1118 |name: String, export_kind: SymbolExportKind| match export_kind {
1120 SymbolExportKind::Text => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#{0}", name))
})format!("#{name}"),
1121 _ => name,
1122 }
1123 }
1124 _ => |name: String, _: SymbolExportKind| name,
1125 };
1126 let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info
1127 .used_crates
1128 .iter()
1129 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
1130 .filter(|l| l.is_weak())
1131 .filter_map(|&l| {
1132 let name = l.link_name()?;
1133 let export_kind = match l.target() {
1134 Target::ForeignFn | Target::Fn => SymbolExportKind::Text,
1135 Target::Static => SymbolExportKind::Data,
1136 _ => ::rustc_span::macros::bug_impl(None,
format_args!("Don\'t know what the export kind is for lang item of kind {0:?}",
l.target()), Location::caller())bug!(
1137 "Don't know what the export kind is for lang item of kind {:?}",
1138 l.target()
1139 ),
1140 };
1141 lang_items::required(tcx, l).then_some((name, export_kind))
1142 })
1143 .collect();
1144
1145 #[allow(rustc::potential_query_instability)]
1148 info.linked_symbols
1149 .iter_mut()
1150 .filter(|(crate_type, _)| {
1151 !#[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib)
1152 })
1153 .for_each(|(_, linked_symbols)| {
1154 let mut symbols = missing_weak_lang_items
1155 .iter()
1156 .map(|(item, export_kind)| {
1157 (
1158 add_prefix(
1159 mangle_internal_symbol(tcx, item.as_str()),
1160 *export_kind,
1161 ),
1162 *export_kind,
1163 )
1164 })
1165 .collect::<Vec<_>>();
1166 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1167 linked_symbols.extend(symbols);
1168 });
1169 }
1170
1171 let mut each_linked_rlib_for_lto = Vec::new();
1172 let mut each_linked_rlib_file_for_lto = Vec::new();
1173 if tcx.sess.lto() != config::Lto::No && tcx.sess.lto() != config::Lto::ThinLocal {
1174 drop(crate::back::link::each_linked_rlib(&info, None, &mut |cnum, path| {
1175 if crate::back::link::ignored_for_lto(tcx.sess, &info, cnum) {
1176 return;
1177 }
1178
1179 each_linked_rlib_for_lto.push(cnum);
1180 each_linked_rlib_file_for_lto.push(path.to_path_buf());
1181 }));
1182 }
1183 info.each_linked_rlib_file_for_lto = each_linked_rlib_file_for_lto;
1184
1185 info.exported_symbols_for_lto =
1188 crate::back::lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto);
1189
1190 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1191 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1192 true
1195 }
1196 CrateType::ProcMacro => {
1197 false
1201 }
1202 CrateType::StaticLib | CrateType::Rlib => {
1203 false
1206 }
1207 });
1208
1209 if target.is_like_msvc && embed_visualizers {
1210 info.natvis_debugger_visualizers =
1211 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1212 }
1213
1214 info
1215 }
1216}
1217
1218pub(crate) fn provide(providers: &mut Providers) {
1219 providers.backend_optimization_level = |tcx, cratenum| {
1220 let for_speed = match tcx.sess.opts.optimize {
1221 config::OptLevel::No => return config::OptLevel::No,
1228 config::OptLevel::Less => return config::OptLevel::Less,
1230 config::OptLevel::More => return config::OptLevel::More,
1231 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1232 config::OptLevel::Size => config::OptLevel::More,
1235 config::OptLevel::SizeMin => config::OptLevel::More,
1236 };
1237
1238 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1239
1240 let any_for_speed = defids.items().any(|id| {
1241 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1242 #[allow(non_exhaustive_omitted_patterns)] match optimize {
OptimizeAttr::Speed => true,
_ => false,
}matches!(optimize, OptimizeAttr::Speed)
1243 });
1244
1245 if any_for_speed {
1246 return for_speed;
1247 }
1248
1249 tcx.sess.opts.optimize
1250 };
1251}
1252
1253pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1254 if !tcx.dep_graph.is_fully_enabled()
1255 || tcx.sess.opts.unstable_opts.disable_incr_comp_backend_caching
1256 {
1257 return CguReuse::No;
1258 }
1259
1260 let work_product_id = &cgu.work_product_id();
1261 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1262 return CguReuse::No;
1265 }
1266
1267 let dep_node = cgu.codegen_dep_node(tcx);
1274 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(tcx.sess, &dep_node, || {
1275 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("CompileCodegenUnit dep-node for CGU `{0}` already exists before marking.",
cgu.name()))
})format!(
1276 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1277 cgu.name()
1278 )
1279 });
1280
1281 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
1282 match compute_per_cgu_lto_type(
1286 &tcx.sess.lto(),
1287 tcx.sess.opts.cg.linker_plugin_lto.enabled(),
1288 tcx.crate_types(),
1289 ) {
1290 ComputedLtoType::No => CguReuse::PostLto,
1291 _ => CguReuse::PreLto,
1292 }
1293 } else {
1294 CguReuse::No
1295 }
1296}