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};
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::{CachedModuleCodegen, CodegenLintLevels, CrateInfo, ModuleCodegen, errors, meth, mir};
53
54pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
55 match (op, signed) {
56 (BinOp::Eq, _) => IntPredicate::IntEQ,
57 (BinOp::Ne, _) => IntPredicate::IntNE,
58 (BinOp::Lt, true) => IntPredicate::IntSLT,
59 (BinOp::Lt, false) => IntPredicate::IntULT,
60 (BinOp::Le, true) => IntPredicate::IntSLE,
61 (BinOp::Le, false) => IntPredicate::IntULE,
62 (BinOp::Gt, true) => IntPredicate::IntSGT,
63 (BinOp::Gt, false) => IntPredicate::IntUGT,
64 (BinOp::Ge, true) => IntPredicate::IntSGE,
65 (BinOp::Ge, false) => IntPredicate::IntUGE,
66 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),
67 }
68}
69
70pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
71 match op {
72 BinOp::Eq => RealPredicate::RealOEQ,
73 BinOp::Ne => RealPredicate::RealUNE,
74 BinOp::Lt => RealPredicate::RealOLT,
75 BinOp::Le => RealPredicate::RealOLE,
76 BinOp::Gt => RealPredicate::RealOGT,
77 BinOp::Ge => RealPredicate::RealOGE,
78 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),
79 }
80}
81
82pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
83 bx: &mut Bx,
84 lhs: Bx::Value,
85 rhs: Bx::Value,
86 t: Ty<'tcx>,
87 ret_ty: Bx::Type,
88 op: BinOp,
89) -> Bx::Value {
90 let signed = match t.kind() {
91 ty::Float(_) => {
92 let cmp = bin_op_to_fcmp_predicate(op);
93 let cmp = bx.fcmp(cmp, lhs, rhs);
94 return bx.sext(cmp, ret_ty);
95 }
96 ty::Uint(_) => false,
97 ty::Int(_) => true,
98 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("compare_simd_types: invalid SIMD type"))bug!("compare_simd_types: invalid SIMD type"),
99 };
100
101 let cmp = bin_op_to_icmp_predicate(op, signed);
102 let cmp = bx.icmp(cmp, lhs, rhs);
103 bx.sext(cmp, ret_ty)
108}
109
110pub fn validate_trivial_unsize<'tcx>(
119 tcx: TyCtxt<'tcx>,
120 source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
121 target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
122) -> bool {
123 match (source_data.principal(), target_data.principal()) {
124 (Some(hr_source_principal), Some(hr_target_principal)) => {
125 let (infcx, param_env) =
126 tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
127 let universe = infcx.universe();
128 let ocx = ObligationCtxt::new(&infcx);
129 infcx.enter_forall(hr_target_principal, |target_principal| {
130 let source_principal = infcx.instantiate_binder_with_fresh_vars(
131 DUMMY_SP,
132 BoundRegionConversionTime::HigherRankedType,
133 hr_source_principal,
134 );
135 let Ok(()) = ocx.eq(
136 &ObligationCause::dummy(),
137 param_env,
138 target_principal,
139 source_principal,
140 ) else {
141 return false;
142 };
143 if !ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
144 return false;
145 }
146 infcx.leak_check(universe, None).is_ok()
147 })
148 }
149 (_, None) => true,
150 _ => false,
151 }
152}
153
154fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
160 bx: &mut Bx,
161 source: Ty<'tcx>,
162 target: Ty<'tcx>,
163 old_info: Option<Bx::Value>,
164) -> Bx::Value {
165 let cx = bx.cx();
166 let (source, target) =
167 cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
168 match (source.kind(), target.kind()) {
169 (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
170 len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
171 ),
172 (&ty::Dynamic(data_a, _), &ty::Dynamic(data_b, _)) => {
173 let old_info =
174 old_info.expect("unsized_info: missing old info for trait upcasting coercion");
175 let b_principal_def_id = data_b.principal_def_id();
176 if data_a.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {
177 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!(
186 validate_trivial_unsize(cx.tcx(), data_a, data_b),
187 "NOP unsize vtable changed principal trait ref: {data_a} -> {data_b}"
188 );
189
190 return old_info;
196 }
197
198 let vptr_entry_idx = cx.tcx().supertrait_vtable_slot((source, target));
201
202 if let Some(entry_idx) = vptr_entry_idx {
203 let ptr_size = bx.data_layout().pointer_size();
204 let vtable_byte_offset = u64::try_from(entry_idx).unwrap() * ptr_size.bytes();
205 load_vtable(bx, old_info, bx.type_ptr(), vtable_byte_offset, source, true)
206 } else {
207 old_info
208 }
209 }
210 (_, ty::Dynamic(data, _)) => meth::get_vtable(
211 cx,
212 source,
213 data.principal()
214 .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),
215 ),
216 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unsized_info: invalid unsizing {0:?} -> {1:?}",
source, target))bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
217 }
218}
219
220pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
222 bx: &mut Bx,
223 src: Bx::Value,
224 src_ty: Ty<'tcx>,
225 dst_ty: Ty<'tcx>,
226 old_info: Option<Bx::Value>,
227) -> (Bx::Value, Bx::Value) {
228 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/base.rs:228",
"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(228u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::base"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
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);
229 match (src_ty.kind(), dst_ty.kind()) {
230 (&ty::Pat(a, _), &ty::Pat(b, _)) => unsize_ptr(bx, src, a, b, old_info),
231 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
232 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
233 match (&bx.cx().type_is_sized(a), &old_info.is_none()) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(bx.cx().type_is_sized(a), old_info.is_none());
234 (src, unsized_info(bx, a, b, old_info))
235 }
236 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
237 match (&def_a, &def_b) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(def_a, def_b); let src_layout = bx.cx().layout_of(src_ty);
239 let dst_layout = bx.cx().layout_of(dst_ty);
240 if src_ty == dst_ty {
241 return (src, old_info.unwrap());
242 }
243 let mut result = None;
244 for i in 0..src_layout.fields.count() {
245 let src_f = src_layout.field(bx.cx(), i);
246 if src_f.is_1zst() {
247 continue;
249 }
250
251 match (&src_layout.fields.offset(i).bytes(), &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(src_layout.fields.offset(i).bytes(), 0);
252 match (&dst_layout.fields.offset(i).bytes(), &0) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
253 match (&src_layout.size, &src_f.size) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(src_layout.size, src_f.size);
254
255 let dst_f = dst_layout.field(bx.cx(), i);
256 match (&src_f.ty, &dst_f.ty) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_ne!(src_f.ty, dst_f.ty);
257 match (&result, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(result, None);
258 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
259 }
260 result.unwrap()
261 }
262 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unsize_ptr: called on bad types"))bug!("unsize_ptr: called on bad types"),
263 }
264}
265
266pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
269 bx: &mut Bx,
270 src: PlaceRef<'tcx, Bx::Value>,
271 dst: PlaceRef<'tcx, Bx::Value>,
272) {
273 let src_ty = src.layout.ty;
274 let dst_ty = dst.layout.ty;
275 match (src_ty.kind(), dst_ty.kind()) {
276 (&ty::Pat(s, sp), &ty::Pat(d, dp))
277 if let (PatternKind::NotNull, PatternKind::NotNull) = (*sp, *dp) =>
278 {
279 let src = src.project_type(bx, s);
280 let dst = dst.project_type(bx, d);
281 coerce_unsized_into(bx, src, dst)
282 }
283 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
284 let (base, info) = match bx.load_operand(src).val {
285 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
286 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
287 OperandValue::Ref(..) | OperandValue::ZeroSized => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
288 };
289 OperandValue::Pair(base, info).store(bx, dst);
290 }
291
292 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
293 match (&def_a, &def_b) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(def_a, def_b); for i in def_a.variant(FIRST_VARIANT).fields.indices() {
296 let src_f = src.project_field(bx, i.as_usize());
297 let dst_f = dst.project_field(bx, i.as_usize());
298
299 if dst_f.layout.is_zst() {
300 continue;
302 }
303
304 if src_f.layout.ty == dst_f.layout.ty {
305 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
306 } else {
307 coerce_unsized_into(bx, src_f, dst_f);
308 }
309 }
310 }
311 _ => ::rustc_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,),
312 }
313}
314
315pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
331 bx: &mut Bx,
332 lhs: Bx::Value,
333 mut rhs: Bx::Value,
334 is_unchecked: bool,
335) -> Bx::Value {
336 let mut rhs_llty = bx.cx().val_ty(rhs);
338 let mut lhs_llty = bx.cx().val_ty(lhs);
339
340 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
341 if !is_unchecked {
342 rhs = bx.and(rhs, mask);
343 }
344
345 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
346 rhs_llty = bx.cx().element_type(rhs_llty)
347 }
348 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
349 lhs_llty = bx.cx().element_type(lhs_llty)
350 }
351 let rhs_sz = bx.cx().int_width(rhs_llty);
352 let lhs_sz = bx.cx().int_width(lhs_llty);
353 if lhs_sz < rhs_sz {
354 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
355 } else if lhs_sz > rhs_sz {
356 if !(lhs_sz <= 256) {
::core::panicking::panic("assertion failed: lhs_sz <= 256")
};assert!(lhs_sz <= 256);
363 bx.zext(rhs, lhs_llty)
364 } else {
365 rhs
366 }
367}
368
369pub fn wants_wasm_eh(sess: &Session) -> bool {
373 sess.target.is_like_wasm
374 && (sess.target.os != Os::Emscripten || sess.opts.unstable_opts.emscripten_wasm_eh)
375}
376
377pub fn wants_msvc_seh(sess: &Session) -> bool {
383 sess.target.is_like_msvc
384}
385
386pub(crate) fn wants_new_eh_instructions(sess: &Session) -> bool {
390 wants_wasm_eh(sess) || wants_msvc_seh(sess)
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 compiler/rustc_codegen_ssa/src/base.rs:400",
"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(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};
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);
401
402 mir::codegen_mir::<Bx>(cx, instance);
403}
404
405pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: 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 string = common::asm_const_to_str(
421 cx.tcx(),
422 *op_sp,
423 const_value,
424 cx.layout_of(ty),
425 );
426 GlobalAsmOperandRef::Const { string }
427 }
428 Err(ErrorHandled::Reported { .. }) => {
429 GlobalAsmOperandRef::Const { string: String::new() }
434 }
435 Err(ErrorHandled::TooGeneric(_)) => {
436 ::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")
437 }
438 }
439 }
440 rustc_hir::InlineAsmOperand::SymFn { expr } => {
441 let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
442 let instance = match ty.kind() {
443 &ty::FnDef(def_id, args) => Instance::expect_resolve(
444 cx.tcx(),
445 ty::TypingEnv::fully_monomorphized(),
446 def_id,
447 args,
448 expr.span,
449 ),
450 _ => ::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"),
451 };
452
453 GlobalAsmOperandRef::SymFn { instance }
454 }
455 rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
456 GlobalAsmOperandRef::SymStatic { def_id }
457 }
458 rustc_hir::InlineAsmOperand::In { .. }
459 | rustc_hir::InlineAsmOperand::Out { .. }
460 | rustc_hir::InlineAsmOperand::InOut { .. }
461 | rustc_hir::InlineAsmOperand::SplitInOut { .. }
462 | rustc_hir::InlineAsmOperand::Label { .. } => {
463 ::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!")
464 }
465 })
466 .collect();
467
468 cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans);
469 } else {
470 ::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")
471 }
472}
473
474pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
477 cx: &'a Bx::CodegenCx,
478 cgu: &CodegenUnit<'tcx>,
479) -> Option<Bx::Function> {
480 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
481 let main_is_local = main_def_id.is_local();
482 let instance = Instance::mono(cx.tcx(), main_def_id);
483
484 if main_is_local {
485 if !cgu.contains_item(&MonoItem::Fn(instance)) {
488 return None;
489 }
490 } else if !cgu.is_primary() {
491 return None;
493 }
494
495 let main_llfn = cx.get_fn_addr(instance);
496
497 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
498 return Some(entry_fn);
499
500 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
501 cx: &'a Bx::CodegenCx,
502 rust_main: Bx::Value,
503 rust_main_def_id: DefId,
504 entry_type: EntryFnType,
505 ) -> Bx::Function {
506 let llfty = if cx.sess().target.os == Os::Uefi {
509 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
510 } else if cx.sess().target.main_needs_argc_argv {
511 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
512 } else {
513 cx.type_func(&[], cx.type_int())
514 };
515
516 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
517 let main_ret_ty = cx
523 .tcx()
524 .normalize_erasing_regions(cx.typing_env(), main_ret_ty.no_bound_vars().unwrap());
525
526 let Some(llfn) = cx.declare_c_main(llfty) else {
527 let span = cx.tcx().def_span(rust_main_def_id);
529 cx.tcx().dcx().emit_fatal(errors::MultipleMainFunctions { span });
530 };
531
532 cx.set_frame_pointer_type(llfn);
534 cx.apply_target_cpu_attr(llfn);
535
536 let llbb = Bx::append_block(cx, llfn, "top");
537 let mut bx = Bx::build(cx, llbb);
538
539 bx.insert_reference_to_gdb_debug_scripts_section_global();
540
541 let isize_ty = cx.type_isize();
542 let ptr_ty = cx.type_ptr();
543 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
544
545 let EntryFnType::Main { sigpipe } = entry_type;
546 let (start_fn, start_ty, args, instance) = {
547 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, DUMMY_SP);
548 let start_instance = ty::Instance::expect_resolve(
549 cx.tcx(),
550 cx.typing_env(),
551 start_def_id,
552 cx.tcx().mk_args(&[main_ret_ty.into()]),
553 DUMMY_SP,
554 );
555 let start_fn = cx.get_fn_addr(start_instance);
556
557 let i8_ty = cx.type_i8();
558 let arg_sigpipe = bx.const_u8(sigpipe);
559
560 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
561 (
562 start_fn,
563 start_ty,
564 ::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],
565 Some(start_instance),
566 )
567 };
568
569 let result = bx.call(start_ty, None, None, start_fn, &args, None, instance);
570 if cx.sess().target.os == Os::Uefi {
571 bx.ret(result);
572 } else {
573 let cast = bx.intcast(result, cx.type_int(), true);
574 bx.ret(cast);
575 }
576
577 llfn
578 }
579}
580
581fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
584 if bx.cx().sess().target.os == Os::Uefi {
585 let param_handle = bx.get_param(0);
587 let param_system_table = bx.get_param(1);
588 let ptr_size = bx.tcx().data_layout.pointer_size();
589 let ptr_align = bx.tcx().data_layout.pointer_align().abi;
590 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
591 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
592 bx.store(param_handle, arg_argv, ptr_align);
593 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
594 bx.store(param_system_table, arg_argv_el1, ptr_align);
595 (arg_argc, arg_argv)
596 } else if bx.cx().sess().target.main_needs_argc_argv {
597 let param_argc = bx.get_param(0);
599 let param_argv = bx.get_param(1);
600 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
601 let arg_argv = param_argv;
602 (arg_argc, arg_argv)
603 } else {
604 let arg_argc = bx.const_int(bx.cx().type_int(), 0);
606 let arg_argv = bx.const_null(bx.cx().type_ptr());
607 (arg_argc, arg_argv)
608 }
609}
610
611pub fn collect_debugger_visualizers_transitive(
615 tcx: TyCtxt<'_>,
616 visualizer_type: DebuggerVisualizerType,
617) -> BTreeSet<DebuggerVisualizerFile> {
618 tcx.debugger_visualizers(LOCAL_CRATE)
619 .iter()
620 .chain(
621 tcx.crates(())
622 .iter()
623 .filter(|&cnum| {
624 let used_crate_source = tcx.used_crate_source(*cnum);
625 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
626 })
627 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
628 )
629 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
630 .cloned()
631 .collect::<BTreeSet<_>>()
632}
633
634pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
638 let all_crate_types_any_dynamic_crate = tcx.dependency_formats(()).iter().all(|(_, list)| {
648 use rustc_middle::middle::dependency_format::Linkage;
649 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
650 });
651 if all_crate_types_any_dynamic_crate { None } else { tcx.allocator_kind(()) }
652}
653
654pub(crate) fn needs_allocator_shim_for_linking(
658 dependency_formats: &Dependencies,
659 crate_type: CrateType,
660) -> bool {
661 use rustc_middle::middle::dependency_format::Linkage;
662 let any_dynamic_crate =
663 dependency_formats[&crate_type].iter().any(|&linkage| linkage == Linkage::Dynamic);
664 !any_dynamic_crate
665}
666
667pub fn allocator_shim_contents(tcx: TyCtxt<'_>, kind: AllocatorKind) -> Vec<AllocatorMethod> {
668 let mut methods = Vec::new();
669
670 if kind == AllocatorKind::Default {
671 methods.extend(ALLOCATOR_METHODS.into_iter().copied());
672 }
673
674 if tcx.alloc_error_handler_kind(()).unwrap() == AllocatorKind::Default {
677 methods.push(AllocatorMethod {
678 name: ALLOC_ERROR_HANDLER,
679 special: None,
680 inputs: &[AllocatorMethodInput { name: "layout", ty: AllocatorTy::Layout }],
681 output: AllocatorTy::Never,
682 });
683 }
684
685 methods
686}
687
688pub fn codegen_crate<B: ExtraBackendMethods>(
689 backend: B,
690 tcx: TyCtxt<'_>,
691 crate_info: &CrateInfo,
692) -> OngoingCodegen<B> {
693 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
694 tcx.dcx().emit_fatal(errors::CpuRequired);
696 }
697
698 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
699
700 let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());
703
704 if tcx.dep_graph.is_fully_enabled() {
710 for cgu in codegen_units {
711 tcx.ensure_ok().codegen_unit(cgu.name());
712 }
713 }
714
715 let allocator_module = if let Some(kind) = allocator_kind_for_codegen(tcx) {
717 let llmod_id =
718 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
719
720 tcx.sess.time("write_allocator_module", || {
721 let module =
722 backend.codegen_allocator(tcx, &llmod_id, &allocator_shim_contents(tcx, kind));
723 Some(ModuleCodegen::new_allocator(llmod_id, module))
724 })
725 } else {
726 None
727 };
728
729 let ongoing_codegen = start_async_codegen(backend.clone(), tcx, crate_info, allocator_module);
730
731 let codegen_units: Vec<_> = {
743 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
744 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
745
746 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
747 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
748 };
749
750 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
752 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
753 });
754
755 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
756 for (i, cgu) in codegen_units.iter().enumerate() {
757 let cgu_reuse = cgu_reuse[i];
758 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
759 }
760 });
761
762 let mut total_codegen_time = Duration::new(0, 0);
763 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
764
765 let mut pre_compiled_cgus = if tcx.sess.threads() > 1 {
776 tcx.sess.time("compile_first_CGU_batch", || {
777 let cgus: Vec<_> = cgu_reuse
779 .iter()
780 .enumerate()
781 .filter(|&(_, reuse)| reuse == &CguReuse::No)
782 .take(tcx.sess.threads())
783 .collect();
784
785 let start_time = Instant::now();
787
788 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
789 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
790 (i, IntoDynSyncSend(module))
791 });
792
793 total_codegen_time += start_time.elapsed();
794
795 pre_compiled_cgus
796 })
797 } else {
798 FxHashMap::default()
799 };
800
801 for (i, cgu) in codegen_units.iter().enumerate() {
802 ongoing_codegen.wait_for_signal_to_codegen_item();
803 ongoing_codegen.check_for_errors(tcx.sess);
804
805 let cgu_reuse = cgu_reuse[i];
806
807 match cgu_reuse {
808 CguReuse::No => {
809 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
810 cgu.0
811 } else {
812 let start_time = Instant::now();
813 let module = backend.compile_codegen_unit(tcx, cgu.name());
814 total_codegen_time += start_time.elapsed();
815 module
816 };
817 tcx.dcx().abort_if_errors();
821
822 submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);
823 }
824 CguReuse::PreLto => {
825 submit_pre_lto_module_to_llvm(
826 tcx,
827 &ongoing_codegen.coordinator,
828 CachedModuleCodegen {
829 name: cgu.name().to_string(),
830 source: cgu.previous_work_product(tcx),
831 },
832 );
833 }
834 CguReuse::PostLto => {
835 submit_post_lto_module_to_llvm(
836 &ongoing_codegen.coordinator,
837 CachedModuleCodegen {
838 name: cgu.name().to_string(),
839 source: cgu.previous_work_product(tcx),
840 },
841 );
842 }
843 }
844 }
845
846 ongoing_codegen.codegen_finished(tcx);
847
848 if tcx.sess.opts.unstable_opts.time_passes {
851 let end_rss = get_resident_set_size();
852
853 print_time_passes_entry(
854 "codegen_to_LLVM_IR",
855 total_codegen_time,
856 start_rss.unwrap(),
857 end_rss,
858 tcx.sess.opts.unstable_opts.time_passes_format,
859 );
860 }
861
862 ongoing_codegen.check_for_errors(tcx.sess);
863 ongoing_codegen
864}
865
866pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
876 tcx: TyCtxt<'tcx>,
877 instance: Instance<'tcx>,
878) -> bool {
879 fn is_llvm_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
880 if let Some(name) = tcx.codegen_fn_attrs(def_id).symbol_name {
881 name.as_str().starts_with("llvm.")
882 } else {
883 false
884 }
885 }
886
887 let def_id = instance.def_id();
888 !def_id.is_local()
889 && tcx.is_compiler_builtins(LOCAL_CRATE)
890 && !is_llvm_intrinsic(tcx, def_id)
891 && !tcx.should_codegen_locally(instance)
892}
893
894impl CrateInfo {
895 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
896 let crate_types = tcx.crate_types().to_vec();
897 let exported_symbols = crate_types
898 .iter()
899 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
900 .collect();
901 let linked_symbols =
902 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
903 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
904 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);
905
906 let mut compiler_builtins = None;
915 let mut used_crates: Vec<_> = tcx
916 .postorder_cnums(())
917 .iter()
918 .rev()
919 .copied()
920 .filter(|&cnum| {
921 let link = !tcx.crate_dep_kind(cnum).macros_only();
922 if link && tcx.is_compiler_builtins(cnum) {
923 compiler_builtins = Some(cnum);
924 return false;
925 }
926 link
927 })
928 .collect();
929 used_crates.extend(compiler_builtins);
931
932 let crates = tcx.crates(());
933 let n_crates = crates.len();
934 let mut info = CrateInfo {
935 target_cpu,
936 target_features: tcx.global_backend_features(()).clone(),
937 crate_types,
938 exported_symbols,
939 linked_symbols,
940 local_crate_name,
941 compiler_builtins,
942 profiler_runtime: None,
943 is_no_builtins: Default::default(),
944 native_libraries: Default::default(),
945 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
946 crate_name: UnordMap::with_capacity(n_crates),
947 used_crates,
948 used_crate_source: UnordMap::with_capacity(n_crates),
949 dependency_formats: Arc::clone(tcx.dependency_formats(())),
950 windows_subsystem,
951 natvis_debugger_visualizers: Default::default(),
952 lint_levels: CodegenLintLevels::from_tcx(tcx),
953 metadata_symbol: exported_symbols::metadata_symbol_name(tcx),
954 };
955
956 info.native_libraries.reserve(n_crates);
957
958 for &cnum in crates.iter() {
959 info.native_libraries
960 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
961 info.crate_name.insert(cnum, tcx.crate_name(cnum));
962
963 let used_crate_source = tcx.used_crate_source(cnum);
964 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
965 if tcx.is_profiler_runtime(cnum) {
966 info.profiler_runtime = Some(cnum);
967 }
968 if tcx.is_no_builtins(cnum) {
969 info.is_no_builtins.insert(cnum);
970 }
971 }
972
973 let target = &tcx.sess.target;
982 if !are_upstream_rust_objects_already_included(tcx.sess) {
983 let add_prefix = match (target.is_like_windows, &target.arch) {
984 (true, Arch::X86) => |name: String, _: SymbolExportKind| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_{0}", name))
})format!("_{name}"),
985 (true, Arch::Arm64EC) => {
986 |name: String, export_kind: SymbolExportKind| match export_kind {
988 SymbolExportKind::Text => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#{0}", name))
})format!("#{name}"),
989 _ => name,
990 }
991 }
992 _ => |name: String, _: SymbolExportKind| name,
993 };
994 let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info
995 .used_crates
996 .iter()
997 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
998 .filter(|l| l.is_weak())
999 .filter_map(|&l| {
1000 let name = l.link_name()?;
1001 let export_kind = match l.target() {
1002 Target::Fn => SymbolExportKind::Text,
1003 Target::Static => SymbolExportKind::Data,
1004 _ => ::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!(
1005 "Don't know what the export kind is for lang item of kind {:?}",
1006 l.target()
1007 ),
1008 };
1009 lang_items::required(tcx, l).then_some((name, export_kind))
1010 })
1011 .collect();
1012
1013 #[allow(rustc::potential_query_instability)]
1016 info.linked_symbols
1017 .iter_mut()
1018 .filter(|(crate_type, _)| {
1019 !#[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib)
1020 })
1021 .for_each(|(_, linked_symbols)| {
1022 let mut symbols = missing_weak_lang_items
1023 .iter()
1024 .map(|(item, export_kind)| {
1025 (
1026 add_prefix(
1027 mangle_internal_symbol(tcx, item.as_str()),
1028 *export_kind,
1029 ),
1030 *export_kind,
1031 )
1032 })
1033 .collect::<Vec<_>>();
1034 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1035 linked_symbols.extend(symbols);
1036 });
1037 }
1038
1039 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1040 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1041 true
1044 }
1045 CrateType::ProcMacro => {
1046 false
1050 }
1051 CrateType::StaticLib | CrateType::Rlib => {
1052 false
1055 }
1056 });
1057
1058 if target.is_like_msvc && embed_visualizers {
1059 info.natvis_debugger_visualizers =
1060 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1061 }
1062
1063 info
1064 }
1065}
1066
1067pub(crate) fn provide(providers: &mut Providers) {
1068 providers.backend_optimization_level = |tcx, cratenum| {
1069 let for_speed = match tcx.sess.opts.optimize {
1070 config::OptLevel::No => return config::OptLevel::No,
1077 config::OptLevel::Less => return config::OptLevel::Less,
1079 config::OptLevel::More => return config::OptLevel::More,
1080 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1081 config::OptLevel::Size => config::OptLevel::More,
1084 config::OptLevel::SizeMin => config::OptLevel::More,
1085 };
1086
1087 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1088
1089 let any_for_speed = defids.items().any(|id| {
1090 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1091 #[allow(non_exhaustive_omitted_patterns)] match optimize {
OptimizeAttr::Speed => true,
_ => false,
}matches!(optimize, OptimizeAttr::Speed)
1092 });
1093
1094 if any_for_speed {
1095 return for_speed;
1096 }
1097
1098 tcx.sess.opts.optimize
1099 };
1100}
1101
1102pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1103 if !tcx.dep_graph.is_fully_enabled() {
1104 return CguReuse::No;
1105 }
1106
1107 let work_product_id = &cgu.work_product_id();
1108 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1109 return CguReuse::No;
1112 }
1113
1114 let dep_node = cgu.codegen_dep_node(tcx);
1121 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(tcx.sess, &dep_node, || {
1122 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("CompileCodegenUnit dep-node for CGU `{0}` already exists before marking.",
cgu.name()))
})format!(
1123 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1124 cgu.name()
1125 )
1126 });
1127
1128 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
1129 match compute_per_cgu_lto_type(
1133 &tcx.sess.lto(),
1134 tcx.sess.opts.cg.linker_plugin_lto.enabled(),
1135 tcx.crate_types(),
1136 ) {
1137 ComputedLtoType::No => CguReuse::PostLto,
1138 _ => CguReuse::PreLto,
1139 }
1140 } else {
1141 CguReuse::No
1142 }
1143}