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::{AttributeKind, DebuggerVisualizerType, OptimizeAttr};
17use rustc_hir::def_id::{CRATE_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::mir::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, 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::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
277 let (base, info) = match bx.load_operand(src).val {
278 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
279 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
280 OperandValue::Ref(..) | OperandValue::ZeroSized => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
281 };
282 OperandValue::Pair(base, info).store(bx, dst);
283 }
284
285 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
286 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() {
289 let src_f = src.project_field(bx, i.as_usize());
290 let dst_f = dst.project_field(bx, i.as_usize());
291
292 if dst_f.layout.is_zst() {
293 continue;
295 }
296
297 if src_f.layout.ty == dst_f.layout.ty {
298 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
299 } else {
300 coerce_unsized_into(bx, src_f, dst_f);
301 }
302 }
303 }
304 _ => ::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,),
305 }
306}
307
308pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
324 bx: &mut Bx,
325 lhs: Bx::Value,
326 mut rhs: Bx::Value,
327 is_unchecked: bool,
328) -> Bx::Value {
329 let mut rhs_llty = bx.cx().val_ty(rhs);
331 let mut lhs_llty = bx.cx().val_ty(lhs);
332
333 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
334 if !is_unchecked {
335 rhs = bx.and(rhs, mask);
336 }
337
338 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
339 rhs_llty = bx.cx().element_type(rhs_llty)
340 }
341 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
342 lhs_llty = bx.cx().element_type(lhs_llty)
343 }
344 let rhs_sz = bx.cx().int_width(rhs_llty);
345 let lhs_sz = bx.cx().int_width(lhs_llty);
346 if lhs_sz < rhs_sz {
347 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
348 } else if lhs_sz > rhs_sz {
349 if !(lhs_sz <= 256) {
::core::panicking::panic("assertion failed: lhs_sz <= 256")
};assert!(lhs_sz <= 256);
356 bx.zext(rhs, lhs_llty)
357 } else {
358 rhs
359 }
360}
361
362pub fn wants_wasm_eh(sess: &Session) -> bool {
366 sess.target.is_like_wasm
367 && (sess.target.os != Os::Emscripten || sess.opts.unstable_opts.emscripten_wasm_eh)
368}
369
370pub fn wants_msvc_seh(sess: &Session) -> bool {
376 sess.target.is_like_msvc
377}
378
379pub(crate) fn wants_new_eh_instructions(sess: &Session) -> bool {
383 wants_wasm_eh(sess) || wants_msvc_seh(sess)
384}
385
386pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
387 cx: &'a Bx::CodegenCx,
388 instance: Instance<'tcx>,
389) {
390 {
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:393",
"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(393u32),
::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);
394
395 mir::codegen_mir::<Bx>(cx, instance);
396}
397
398pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: ItemId)
399where
400 Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + AsmCodegenMethods<'tcx>,
401{
402 let item = cx.tcx().hir_item(item_id);
403 if let rustc_hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
404 let operands: Vec<_> = asm
405 .operands
406 .iter()
407 .map(|(op, op_sp)| match *op {
408 rustc_hir::InlineAsmOperand::Const { ref anon_const } => {
409 match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) {
410 Ok(const_value) => {
411 let ty =
412 cx.tcx().typeck_body(anon_const.body).node_type(anon_const.hir_id);
413 let string = common::asm_const_to_str(
414 cx.tcx(),
415 *op_sp,
416 const_value,
417 cx.layout_of(ty),
418 );
419 GlobalAsmOperandRef::Const { string }
420 }
421 Err(ErrorHandled::Reported { .. }) => {
422 GlobalAsmOperandRef::Const { string: String::new() }
427 }
428 Err(ErrorHandled::TooGeneric(_)) => {
429 ::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")
430 }
431 }
432 }
433 rustc_hir::InlineAsmOperand::SymFn { expr } => {
434 let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
435 let instance = match ty.kind() {
436 &ty::FnDef(def_id, args) => Instance::expect_resolve(
437 cx.tcx(),
438 ty::TypingEnv::fully_monomorphized(),
439 def_id,
440 args,
441 expr.span,
442 ),
443 _ => ::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"),
444 };
445
446 GlobalAsmOperandRef::SymFn { instance }
447 }
448 rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
449 GlobalAsmOperandRef::SymStatic { def_id }
450 }
451 rustc_hir::InlineAsmOperand::In { .. }
452 | rustc_hir::InlineAsmOperand::Out { .. }
453 | rustc_hir::InlineAsmOperand::InOut { .. }
454 | rustc_hir::InlineAsmOperand::SplitInOut { .. }
455 | rustc_hir::InlineAsmOperand::Label { .. } => {
456 ::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!")
457 }
458 })
459 .collect();
460
461 cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans);
462 } else {
463 ::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")
464 }
465}
466
467pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
470 cx: &'a Bx::CodegenCx,
471 cgu: &CodegenUnit<'tcx>,
472) -> Option<Bx::Function> {
473 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
474 let main_is_local = main_def_id.is_local();
475 let instance = Instance::mono(cx.tcx(), main_def_id);
476
477 if main_is_local {
478 if !cgu.contains_item(&MonoItem::Fn(instance)) {
481 return None;
482 }
483 } else if !cgu.is_primary() {
484 return None;
486 }
487
488 let main_llfn = cx.get_fn_addr(instance);
489
490 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
491 return Some(entry_fn);
492
493 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
494 cx: &'a Bx::CodegenCx,
495 rust_main: Bx::Value,
496 rust_main_def_id: DefId,
497 entry_type: EntryFnType,
498 ) -> Bx::Function {
499 let llfty = if cx.sess().target.os == Os::Uefi {
502 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
503 } else if cx.sess().target.main_needs_argc_argv {
504 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
505 } else {
506 cx.type_func(&[], cx.type_int())
507 };
508
509 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
510 let main_ret_ty = cx
516 .tcx()
517 .normalize_erasing_regions(cx.typing_env(), main_ret_ty.no_bound_vars().unwrap());
518
519 let Some(llfn) = cx.declare_c_main(llfty) else {
520 let span = cx.tcx().def_span(rust_main_def_id);
522 cx.tcx().dcx().emit_fatal(errors::MultipleMainFunctions { span });
523 };
524
525 cx.set_frame_pointer_type(llfn);
527 cx.apply_target_cpu_attr(llfn);
528
529 let llbb = Bx::append_block(cx, llfn, "top");
530 let mut bx = Bx::build(cx, llbb);
531
532 bx.insert_reference_to_gdb_debug_scripts_section_global();
533
534 let isize_ty = cx.type_isize();
535 let ptr_ty = cx.type_ptr();
536 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
537
538 let EntryFnType::Main { sigpipe } = entry_type;
539 let (start_fn, start_ty, args, instance) = {
540 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, DUMMY_SP);
541 let start_instance = ty::Instance::expect_resolve(
542 cx.tcx(),
543 cx.typing_env(),
544 start_def_id,
545 cx.tcx().mk_args(&[main_ret_ty.into()]),
546 DUMMY_SP,
547 );
548 let start_fn = cx.get_fn_addr(start_instance);
549
550 let i8_ty = cx.type_i8();
551 let arg_sigpipe = bx.const_u8(sigpipe);
552
553 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
554 (
555 start_fn,
556 start_ty,
557 <[_]>::into_vec(::alloc::boxed::box_new([rust_main, arg_argc, arg_argv,
arg_sigpipe]))vec![rust_main, arg_argc, arg_argv, arg_sigpipe],
558 Some(start_instance),
559 )
560 };
561
562 let result = bx.call(start_ty, None, None, start_fn, &args, None, instance);
563 if cx.sess().target.os == Os::Uefi {
564 bx.ret(result);
565 } else {
566 let cast = bx.intcast(result, cx.type_int(), true);
567 bx.ret(cast);
568 }
569
570 llfn
571 }
572}
573
574fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
577 if bx.cx().sess().target.os == Os::Uefi {
578 let param_handle = bx.get_param(0);
580 let param_system_table = bx.get_param(1);
581 let ptr_size = bx.tcx().data_layout.pointer_size();
582 let ptr_align = bx.tcx().data_layout.pointer_align().abi;
583 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
584 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
585 bx.store(param_handle, arg_argv, ptr_align);
586 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
587 bx.store(param_system_table, arg_argv_el1, ptr_align);
588 (arg_argc, arg_argv)
589 } else if bx.cx().sess().target.main_needs_argc_argv {
590 let param_argc = bx.get_param(0);
592 let param_argv = bx.get_param(1);
593 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
594 let arg_argv = param_argv;
595 (arg_argc, arg_argv)
596 } else {
597 let arg_argc = bx.const_int(bx.cx().type_int(), 0);
599 let arg_argv = bx.const_null(bx.cx().type_ptr());
600 (arg_argc, arg_argv)
601 }
602}
603
604pub fn collect_debugger_visualizers_transitive(
608 tcx: TyCtxt<'_>,
609 visualizer_type: DebuggerVisualizerType,
610) -> BTreeSet<DebuggerVisualizerFile> {
611 tcx.debugger_visualizers(LOCAL_CRATE)
612 .iter()
613 .chain(
614 tcx.crates(())
615 .iter()
616 .filter(|&cnum| {
617 let used_crate_source = tcx.used_crate_source(*cnum);
618 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
619 })
620 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
621 )
622 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
623 .cloned()
624 .collect::<BTreeSet<_>>()
625}
626
627pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
631 let all_crate_types_any_dynamic_crate = tcx.dependency_formats(()).iter().all(|(_, list)| {
641 use rustc_middle::middle::dependency_format::Linkage;
642 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
643 });
644 if all_crate_types_any_dynamic_crate { None } else { tcx.allocator_kind(()) }
645}
646
647pub(crate) fn needs_allocator_shim_for_linking(
651 dependency_formats: &Dependencies,
652 crate_type: CrateType,
653) -> bool {
654 use rustc_middle::middle::dependency_format::Linkage;
655 let any_dynamic_crate =
656 dependency_formats[&crate_type].iter().any(|&linkage| linkage == Linkage::Dynamic);
657 !any_dynamic_crate
658}
659
660pub fn allocator_shim_contents(tcx: TyCtxt<'_>, kind: AllocatorKind) -> Vec<AllocatorMethod> {
661 let mut methods = Vec::new();
662
663 if kind == AllocatorKind::Default {
664 methods.extend(ALLOCATOR_METHODS.into_iter().copied());
665 }
666
667 if tcx.alloc_error_handler_kind(()).unwrap() == AllocatorKind::Default {
670 methods.push(AllocatorMethod {
671 name: ALLOC_ERROR_HANDLER,
672 special: None,
673 inputs: &[AllocatorMethodInput { name: "layout", ty: AllocatorTy::Layout }],
674 output: AllocatorTy::Never,
675 });
676 }
677
678 methods
679}
680
681pub fn codegen_crate<B: ExtraBackendMethods>(
682 backend: B,
683 tcx: TyCtxt<'_>,
684 target_cpu: String,
685) -> OngoingCodegen<B> {
686 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
687 tcx.dcx().emit_fatal(errors::CpuRequired);
689 }
690
691 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
692
693 let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());
696
697 if tcx.dep_graph.is_fully_enabled() {
703 for cgu in codegen_units {
704 tcx.ensure_ok().codegen_unit(cgu.name());
705 }
706 }
707
708 let allocator_module = if let Some(kind) = allocator_kind_for_codegen(tcx) {
710 let llmod_id =
711 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
712
713 tcx.sess.time("write_allocator_module", || {
714 let module =
715 backend.codegen_allocator(tcx, &llmod_id, &allocator_shim_contents(tcx, kind));
716 Some(ModuleCodegen::new_allocator(llmod_id, module))
717 })
718 } else {
719 None
720 };
721
722 let ongoing_codegen = start_async_codegen(backend.clone(), tcx, target_cpu, allocator_module);
723
724 let codegen_units: Vec<_> = {
736 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
737 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
738
739 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
740 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
741 };
742
743 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
745 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
746 });
747
748 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
749 for (i, cgu) in codegen_units.iter().enumerate() {
750 let cgu_reuse = cgu_reuse[i];
751 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
752 }
753 });
754
755 let mut total_codegen_time = Duration::new(0, 0);
756 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
757
758 let mut pre_compiled_cgus = if tcx.sess.threads() > 1 {
769 tcx.sess.time("compile_first_CGU_batch", || {
770 let cgus: Vec<_> = cgu_reuse
772 .iter()
773 .enumerate()
774 .filter(|&(_, reuse)| reuse == &CguReuse::No)
775 .take(tcx.sess.threads())
776 .collect();
777
778 let start_time = Instant::now();
780
781 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
782 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
783 (i, IntoDynSyncSend(module))
784 });
785
786 total_codegen_time += start_time.elapsed();
787
788 pre_compiled_cgus
789 })
790 } else {
791 FxHashMap::default()
792 };
793
794 for (i, cgu) in codegen_units.iter().enumerate() {
795 ongoing_codegen.wait_for_signal_to_codegen_item();
796 ongoing_codegen.check_for_errors(tcx.sess);
797
798 let cgu_reuse = cgu_reuse[i];
799
800 match cgu_reuse {
801 CguReuse::No => {
802 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
803 cgu.0
804 } else {
805 let start_time = Instant::now();
806 let module = backend.compile_codegen_unit(tcx, cgu.name());
807 total_codegen_time += start_time.elapsed();
808 module
809 };
810 tcx.dcx().abort_if_errors();
814
815 submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);
816 }
817 CguReuse::PreLto => {
818 submit_pre_lto_module_to_llvm(
819 tcx,
820 &ongoing_codegen.coordinator,
821 CachedModuleCodegen {
822 name: cgu.name().to_string(),
823 source: cgu.previous_work_product(tcx),
824 },
825 );
826 }
827 CguReuse::PostLto => {
828 submit_post_lto_module_to_llvm(
829 &ongoing_codegen.coordinator,
830 CachedModuleCodegen {
831 name: cgu.name().to_string(),
832 source: cgu.previous_work_product(tcx),
833 },
834 );
835 }
836 }
837 }
838
839 ongoing_codegen.codegen_finished(tcx);
840
841 if tcx.sess.opts.unstable_opts.time_passes {
844 let end_rss = get_resident_set_size();
845
846 print_time_passes_entry(
847 "codegen_to_LLVM_IR",
848 total_codegen_time,
849 start_rss.unwrap(),
850 end_rss,
851 tcx.sess.opts.unstable_opts.time_passes_format,
852 );
853 }
854
855 ongoing_codegen.check_for_errors(tcx.sess);
856 ongoing_codegen
857}
858
859pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
869 tcx: TyCtxt<'tcx>,
870 instance: Instance<'tcx>,
871) -> bool {
872 fn is_llvm_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
873 if let Some(name) = tcx.codegen_fn_attrs(def_id).symbol_name {
874 name.as_str().starts_with("llvm.")
875 } else {
876 false
877 }
878 }
879
880 let def_id = instance.def_id();
881 !def_id.is_local()
882 && tcx.is_compiler_builtins(LOCAL_CRATE)
883 && !is_llvm_intrinsic(tcx, def_id)
884 && !tcx.should_codegen_locally(instance)
885}
886
887impl CrateInfo {
888 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
889 let crate_types = tcx.crate_types().to_vec();
890 let exported_symbols = crate_types
891 .iter()
892 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
893 .collect();
894 let linked_symbols =
895 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
896 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
897 let windows_subsystem = {
'done:
{
for i in tcx.get_all_attrs(CRATE_DEF_ID) {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::WindowsSubsystem(kind,
_)) => {
break 'done Some(*kind);
}
_ => {}
}
}
None
}
}find_attr!(tcx.get_all_attrs(CRATE_DEF_ID), AttributeKind::WindowsSubsystem(kind, _) => *kind);
898
899 let mut compiler_builtins = None;
908 let mut used_crates: Vec<_> = tcx
909 .postorder_cnums(())
910 .iter()
911 .rev()
912 .copied()
913 .filter(|&cnum| {
914 let link = !tcx.dep_kind(cnum).macros_only();
915 if link && tcx.is_compiler_builtins(cnum) {
916 compiler_builtins = Some(cnum);
917 return false;
918 }
919 link
920 })
921 .collect();
922 used_crates.extend(compiler_builtins);
924
925 let crates = tcx.crates(());
926 let n_crates = crates.len();
927 let mut info = CrateInfo {
928 target_cpu,
929 target_features: tcx.global_backend_features(()).clone(),
930 crate_types,
931 exported_symbols,
932 linked_symbols,
933 local_crate_name,
934 compiler_builtins,
935 profiler_runtime: None,
936 is_no_builtins: Default::default(),
937 native_libraries: Default::default(),
938 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
939 crate_name: UnordMap::with_capacity(n_crates),
940 used_crates,
941 used_crate_source: UnordMap::with_capacity(n_crates),
942 dependency_formats: Arc::clone(tcx.dependency_formats(())),
943 windows_subsystem,
944 natvis_debugger_visualizers: Default::default(),
945 lint_levels: CodegenLintLevels::from_tcx(tcx),
946 metadata_symbol: exported_symbols::metadata_symbol_name(tcx),
947 };
948
949 info.native_libraries.reserve(n_crates);
950
951 for &cnum in crates.iter() {
952 info.native_libraries
953 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
954 info.crate_name.insert(cnum, tcx.crate_name(cnum));
955
956 let used_crate_source = tcx.used_crate_source(cnum);
957 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
958 if tcx.is_profiler_runtime(cnum) {
959 info.profiler_runtime = Some(cnum);
960 }
961 if tcx.is_no_builtins(cnum) {
962 info.is_no_builtins.insert(cnum);
963 }
964 }
965
966 let target = &tcx.sess.target;
975 if !are_upstream_rust_objects_already_included(tcx.sess) {
976 let add_prefix = match (target.is_like_windows, &target.arch) {
977 (true, Arch::X86) => |name: String, _: SymbolExportKind| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("_{0}", name))
})format!("_{name}"),
978 (true, Arch::Arm64EC) => {
979 |name: String, export_kind: SymbolExportKind| match export_kind {
981 SymbolExportKind::Text => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#{0}", name))
})format!("#{name}"),
982 _ => name,
983 }
984 }
985 _ => |name: String, _: SymbolExportKind| name,
986 };
987 let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info
988 .used_crates
989 .iter()
990 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
991 .filter(|l| l.is_weak())
992 .filter_map(|&l| {
993 let name = l.link_name()?;
994 let export_kind = match l.target() {
995 Target::Fn => SymbolExportKind::Text,
996 Target::Static => SymbolExportKind::Data,
997 _ => ::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!(
998 "Don't know what the export kind is for lang item of kind {:?}",
999 l.target()
1000 ),
1001 };
1002 lang_items::required(tcx, l).then_some((name, export_kind))
1003 })
1004 .collect();
1005
1006 #[allow(rustc::potential_query_instability)]
1009 info.linked_symbols
1010 .iter_mut()
1011 .filter(|(crate_type, _)| {
1012 !#[allow(non_exhaustive_omitted_patterns)] match crate_type {
CrateType::Rlib | CrateType::StaticLib => true,
_ => false,
}matches!(crate_type, CrateType::Rlib | CrateType::StaticLib)
1013 })
1014 .for_each(|(_, linked_symbols)| {
1015 let mut symbols = missing_weak_lang_items
1016 .iter()
1017 .map(|(item, export_kind)| {
1018 (
1019 add_prefix(
1020 mangle_internal_symbol(tcx, item.as_str()),
1021 *export_kind,
1022 ),
1023 *export_kind,
1024 )
1025 })
1026 .collect::<Vec<_>>();
1027 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1028 linked_symbols.extend(symbols);
1029 });
1030 }
1031
1032 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1033 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1034 true
1037 }
1038 CrateType::ProcMacro => {
1039 false
1043 }
1044 CrateType::StaticLib | CrateType::Rlib => {
1045 false
1048 }
1049 });
1050
1051 if target.is_like_msvc && embed_visualizers {
1052 info.natvis_debugger_visualizers =
1053 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1054 }
1055
1056 info
1057 }
1058}
1059
1060pub(crate) fn provide(providers: &mut Providers) {
1061 providers.backend_optimization_level = |tcx, cratenum| {
1062 let for_speed = match tcx.sess.opts.optimize {
1063 config::OptLevel::No => return config::OptLevel::No,
1070 config::OptLevel::Less => return config::OptLevel::Less,
1072 config::OptLevel::More => return config::OptLevel::More,
1073 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1074 config::OptLevel::Size => config::OptLevel::More,
1077 config::OptLevel::SizeMin => config::OptLevel::More,
1078 };
1079
1080 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1081
1082 let any_for_speed = defids.items().any(|id| {
1083 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1084 #[allow(non_exhaustive_omitted_patterns)] match optimize {
OptimizeAttr::Speed => true,
_ => false,
}matches!(optimize, OptimizeAttr::Speed)
1085 });
1086
1087 if any_for_speed {
1088 return for_speed;
1089 }
1090
1091 tcx.sess.opts.optimize
1092 };
1093}
1094
1095pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1096 if !tcx.dep_graph.is_fully_enabled() {
1097 return CguReuse::No;
1098 }
1099
1100 let work_product_id = &cgu.work_product_id();
1101 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1102 return CguReuse::No;
1105 }
1106
1107 let dep_node = cgu.codegen_dep_node(tcx);
1114 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(&dep_node, || {
1115 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("CompileCodegenUnit dep-node for CGU `{0}` already exists before marking.",
cgu.name()))
})format!(
1116 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1117 cgu.name()
1118 )
1119 });
1120
1121 if tcx.try_mark_green(&dep_node) {
1122 match compute_per_cgu_lto_type(
1126 &tcx.sess.lto(),
1127 tcx.sess.opts.cg.linker_plugin_lto.enabled(),
1128 tcx.crate_types(),
1129 ) {
1130 ComputedLtoType::No => CguReuse::PostLto,
1131 _ => CguReuse::PreLto,
1132 }
1133 } else {
1134 CguReuse::No
1135 }
1136}