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::expand::allocator::{
9 ALLOC_ERROR_HANDLER, ALLOCATOR_METHODS, AllocatorKind, AllocatorMethod, AllocatorMethodInput,
10 AllocatorTy,
11};
12use rustc_data_structures::fx::{FxHashMap, 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, OptimizeAttr};
17use rustc_hir::def_id::{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;
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, ModuleCodegen, errors, meth, mir,
54};
55
56pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
57 match (op, signed) {
58 (BinOp::Eq, _) => IntPredicate::IntEQ,
59 (BinOp::Ne, _) => IntPredicate::IntNE,
60 (BinOp::Lt, true) => IntPredicate::IntSLT,
61 (BinOp::Lt, false) => IntPredicate::IntULT,
62 (BinOp::Le, true) => IntPredicate::IntSLE,
63 (BinOp::Le, false) => IntPredicate::IntULE,
64 (BinOp::Gt, true) => IntPredicate::IntSGT,
65 (BinOp::Gt, false) => IntPredicate::IntUGT,
66 (BinOp::Ge, true) => IntPredicate::IntSGE,
67 (BinOp::Ge, false) => IntPredicate::IntUGE,
68 op => ::rustc_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),
69 }
70}
71
72pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
73 match op {
74 BinOp::Eq => RealPredicate::RealOEQ,
75 BinOp::Ne => RealPredicate::RealUNE,
76 BinOp::Lt => RealPredicate::RealOLT,
77 BinOp::Le => RealPredicate::RealOLE,
78 BinOp::Gt => RealPredicate::RealOGT,
79 BinOp::Ge => RealPredicate::RealOGE,
80 op => ::rustc_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),
81 }
82}
83
84pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
85 bx: &mut Bx,
86 lhs: Bx::Value,
87 rhs: Bx::Value,
88 t: Ty<'tcx>,
89 ret_ty: Bx::Type,
90 op: BinOp,
91) -> Bx::Value {
92 let signed = match t.kind() {
93 ty::Float(_) => {
94 let cmp = bin_op_to_fcmp_predicate(op);
95 let cmp = bx.fcmp(cmp, lhs, rhs);
96 return bx.sext(cmp, ret_ty);
97 }
98 ty::Uint(_) => false,
99 ty::Int(_) => true,
100 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("compare_simd_types: invalid SIMD type"))bug!("compare_simd_types: invalid SIMD type"),
101 };
102
103 let cmp = bin_op_to_icmp_predicate(op, signed);
104 let cmp = bx.icmp(cmp, lhs, rhs);
105 bx.sext(cmp, ret_ty)
110}
111
112pub fn validate_trivial_unsize<'tcx>(
121 tcx: TyCtxt<'tcx>,
122 source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
123 target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
124) -> bool {
125 match (source_data.principal(), target_data.principal()) {
126 (Some(hr_source_principal), Some(hr_target_principal)) => {
127 let (infcx, param_env) =
128 tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
129 let universe = infcx.universe();
130 let ocx = ObligationCtxt::new(&infcx);
131 infcx.enter_forall(hr_target_principal, |target_principal| {
132 let source_principal = infcx.instantiate_binder_with_fresh_vars(
133 DUMMY_SP,
134 BoundRegionConversionTime::HigherRankedType,
135 hr_source_principal,
136 );
137 let Ok(()) = ocx.eq(
138 &ObligationCause::dummy(),
139 param_env,
140 target_principal,
141 source_principal,
142 ) else {
143 return false;
144 };
145 if !ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
146 return false;
147 }
148 infcx.leak_check(universe, None).is_ok()
149 })
150 }
151 (_, None) => true,
152 _ => false,
153 }
154}
155
156fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
162 bx: &mut Bx,
163 source: Ty<'tcx>,
164 target: Ty<'tcx>,
165 old_info: Option<Bx::Value>,
166) -> Bx::Value {
167 let cx = bx.cx();
168 let (source, target) =
169 cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
170 match (source.kind(), target.kind()) {
171 (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
172 len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
173 ),
174 (&ty::Dynamic(data_a, _), &ty::Dynamic(data_b, _)) => {
175 let old_info =
176 old_info.expect("unsized_info: missing old info for trait upcasting coercion");
177 let b_principal_def_id = data_b.principal_def_id();
178 if data_a.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {
179 if true {
if !validate_trivial_unsize(cx.tcx(), data_a, data_b) {
{
::core::panicking::panic_fmt(format_args!("NOP unsize vtable changed principal trait ref: {0} -> {1}",
data_a, data_b));
}
};
};debug_assert!(
188 validate_trivial_unsize(cx.tcx(), data_a, data_b),
189 "NOP unsize vtable changed principal trait ref: {data_a} -> {data_b}"
190 );
191
192 return old_info;
198 }
199
200 let vptr_entry_idx = cx.tcx().supertrait_vtable_slot((source, target));
203
204 if let Some(entry_idx) = vptr_entry_idx {
205 let ptr_size = bx.data_layout().pointer_size();
206 let vtable_byte_offset = u64::try_from(entry_idx).unwrap() * ptr_size.bytes();
207 load_vtable(bx, old_info, bx.type_ptr(), vtable_byte_offset, source, true)
208 } else {
209 old_info
210 }
211 }
212 (_, ty::Dynamic(data, _)) => meth::get_vtable(
213 cx,
214 source,
215 data.principal()
216 .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),
217 ),
218 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unsized_info: invalid unsizing {0:?} -> {1:?}",
source, target))bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
219 }
220}
221
222pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
224 bx: &mut Bx,
225 src: Bx::Value,
226 src_ty: Ty<'tcx>,
227 dst_ty: Ty<'tcx>,
228 old_info: Option<Bx::Value>,
229) -> (Bx::Value, Bx::Value) {
230 {
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:230",
"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(230u32),
::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);
231 match (src_ty.kind(), dst_ty.kind()) {
232 (&ty::Pat(a, _), &ty::Pat(b, _)) => unsize_ptr(bx, src, a, b, old_info),
233 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
234 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
235 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());
236 (src, unsized_info(bx, a, b, old_info))
237 }
238 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
239 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);
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 continue;
251 }
252
253 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);
254 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);
255 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);
256
257 let dst_f = dst_layout.field(bx.cx(), i);
258 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);
259 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);
260 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
261 }
262 result.unwrap()
263 }
264 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unsize_ptr: called on bad types"))bug!("unsize_ptr: called on bad types"),
265 }
266}
267
268pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
271 bx: &mut Bx,
272 src: PlaceRef<'tcx, Bx::Value>,
273 dst: PlaceRef<'tcx, Bx::Value>,
274) {
275 let src_ty = src.layout.ty;
276 let dst_ty = dst.layout.ty;
277 match (src_ty.kind(), dst_ty.kind()) {
278 (&ty::Pat(s, sp), &ty::Pat(d, dp))
279 if let (PatternKind::NotNull, PatternKind::NotNull) = (*sp, *dp) =>
280 {
281 let src = src.project_type(bx, s);
282 let dst = dst.project_type(bx, d);
283 coerce_unsized_into(bx, src, dst)
284 }
285 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
286 let (base, info) = match bx.load_operand(src).val {
287 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
288 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
289 OperandValue::Ref(..) | OperandValue::ZeroSized => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
290 };
291 OperandValue::Pair(base, info).store(bx, dst);
292 }
293
294 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
295 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() {
298 let src_f = src.project_field(bx, i.as_usize());
299 let dst_f = dst.project_field(bx, i.as_usize());
300
301 if dst_f.layout.is_zst() {
302 continue;
304 }
305
306 if src_f.layout.ty == dst_f.layout.ty {
307 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
308 } else {
309 coerce_unsized_into(bx, src_f, dst_f);
310 }
311 }
312 }
313 _ => ::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,),
314 }
315}
316
317pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
333 bx: &mut Bx,
334 lhs: Bx::Value,
335 mut rhs: Bx::Value,
336 is_unchecked: bool,
337) -> Bx::Value {
338 let mut rhs_llty = bx.cx().val_ty(rhs);
340 let mut lhs_llty = bx.cx().val_ty(lhs);
341
342 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
343 if !is_unchecked {
344 rhs = bx.and(rhs, mask);
345 }
346
347 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
348 rhs_llty = bx.cx().element_type(rhs_llty)
349 }
350 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
351 lhs_llty = bx.cx().element_type(lhs_llty)
352 }
353 let rhs_sz = bx.cx().int_width(rhs_llty);
354 let lhs_sz = bx.cx().int_width(lhs_llty);
355 if lhs_sz < rhs_sz {
356 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
357 } else if lhs_sz > rhs_sz {
358 if !(lhs_sz <= 256) {
::core::panicking::panic("assertion failed: lhs_sz <= 256")
};assert!(lhs_sz <= 256);
365 bx.zext(rhs, lhs_llty)
366 } else {
367 rhs
368 }
369}
370
371pub fn wants_wasm_eh(sess: &Session) -> bool {
375 sess.target.is_like_wasm
376}
377
378pub fn wants_msvc_seh(sess: &Session) -> bool {
384 sess.target.is_like_msvc
385}
386
387pub(crate) fn wants_new_eh_instructions(sess: &Session) -> bool {
391 wants_wasm_eh(sess) || wants_msvc_seh(sess)
392}
393
394pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
395 cx: &'a Bx::CodegenCx,
396 instance: Instance<'tcx>,
397) {
398 {
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:401",
"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(401u32),
::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);
402
403 mir::codegen_mir::<Bx>(cx, instance);
404}
405
406pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: ItemId)
407where
408 Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + AsmCodegenMethods<'tcx>,
409{
410 let item = cx.tcx().hir_item(item_id);
411 if let rustc_hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
412 let operands: Vec<_> = asm
413 .operands
414 .iter()
415 .map(|(op, op_sp)| match *op {
416 rustc_hir::InlineAsmOperand::Const { ref anon_const } => {
417 match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) {
418 Ok(const_value) => {
419 let ty =
420 cx.tcx().typeck_body(anon_const.body).node_type(anon_const.hir_id);
421 let string = common::asm_const_to_str(
422 cx.tcx(),
423 *op_sp,
424 const_value,
425 cx.layout_of(ty),
426 );
427 GlobalAsmOperandRef::Const { string }
428 }
429 Err(ErrorHandled::Reported { .. }) => {
430 GlobalAsmOperandRef::Const { string: String::new() }
435 }
436 Err(ErrorHandled::TooGeneric(_)) => {
437 ::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")
438 }
439 }
440 }
441 rustc_hir::InlineAsmOperand::SymFn { expr } => {
442 let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
443 let instance = match ty.kind() {
444 &ty::FnDef(def_id, args) => Instance::expect_resolve(
445 cx.tcx(),
446 ty::TypingEnv::fully_monomorphized(),
447 def_id,
448 args,
449 expr.span,
450 ),
451 _ => ::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"),
452 };
453
454 GlobalAsmOperandRef::SymFn { instance }
455 }
456 rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
457 GlobalAsmOperandRef::SymStatic { def_id }
458 }
459 rustc_hir::InlineAsmOperand::In { .. }
460 | rustc_hir::InlineAsmOperand::Out { .. }
461 | rustc_hir::InlineAsmOperand::InOut { .. }
462 | rustc_hir::InlineAsmOperand::SplitInOut { .. }
463 | rustc_hir::InlineAsmOperand::Label { .. } => {
464 ::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!")
465 }
466 })
467 .collect();
468
469 cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans);
470 } else {
471 ::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")
472 }
473}
474
475pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
478 cx: &'a Bx::CodegenCx,
479 cgu: &CodegenUnit<'tcx>,
480) -> Option<Bx::Function> {
481 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
482 let main_is_local = main_def_id.is_local();
483 let instance = Instance::mono(cx.tcx(), main_def_id);
484
485 if main_is_local {
486 if !cgu.contains_item(&MonoItem::Fn(instance)) {
489 return None;
490 }
491 } else if !cgu.is_primary() {
492 return None;
494 }
495
496 let main_llfn = cx.get_fn_addr(instance);
497
498 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
499 return Some(entry_fn);
500
501 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
502 cx: &'a Bx::CodegenCx,
503 rust_main: Bx::Value,
504 rust_main_def_id: DefId,
505 entry_type: EntryFnType,
506 ) -> Bx::Function {
507 let llfty = if cx.sess().target.os == Os::Uefi {
510 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
511 } else if cx.sess().target.main_needs_argc_argv {
512 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
513 } else {
514 cx.type_func(&[], cx.type_int())
515 };
516
517 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
518 let main_ret_ty = cx.tcx().normalize_erasing_regions(
524 cx.typing_env(),
525 Unnormalized::new_wip(main_ret_ty.no_bound_vars().unwrap()),
526 );
527
528 let Some(llfn) = cx.declare_c_main(llfty) else {
529 let span = cx.tcx().def_span(rust_main_def_id);
531 cx.tcx().dcx().emit_fatal(errors::MultipleMainFunctions { span });
532 };
533
534 cx.set_frame_pointer_type(llfn);
536 cx.apply_target_cpu_attr(llfn);
537
538 let llbb = Bx::append_block(cx, llfn, "top");
539 let mut bx = Bx::build(cx, llbb);
540
541 bx.insert_reference_to_gdb_debug_scripts_section_global();
542
543 let isize_ty = cx.type_isize();
544 let ptr_ty = cx.type_ptr();
545 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
546
547 let EntryFnType::Main { sigpipe } = entry_type;
548 let (start_fn, start_ty, args, instance) = {
549 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, DUMMY_SP);
550 let start_instance = ty::Instance::expect_resolve(
551 cx.tcx(),
552 cx.typing_env(),
553 start_def_id,
554 cx.tcx().mk_args(&[main_ret_ty.into()]),
555 DUMMY_SP,
556 );
557 let start_fn = cx.get_fn_addr(start_instance);
558
559 let i8_ty = cx.type_i8();
560 let arg_sigpipe = bx.const_u8(sigpipe);
561
562 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
563 (
564 start_fn,
565 start_ty,
566 ::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],
567 Some(start_instance),
568 )
569 };
570
571 let result = bx.call(start_ty, None, None, start_fn, &args, None, instance);
572 if cx.sess().target.os == Os::Uefi {
573 bx.ret(result);
574 } else {
575 let cast = bx.intcast(result, cx.type_int(), true);
576 bx.ret(cast);
577 }
578
579 llfn
580 }
581}
582
583fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
586 if bx.cx().sess().target.os == Os::Uefi {
587 let param_handle = bx.get_param(0);
589 let param_system_table = bx.get_param(1);
590 let ptr_size = bx.tcx().data_layout.pointer_size();
591 let ptr_align = bx.tcx().data_layout.pointer_align().abi;
592 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
593 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
594 bx.store(param_handle, arg_argv, ptr_align);
595 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
596 bx.store(param_system_table, arg_argv_el1, ptr_align);
597 (arg_argc, arg_argv)
598 } else if bx.cx().sess().target.main_needs_argc_argv {
599 let param_argc = bx.get_param(0);
601 let param_argv = bx.get_param(1);
602 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
603 let arg_argv = param_argv;
604 (arg_argc, arg_argv)
605 } else {
606 let arg_argc = bx.const_int(bx.cx().type_int(), 0);
608 let arg_argv = bx.const_null(bx.cx().type_ptr());
609 (arg_argc, arg_argv)
610 }
611}
612
613pub fn collect_debugger_visualizers_transitive(
617 tcx: TyCtxt<'_>,
618 visualizer_type: DebuggerVisualizerType,
619) -> BTreeSet<DebuggerVisualizerFile> {
620 tcx.debugger_visualizers(LOCAL_CRATE)
621 .iter()
622 .chain(
623 tcx.crates(())
624 .iter()
625 .filter(|&cnum| {
626 let used_crate_source = tcx.used_crate_source(*cnum);
627 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
628 })
629 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
630 )
631 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
632 .cloned()
633 .collect::<BTreeSet<_>>()
634}
635
636pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
640 let all_crate_types_any_dynamic_crate = tcx.dependency_formats(()).iter().all(|(_, list)| {
650 use rustc_middle::middle::dependency_format::Linkage;
651 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
652 });
653 if all_crate_types_any_dynamic_crate { None } else { tcx.allocator_kind(()) }
654}
655
656pub(crate) fn needs_allocator_shim_for_linking(
660 dependency_formats: &Dependencies,
661 crate_type: CrateType,
662) -> bool {
663 use rustc_middle::middle::dependency_format::Linkage;
664 let any_dynamic_crate =
665 dependency_formats[&crate_type].iter().any(|&linkage| linkage == Linkage::Dynamic);
666 !any_dynamic_crate
667}
668
669pub fn allocator_shim_contents(tcx: TyCtxt<'_>, kind: AllocatorKind) -> Vec<AllocatorMethod> {
670 let mut methods = Vec::new();
671
672 if kind == AllocatorKind::Default {
673 methods.extend(ALLOCATOR_METHODS.into_iter().copied());
674 }
675
676 if tcx.alloc_error_handler_kind(()).unwrap() == AllocatorKind::Default {
679 methods.push(AllocatorMethod {
680 name: ALLOC_ERROR_HANDLER,
681 special: None,
682 inputs: &[AllocatorMethodInput { name: "layout", ty: AllocatorTy::Layout }],
683 output: AllocatorTy::Never,
684 });
685 }
686
687 methods
688}
689
690pub fn codegen_crate<
691 B: ExtraBackendMethods<Module = M> + WriteBackendMethods<Module = M>,
692 M: Send,
693>(
694 backend: B,
695 tcx: TyCtxt<'_>,
696) -> OngoingCodegen<B> {
697 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
698 tcx.dcx().emit_fatal(errors::CpuRequired);
700 }
701
702 if let Some(target_cpu) = &tcx.sess.opts.cg.target_cpu
703 && tcx.sess.target.unsupported_cpus.contains(&target_cpu.into())
704 {
705 tcx.dcx().emit_fatal(errors::CpuUnsupported { target_cpu: target_cpu.clone() });
707 }
708
709 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
710
711 let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());
714
715 if tcx.dep_graph.is_fully_enabled() {
721 for cgu in codegen_units {
722 tcx.ensure_ok().codegen_unit(cgu.name());
723 }
724 }
725
726 let allocator_module = if let Some(kind) = allocator_kind_for_codegen(tcx) {
728 let llmod_id =
729 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
730
731 tcx.sess.time("write_allocator_module", || {
732 let module =
733 backend.codegen_allocator(tcx, &llmod_id, &allocator_shim_contents(tcx, kind));
734 Some(ModuleCodegen::new_allocator(llmod_id, module))
735 })
736 } else {
737 None
738 };
739
740 let ongoing_codegen = start_async_codegen(backend.clone(), tcx, allocator_module);
741
742 let codegen_units: Vec<_> = {
754 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
755 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
756
757 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
758 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
759 };
760
761 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
763 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
764 });
765
766 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
767 for (i, cgu) in codegen_units.iter().enumerate() {
768 let cgu_reuse = cgu_reuse[i];
769 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
770 }
771 });
772
773 let mut total_codegen_time = Duration::new(0, 0);
774 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
775
776 let mut pre_compiled_cgus = if let Some(threads) = tcx.sess.threads() {
787 tcx.sess.time("compile_first_CGU_batch", || {
788 let cgus: Vec<_> = cgu_reuse
790 .iter()
791 .enumerate()
792 .filter(|&(_, reuse)| reuse == &CguReuse::No)
793 .take(threads)
794 .collect();
795
796 let start_time = Instant::now();
798
799 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
800 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
801 (i, IntoDynSyncSend(module))
802 });
803
804 total_codegen_time += start_time.elapsed();
805
806 pre_compiled_cgus
807 })
808 } else {
809 FxHashMap::default()
810 };
811
812 for (i, cgu) in codegen_units.iter().enumerate() {
813 ongoing_codegen.wait_for_signal_to_codegen_item();
814 ongoing_codegen.check_for_errors(tcx.sess);
815
816 let cgu_reuse = cgu_reuse[i];
817
818 match cgu_reuse {
819 CguReuse::No => {
820 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
821 cgu.0
822 } else {
823 let start_time = Instant::now();
824 let module = backend.compile_codegen_unit(tcx, cgu.name());
825 total_codegen_time += start_time.elapsed();
826 module
827 };
828 tcx.dcx().abort_if_errors();
832
833 submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);
834 }
835 CguReuse::PreLto => {
836 submit_pre_lto_module_to_llvm(
837 tcx,
838 &ongoing_codegen.coordinator,
839 CachedModuleCodegen {
840 name: cgu.name().to_string(),
841 source: cgu.previous_work_product(tcx),
842 },
843 );
844 }
845 CguReuse::PostLto => {
846 submit_post_lto_module_to_llvm(
847 &ongoing_codegen.coordinator,
848 CachedModuleCodegen {
849 name: cgu.name().to_string(),
850 source: cgu.previous_work_product(tcx),
851 },
852 );
853 }
854 }
855 }
856
857 ongoing_codegen.codegen_finished(tcx);
858
859 if tcx.sess.opts.unstable_opts.time_passes {
862 let end_rss = get_resident_set_size();
863
864 print_time_passes_entry(
865 "codegen_to_LLVM_IR",
866 total_codegen_time,
867 start_rss.unwrap(),
868 end_rss,
869 tcx.sess.opts.unstable_opts.time_passes_format,
870 );
871 }
872
873 ongoing_codegen.check_for_errors(tcx.sess);
874 ongoing_codegen
875}
876
877pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
887 tcx: TyCtxt<'tcx>,
888 instance: Instance<'tcx>,
889) -> bool {
890 fn is_llvm_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
891 if let Some(name) = tcx.codegen_fn_attrs(def_id).symbol_name {
892 name.as_str().starts_with("llvm.")
893 } else {
894 false
895 }
896 }
897
898 let def_id = instance.def_id();
899 !def_id.is_local()
900 && tcx.is_compiler_builtins(LOCAL_CRATE)
901 && !is_llvm_intrinsic(tcx, def_id)
902 && !tcx.should_codegen_locally(instance)
903}
904
905impl CrateInfo {
906 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
907 let crate_types = tcx.crate_types().to_vec();
908 let exported_symbols = crate_types
909 .iter()
910 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
911 .collect();
912 let linked_symbols =
913 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
914 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
915 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);
916
917 let mut compiler_builtins = None;
926 let mut used_crates: Vec<_> = tcx
927 .postorder_cnums(())
928 .iter()
929 .rev()
930 .copied()
931 .filter(|&cnum| {
932 let link = !tcx.crate_dep_kind(cnum).macros_only();
933 if link && tcx.is_compiler_builtins(cnum) {
934 compiler_builtins = Some(cnum);
935 return false;
936 }
937 link
938 })
939 .collect();
940 used_crates.extend(compiler_builtins);
942
943 let crates = tcx.crates(());
944 let n_crates = crates.len();
945 let mut info = CrateInfo {
946 target_cpu,
947 target_features: tcx.global_backend_features(()).clone(),
948 crate_types,
949 exported_symbols,
950 linked_symbols,
951 local_crate_name,
952 compiler_builtins,
953 profiler_runtime: None,
954 is_no_builtins: Default::default(),
955 native_libraries: Default::default(),
956 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
957 crate_name: UnordMap::with_capacity(n_crates),
958 used_crates,
959 used_crate_source: UnordMap::with_capacity(n_crates),
960 dependency_formats: Arc::clone(tcx.dependency_formats(())),
961 windows_subsystem,
962 natvis_debugger_visualizers: Default::default(),
963 lint_level_specs: CodegenLintLevelSpecs::from_tcx(tcx),
964 metadata_symbol: exported_symbols::metadata_symbol_name(tcx),
965 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)),
966 each_linked_rlib_file_for_lto: Default::default(),
967 exported_symbols_for_lto: Default::default(),
968 };
969
970 info.native_libraries.reserve(n_crates);
971
972 for &cnum in crates.iter() {
973 info.native_libraries
974 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
975 info.crate_name.insert(cnum, tcx.crate_name(cnum));
976
977 let used_crate_source = tcx.used_crate_source(cnum);
978 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
979 if tcx.is_profiler_runtime(cnum) {
980 info.profiler_runtime = Some(cnum);
981 }
982 if tcx.is_no_builtins(cnum) {
983 info.is_no_builtins.insert(cnum);
984 }
985 }
986
987 let target = &tcx.sess.target;
996 if !are_upstream_rust_objects_already_included(tcx.sess) {
997 let add_prefix = match (target.is_like_windows, &target.arch) {
998 (true, Arch::X86) => |name: String, _: SymbolExportKind| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_{0}", name))
})format!("_{name}"),
999 (true, Arch::Arm64EC) => {
1000 |name: String, export_kind: SymbolExportKind| match export_kind {
1002 SymbolExportKind::Text => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#{0}", name))
})format!("#{name}"),
1003 _ => name,
1004 }
1005 }
1006 _ => |name: String, _: SymbolExportKind| name,
1007 };
1008 let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info
1009 .used_crates
1010 .iter()
1011 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
1012 .filter(|l| l.is_weak())
1013 .filter_map(|&l| {
1014 let name = l.link_name()?;
1015 let export_kind = match l.target() {
1016 Target::Fn => SymbolExportKind::Text,
1017 Target::Static => SymbolExportKind::Data,
1018 _ => ::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!(
1019 "Don't know what the export kind is for lang item of kind {:?}",
1020 l.target()
1021 ),
1022 };
1023 lang_items::required(tcx, l).then_some((name, export_kind))
1024 })
1025 .collect();
1026
1027 #[allow(rustc::potential_query_instability)]
1030 info.linked_symbols
1031 .iter_mut()
1032 .filter(|(crate_type, _)| {
1033 !#[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib)
1034 })
1035 .for_each(|(_, linked_symbols)| {
1036 let mut symbols = missing_weak_lang_items
1037 .iter()
1038 .map(|(item, export_kind)| {
1039 (
1040 add_prefix(
1041 mangle_internal_symbol(tcx, item.as_str()),
1042 *export_kind,
1043 ),
1044 *export_kind,
1045 )
1046 })
1047 .collect::<Vec<_>>();
1048 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1049 linked_symbols.extend(symbols);
1050 });
1051 }
1052
1053 let mut each_linked_rlib_for_lto = Vec::new();
1054 let mut each_linked_rlib_file_for_lto = Vec::new();
1055 if tcx.sess.lto() != config::Lto::No && tcx.sess.lto() != config::Lto::ThinLocal {
1056 drop(crate::back::link::each_linked_rlib(&info, None, &mut |cnum, path| {
1057 if crate::back::link::ignored_for_lto(tcx.sess, &info, cnum) {
1058 return;
1059 }
1060
1061 each_linked_rlib_for_lto.push(cnum);
1062 each_linked_rlib_file_for_lto.push(path.to_path_buf());
1063 }));
1064 }
1065 info.each_linked_rlib_file_for_lto = each_linked_rlib_file_for_lto;
1066
1067 info.exported_symbols_for_lto =
1070 crate::back::lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto);
1071
1072 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1073 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1074 true
1077 }
1078 CrateType::ProcMacro => {
1079 false
1083 }
1084 CrateType::StaticLib | CrateType::Rlib => {
1085 false
1088 }
1089 });
1090
1091 if target.is_like_msvc && embed_visualizers {
1092 info.natvis_debugger_visualizers =
1093 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1094 }
1095
1096 info
1097 }
1098}
1099
1100pub(crate) fn provide(providers: &mut Providers) {
1101 providers.backend_optimization_level = |tcx, cratenum| {
1102 let for_speed = match tcx.sess.opts.optimize {
1103 config::OptLevel::No => return config::OptLevel::No,
1110 config::OptLevel::Less => return config::OptLevel::Less,
1112 config::OptLevel::More => return config::OptLevel::More,
1113 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1114 config::OptLevel::Size => config::OptLevel::More,
1117 config::OptLevel::SizeMin => config::OptLevel::More,
1118 };
1119
1120 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1121
1122 let any_for_speed = defids.items().any(|id| {
1123 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1124 #[allow(non_exhaustive_omitted_patterns)] match optimize {
OptimizeAttr::Speed => true,
_ => false,
}matches!(optimize, OptimizeAttr::Speed)
1125 });
1126
1127 if any_for_speed {
1128 return for_speed;
1129 }
1130
1131 tcx.sess.opts.optimize
1132 };
1133}
1134
1135pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1136 if !tcx.dep_graph.is_fully_enabled()
1137 || tcx.sess.opts.unstable_opts.disable_incr_comp_backend_caching
1138 {
1139 return CguReuse::No;
1140 }
1141
1142 let work_product_id = &cgu.work_product_id();
1143 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1144 return CguReuse::No;
1147 }
1148
1149 let dep_node = cgu.codegen_dep_node(tcx);
1156 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(tcx.sess, &dep_node, || {
1157 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("CompileCodegenUnit dep-node for CGU `{0}` already exists before marking.",
cgu.name()))
})format!(
1158 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1159 cgu.name()
1160 )
1161 });
1162
1163 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
1164 match compute_per_cgu_lto_type(
1168 &tcx.sess.lto(),
1169 tcx.sess.opts.cg.linker_plugin_lto.enabled(),
1170 tcx.crate_types(),
1171 ) {
1172 ComputedLtoType::No => CguReuse::PostLto,
1173 _ => CguReuse::PreLto,
1174 }
1175 } else {
1176 CguReuse::No
1177 }
1178}