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 as ast;
9use rustc_ast::expand::allocator::{ALLOCATOR_METHODS, AllocatorKind, global_fn_name};
10use rustc_attr_data_structures::OptimizeAttr;
11use rustc_data_structures::fx::{FxHashMap, FxIndexSet};
12use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
13use rustc_data_structures::sync::{IntoDynSyncSend, par_map};
14use rustc_data_structures::unord::UnordMap;
15use rustc_hir::ItemId;
16use rustc_hir::def_id::{DefId, LOCAL_CRATE};
17use rustc_hir::lang_items::LangItem;
18use rustc_metadata::EncodedMetadata;
19use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
20use rustc_middle::middle::debugger_visualizer::{DebuggerVisualizerFile, DebuggerVisualizerType};
21use rustc_middle::middle::exported_symbols::SymbolExportKind;
22use rustc_middle::middle::{exported_symbols, lang_items};
23use rustc_middle::mir::BinOp;
24use rustc_middle::mir::interpret::ErrorHandled;
25use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem, MonoItemPartitions};
26use rustc_middle::query::Providers;
27use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
28use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
29use rustc_middle::{bug, span_bug};
30use rustc_session::Session;
31use rustc_session::config::{self, CrateType, EntryFnType, OutputType};
32use rustc_span::{DUMMY_SP, Symbol, sym};
33use rustc_symbol_mangling::mangle_internal_symbol;
34use rustc_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt};
35use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt};
36use tracing::{debug, info};
37
38use crate::assert_module_sources::CguReuse;
39use crate::back::link::are_upstream_rust_objects_already_included;
40use crate::back::metadata::create_compressed_metadata_file;
41use crate::back::write::{
42 ComputedLtoType, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen,
43 submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm,
44};
45use crate::common::{self, IntPredicate, RealPredicate, TypeKind};
46use crate::meth::load_vtable;
47use crate::mir::operand::OperandValue;
48use crate::mir::place::PlaceRef;
49use crate::traits::*;
50use crate::{
51 CachedModuleCodegen, CodegenLintLevels, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
52 errors, meth, mir,
53};
54
55pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
56 match (op, signed) {
57 (BinOp::Eq, _) => IntPredicate::IntEQ,
58 (BinOp::Ne, _) => IntPredicate::IntNE,
59 (BinOp::Lt, true) => IntPredicate::IntSLT,
60 (BinOp::Lt, false) => IntPredicate::IntULT,
61 (BinOp::Le, true) => IntPredicate::IntSLE,
62 (BinOp::Le, false) => IntPredicate::IntULE,
63 (BinOp::Gt, true) => IntPredicate::IntSGT,
64 (BinOp::Gt, false) => IntPredicate::IntUGT,
65 (BinOp::Ge, true) => IntPredicate::IntSGE,
66 (BinOp::Ge, false) => IntPredicate::IntUGE,
67 op => bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),
68 }
69}
70
71pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
72 match op {
73 BinOp::Eq => RealPredicate::RealOEQ,
74 BinOp::Ne => RealPredicate::RealUNE,
75 BinOp::Lt => RealPredicate::RealOLT,
76 BinOp::Le => RealPredicate::RealOLE,
77 BinOp::Gt => RealPredicate::RealOGT,
78 BinOp::Ge => RealPredicate::RealOGE,
79 op => bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),
80 }
81}
82
83pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
84 bx: &mut Bx,
85 lhs: Bx::Value,
86 rhs: Bx::Value,
87 t: Ty<'tcx>,
88 ret_ty: Bx::Type,
89 op: BinOp,
90) -> Bx::Value {
91 let signed = match t.kind() {
92 ty::Float(_) => {
93 let cmp = bin_op_to_fcmp_predicate(op);
94 let cmp = bx.fcmp(cmp, lhs, rhs);
95 return bx.sext(cmp, ret_ty);
96 }
97 ty::Uint(_) => false,
98 ty::Int(_) => true,
99 _ => bug!("compare_simd_types: invalid SIMD type"),
100 };
101
102 let cmp = bin_op_to_icmp_predicate(op, signed);
103 let cmp = bx.icmp(cmp, lhs, rhs);
104 bx.sext(cmp, ret_ty)
109}
110
111pub fn validate_trivial_unsize<'tcx>(
120 tcx: TyCtxt<'tcx>,
121 source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
122 target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
123) -> bool {
124 match (source_data.principal(), target_data.principal()) {
125 (Some(hr_source_principal), Some(hr_target_principal)) => {
126 let (infcx, param_env) =
127 tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
128 let universe = infcx.universe();
129 let ocx = ObligationCtxt::new(&infcx);
130 infcx.enter_forall(hr_target_principal, |target_principal| {
131 let source_principal = infcx.instantiate_binder_with_fresh_vars(
132 DUMMY_SP,
133 BoundRegionConversionTime::HigherRankedType,
134 hr_source_principal,
135 );
136 let Ok(()) = ocx.eq(
137 &ObligationCause::dummy(),
138 param_env,
139 target_principal,
140 source_principal,
141 ) else {
142 return false;
143 };
144 if !ocx.select_all_or_error().is_empty() {
145 return false;
146 }
147 infcx.leak_check(universe, None).is_ok()
148 })
149 }
150 (_, None) => true,
151 _ => false,
152 }
153}
154
155fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
161 bx: &mut Bx,
162 source: Ty<'tcx>,
163 target: Ty<'tcx>,
164 old_info: Option<Bx::Value>,
165) -> Bx::Value {
166 let cx = bx.cx();
167 let (source, target) =
168 cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
169 match (source.kind(), target.kind()) {
170 (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
171 len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
172 ),
173 (&ty::Dynamic(data_a, _, src_dyn_kind), &ty::Dynamic(data_b, _, target_dyn_kind))
174 if src_dyn_kind == target_dyn_kind =>
175 {
176 let old_info =
177 old_info.expect("unsized_info: missing old info for trait upcasting coercion");
178 let b_principal_def_id = data_b.principal_def_id();
179 if data_a.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {
180 debug_assert!(
189 validate_trivial_unsize(cx.tcx(), data_a, data_b),
190 "NOP unsize vtable changed principal trait ref: {data_a} -> {data_b}"
191 );
192
193 return old_info;
199 }
200
201 let vptr_entry_idx = cx.tcx().supertrait_vtable_slot((source, target));
204
205 if let Some(entry_idx) = vptr_entry_idx {
206 let ptr_size = bx.data_layout().pointer_size;
207 let vtable_byte_offset = u64::try_from(entry_idx).unwrap() * ptr_size.bytes();
208 load_vtable(bx, old_info, bx.type_ptr(), vtable_byte_offset, source, true)
209 } else {
210 old_info
211 }
212 }
213 (_, ty::Dynamic(data, _, _)) => meth::get_vtable(
214 cx,
215 source,
216 data.principal()
217 .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),
218 ),
219 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
220 }
221}
222
223pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
225 bx: &mut Bx,
226 src: Bx::Value,
227 src_ty: Ty<'tcx>,
228 dst_ty: Ty<'tcx>,
229 old_info: Option<Bx::Value>,
230) -> (Bx::Value, Bx::Value) {
231 debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
232 match (src_ty.kind(), dst_ty.kind()) {
233 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
234 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
235 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 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 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
254 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
255 assert_eq!(src_layout.size, src_f.size);
256
257 let dst_f = dst_layout.field(bx.cx(), i);
258 assert_ne!(src_f.ty, dst_f.ty);
259 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 _ => bug!("unsize_ptr: called on bad types"),
265 }
266}
267
268pub(crate) fn cast_to_dyn_star<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
270 bx: &mut Bx,
271 src: Bx::Value,
272 src_ty_and_layout: TyAndLayout<'tcx>,
273 dst_ty: Ty<'tcx>,
274 old_info: Option<Bx::Value>,
275) -> (Bx::Value, Bx::Value) {
276 debug!("cast_to_dyn_star: {:?} => {:?}", src_ty_and_layout.ty, dst_ty);
277 assert!(
278 matches!(dst_ty.kind(), ty::Dynamic(_, _, ty::DynStar)),
279 "destination type must be a dyn*"
280 );
281 let src = match bx.cx().type_kind(bx.cx().backend_type(src_ty_and_layout)) {
282 TypeKind::Pointer => src,
283 TypeKind::Integer => bx.inttoptr(src, bx.type_ptr()),
284 kind => bug!("unexpected TypeKind for left-hand side of `dyn*` cast: {kind:?}"),
286 };
287 (src, unsized_info(bx, src_ty_and_layout.ty, dst_ty, old_info))
288}
289
290pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
293 bx: &mut Bx,
294 src: PlaceRef<'tcx, Bx::Value>,
295 dst: PlaceRef<'tcx, Bx::Value>,
296) {
297 let src_ty = src.layout.ty;
298 let dst_ty = dst.layout.ty;
299 match (src_ty.kind(), dst_ty.kind()) {
300 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
301 let (base, info) = match bx.load_operand(src).val {
302 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
303 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
304 OperandValue::Ref(..) | OperandValue::ZeroSized => bug!(),
305 };
306 OperandValue::Pair(base, info).store(bx, dst);
307 }
308
309 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
310 assert_eq!(def_a, def_b); for i in def_a.variant(FIRST_VARIANT).fields.indices() {
313 let src_f = src.project_field(bx, i.as_usize());
314 let dst_f = dst.project_field(bx, i.as_usize());
315
316 if dst_f.layout.is_zst() {
317 continue;
319 }
320
321 if src_f.layout.ty == dst_f.layout.ty {
322 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
323 } else {
324 coerce_unsized_into(bx, src_f, dst_f);
325 }
326 }
327 }
328 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
329 }
330}
331
332pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
348 bx: &mut Bx,
349 lhs: Bx::Value,
350 mut rhs: Bx::Value,
351 is_unchecked: bool,
352) -> Bx::Value {
353 let mut rhs_llty = bx.cx().val_ty(rhs);
355 let mut lhs_llty = bx.cx().val_ty(lhs);
356
357 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
358 if !is_unchecked {
359 rhs = bx.and(rhs, mask);
360 }
361
362 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
363 rhs_llty = bx.cx().element_type(rhs_llty)
364 }
365 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
366 lhs_llty = bx.cx().element_type(lhs_llty)
367 }
368 let rhs_sz = bx.cx().int_width(rhs_llty);
369 let lhs_sz = bx.cx().int_width(lhs_llty);
370 if lhs_sz < rhs_sz {
371 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
372 } else if lhs_sz > rhs_sz {
373 assert!(lhs_sz <= 256);
380 bx.zext(rhs, lhs_llty)
381 } else {
382 rhs
383 }
384}
385
386pub fn wants_wasm_eh(sess: &Session) -> bool {
390 sess.target.is_like_wasm
391 && (sess.target.os != "emscripten" || sess.opts.unstable_opts.emscripten_wasm_eh)
392}
393
394pub fn wants_msvc_seh(sess: &Session) -> bool {
400 sess.target.is_like_msvc
401}
402
403pub(crate) fn wants_new_eh_instructions(sess: &Session) -> bool {
407 wants_wasm_eh(sess) || wants_msvc_seh(sess)
408}
409
410pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
411 cx: &'a Bx::CodegenCx,
412 instance: Instance<'tcx>,
413) {
414 info!("codegen_instance({})", instance);
418
419 mir::codegen_mir::<Bx>(cx, instance);
420}
421
422pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: ItemId)
423where
424 Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + AsmCodegenMethods<'tcx>,
425{
426 let item = cx.tcx().hir_item(item_id);
427 if let rustc_hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
428 let operands: Vec<_> = asm
429 .operands
430 .iter()
431 .map(|(op, op_sp)| match *op {
432 rustc_hir::InlineAsmOperand::Const { ref anon_const } => {
433 match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) {
434 Ok(const_value) => {
435 let ty =
436 cx.tcx().typeck_body(anon_const.body).node_type(anon_const.hir_id);
437 let string = common::asm_const_to_str(
438 cx.tcx(),
439 *op_sp,
440 const_value,
441 cx.layout_of(ty),
442 );
443 GlobalAsmOperandRef::Const { string }
444 }
445 Err(ErrorHandled::Reported { .. }) => {
446 GlobalAsmOperandRef::Const { string: String::new() }
451 }
452 Err(ErrorHandled::TooGeneric(_)) => {
453 span_bug!(*op_sp, "asm const cannot be resolved; too generic")
454 }
455 }
456 }
457 rustc_hir::InlineAsmOperand::SymFn { expr } => {
458 let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
459 let instance = match ty.kind() {
460 &ty::FnDef(def_id, args) => Instance::expect_resolve(
461 cx.tcx(),
462 ty::TypingEnv::fully_monomorphized(),
463 def_id,
464 args,
465 expr.span,
466 ),
467 _ => span_bug!(*op_sp, "asm sym is not a function"),
468 };
469
470 GlobalAsmOperandRef::SymFn { instance }
471 }
472 rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
473 GlobalAsmOperandRef::SymStatic { def_id }
474 }
475 rustc_hir::InlineAsmOperand::In { .. }
476 | rustc_hir::InlineAsmOperand::Out { .. }
477 | rustc_hir::InlineAsmOperand::InOut { .. }
478 | rustc_hir::InlineAsmOperand::SplitInOut { .. }
479 | rustc_hir::InlineAsmOperand::Label { .. } => {
480 span_bug!(*op_sp, "invalid operand type for global_asm!")
481 }
482 })
483 .collect();
484
485 cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans);
486 } else {
487 span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
488 }
489}
490
491pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
494 cx: &'a Bx::CodegenCx,
495) -> Option<Bx::Function> {
496 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
497 let main_is_local = main_def_id.is_local();
498 let instance = Instance::mono(cx.tcx(), main_def_id);
499
500 if main_is_local {
501 if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
504 return None;
505 }
506 } else if !cx.codegen_unit().is_primary() {
507 return None;
509 }
510
511 let main_llfn = cx.get_fn_addr(instance);
512
513 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
514 return Some(entry_fn);
515
516 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
517 cx: &'a Bx::CodegenCx,
518 rust_main: Bx::Value,
519 rust_main_def_id: DefId,
520 entry_type: EntryFnType,
521 ) -> Bx::Function {
522 let llfty = if cx.sess().target.os.contains("uefi") {
525 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
526 } else if cx.sess().target.main_needs_argc_argv {
527 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
528 } else {
529 cx.type_func(&[], cx.type_int())
530 };
531
532 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
533 let main_ret_ty = cx
539 .tcx()
540 .normalize_erasing_regions(cx.typing_env(), main_ret_ty.no_bound_vars().unwrap());
541
542 let Some(llfn) = cx.declare_c_main(llfty) else {
543 let span = cx.tcx().def_span(rust_main_def_id);
545 cx.tcx().dcx().emit_fatal(errors::MultipleMainFunctions { span });
546 };
547
548 cx.set_frame_pointer_type(llfn);
550 cx.apply_target_cpu_attr(llfn);
551
552 let llbb = Bx::append_block(cx, llfn, "top");
553 let mut bx = Bx::build(cx, llbb);
554
555 bx.insert_reference_to_gdb_debug_scripts_section_global();
556
557 let isize_ty = cx.type_isize();
558 let ptr_ty = cx.type_ptr();
559 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
560
561 let EntryFnType::Main { sigpipe } = entry_type;
562 let (start_fn, start_ty, args, instance) = {
563 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, None);
564 let start_instance = ty::Instance::expect_resolve(
565 cx.tcx(),
566 cx.typing_env(),
567 start_def_id,
568 cx.tcx().mk_args(&[main_ret_ty.into()]),
569 DUMMY_SP,
570 );
571 let start_fn = cx.get_fn_addr(start_instance);
572
573 let i8_ty = cx.type_i8();
574 let arg_sigpipe = bx.const_u8(sigpipe);
575
576 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
577 (
578 start_fn,
579 start_ty,
580 vec![rust_main, arg_argc, arg_argv, arg_sigpipe],
581 Some(start_instance),
582 )
583 };
584
585 let result = bx.call(start_ty, None, None, start_fn, &args, None, instance);
586 if cx.sess().target.os.contains("uefi") {
587 bx.ret(result);
588 } else {
589 let cast = bx.intcast(result, cx.type_int(), true);
590 bx.ret(cast);
591 }
592
593 llfn
594 }
595}
596
597fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
600 if bx.cx().sess().target.os.contains("uefi") {
601 let param_handle = bx.get_param(0);
603 let param_system_table = bx.get_param(1);
604 let ptr_size = bx.tcx().data_layout.pointer_size;
605 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
606 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
607 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
608 bx.store(param_handle, arg_argv, ptr_align);
609 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
610 bx.store(param_system_table, arg_argv_el1, ptr_align);
611 (arg_argc, arg_argv)
612 } else if bx.cx().sess().target.main_needs_argc_argv {
613 let param_argc = bx.get_param(0);
615 let param_argv = bx.get_param(1);
616 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
617 let arg_argv = param_argv;
618 (arg_argc, arg_argv)
619 } else {
620 let arg_argc = bx.const_int(bx.cx().type_int(), 0);
622 let arg_argv = bx.const_null(bx.cx().type_ptr());
623 (arg_argc, arg_argv)
624 }
625}
626
627pub fn collect_debugger_visualizers_transitive(
631 tcx: TyCtxt<'_>,
632 visualizer_type: DebuggerVisualizerType,
633) -> BTreeSet<DebuggerVisualizerFile> {
634 tcx.debugger_visualizers(LOCAL_CRATE)
635 .iter()
636 .chain(
637 tcx.crates(())
638 .iter()
639 .filter(|&cnum| {
640 let used_crate_source = tcx.used_crate_source(*cnum);
641 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
642 })
643 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
644 )
645 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
646 .cloned()
647 .collect::<BTreeSet<_>>()
648}
649
650pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
654 let any_dynamic_crate = tcx.dependency_formats(()).iter().any(|(_, list)| {
661 use rustc_middle::middle::dependency_format::Linkage;
662 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
663 });
664 if any_dynamic_crate { None } else { tcx.allocator_kind(()) }
665}
666
667pub fn codegen_crate<B: ExtraBackendMethods>(
668 backend: B,
669 tcx: TyCtxt<'_>,
670 target_cpu: String,
671 metadata: EncodedMetadata,
672 need_metadata_module: bool,
673) -> OngoingCodegen<B> {
674 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
676 let ongoing_codegen = start_async_codegen(backend, tcx, target_cpu, metadata, None);
677
678 ongoing_codegen.codegen_finished(tcx);
679
680 ongoing_codegen.check_for_errors(tcx.sess);
681
682 return ongoing_codegen;
683 }
684
685 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
686 tcx.dcx().emit_fatal(errors::CpuRequired);
688 }
689
690 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
691
692 let MonoItemPartitions { codegen_units, autodiff_items, .. } =
695 tcx.collect_and_partition_mono_items(());
696 let autodiff_fncs = autodiff_items.to_vec();
697
698 if tcx.dep_graph.is_fully_enabled() {
704 for cgu in codegen_units {
705 tcx.ensure_ok().codegen_unit(cgu.name());
706 }
707 }
708
709 let metadata_module = need_metadata_module.then(|| {
710 let metadata_cgu_name =
712 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
713 tcx.sess.time("write_compressed_metadata", || {
714 let file_name = tcx.output_filenames(()).temp_path_for_cgu(
715 OutputType::Metadata,
716 &metadata_cgu_name,
717 tcx.sess.invocation_temp.as_deref(),
718 );
719 let data = create_compressed_metadata_file(
720 tcx.sess,
721 &metadata,
722 &exported_symbols::metadata_symbol_name(tcx),
723 );
724 if let Err(error) = std::fs::write(&file_name, data) {
725 tcx.dcx().emit_fatal(errors::MetadataObjectFileWrite { error });
726 }
727 CompiledModule {
728 name: metadata_cgu_name,
729 kind: ModuleKind::Metadata,
730 object: Some(file_name),
731 dwarf_object: None,
732 bytecode: None,
733 assembly: None,
734 llvm_ir: None,
735 links_from_incr_cache: Vec::new(),
736 }
737 })
738 });
739
740 let ongoing_codegen =
741 start_async_codegen(backend.clone(), tcx, target_cpu, metadata, metadata_module);
742
743 if let Some(kind) = allocator_kind_for_codegen(tcx) {
745 let llmod_id =
746 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
747 let module_llvm = tcx.sess.time("write_allocator_module", || {
748 backend.codegen_allocator(
749 tcx,
750 &llmod_id,
751 kind,
752 tcx.alloc_error_handler_kind(()).unwrap(),
755 )
756 });
757
758 ongoing_codegen.wait_for_signal_to_codegen_item();
759 ongoing_codegen.check_for_errors(tcx.sess);
760
761 let cost = 0;
763 submit_codegened_module_to_llvm(
764 &backend,
765 &ongoing_codegen.coordinator.sender,
766 ModuleCodegen::new_allocator(llmod_id, module_llvm),
767 cost,
768 );
769 }
770
771 if !autodiff_fncs.is_empty() {
772 ongoing_codegen.submit_autodiff_items(autodiff_fncs);
773 }
774
775 let codegen_units: Vec<_> = {
787 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
788 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
789
790 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
791 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
792 };
793
794 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
796 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
797 });
798
799 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
800 for (i, cgu) in codegen_units.iter().enumerate() {
801 let cgu_reuse = cgu_reuse[i];
802 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
803 }
804 });
805
806 let mut total_codegen_time = Duration::new(0, 0);
807 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
808
809 let mut pre_compiled_cgus = if tcx.sess.threads() > 1 {
820 tcx.sess.time("compile_first_CGU_batch", || {
821 let cgus: Vec<_> = cgu_reuse
823 .iter()
824 .enumerate()
825 .filter(|&(_, reuse)| reuse == &CguReuse::No)
826 .take(tcx.sess.threads())
827 .collect();
828
829 let start_time = Instant::now();
831
832 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
833 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
834 (i, IntoDynSyncSend(module))
835 });
836
837 total_codegen_time += start_time.elapsed();
838
839 pre_compiled_cgus
840 })
841 } else {
842 FxHashMap::default()
843 };
844
845 for (i, cgu) in codegen_units.iter().enumerate() {
846 ongoing_codegen.wait_for_signal_to_codegen_item();
847 ongoing_codegen.check_for_errors(tcx.sess);
848
849 let cgu_reuse = cgu_reuse[i];
850
851 match cgu_reuse {
852 CguReuse::No => {
853 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
854 cgu.0
855 } else {
856 let start_time = Instant::now();
857 let module = backend.compile_codegen_unit(tcx, cgu.name());
858 total_codegen_time += start_time.elapsed();
859 module
860 };
861 tcx.dcx().abort_if_errors();
865
866 submit_codegened_module_to_llvm(
867 &backend,
868 &ongoing_codegen.coordinator.sender,
869 module,
870 cost,
871 );
872 }
873 CguReuse::PreLto => {
874 submit_pre_lto_module_to_llvm(
875 &backend,
876 tcx,
877 &ongoing_codegen.coordinator.sender,
878 CachedModuleCodegen {
879 name: cgu.name().to_string(),
880 source: cgu.previous_work_product(tcx),
881 },
882 );
883 }
884 CguReuse::PostLto => {
885 submit_post_lto_module_to_llvm(
886 &backend,
887 &ongoing_codegen.coordinator.sender,
888 CachedModuleCodegen {
889 name: cgu.name().to_string(),
890 source: cgu.previous_work_product(tcx),
891 },
892 );
893 }
894 }
895 }
896
897 ongoing_codegen.codegen_finished(tcx);
898
899 if tcx.sess.opts.unstable_opts.time_passes {
902 let end_rss = get_resident_set_size();
903
904 print_time_passes_entry(
905 "codegen_to_LLVM_IR",
906 total_codegen_time,
907 start_rss.unwrap(),
908 end_rss,
909 tcx.sess.opts.unstable_opts.time_passes_format,
910 );
911 }
912
913 ongoing_codegen.check_for_errors(tcx.sess);
914 ongoing_codegen
915}
916
917pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
927 tcx: TyCtxt<'tcx>,
928 instance: Instance<'tcx>,
929) -> bool {
930 fn is_llvm_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
931 if let Some(name) = tcx.codegen_fn_attrs(def_id).link_name {
932 name.as_str().starts_with("llvm.")
933 } else {
934 false
935 }
936 }
937
938 let def_id = instance.def_id();
939 !def_id.is_local()
940 && tcx.is_compiler_builtins(LOCAL_CRATE)
941 && !is_llvm_intrinsic(tcx, def_id)
942 && !tcx.should_codegen_locally(instance)
943}
944
945impl CrateInfo {
946 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
947 let crate_types = tcx.crate_types().to_vec();
948 let exported_symbols = crate_types
949 .iter()
950 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
951 .collect();
952 let linked_symbols =
953 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
954 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
955 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
956 let subsystem =
957 ast::attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
958 let windows_subsystem = subsystem.map(|subsystem| {
959 if subsystem != sym::windows && subsystem != sym::console {
960 tcx.dcx().emit_fatal(errors::InvalidWindowsSubsystem { subsystem });
961 }
962 subsystem.to_string()
963 });
964
965 let mut compiler_builtins = None;
974 let mut used_crates: Vec<_> = tcx
975 .postorder_cnums(())
976 .iter()
977 .rev()
978 .copied()
979 .filter(|&cnum| {
980 let link = !tcx.dep_kind(cnum).macros_only();
981 if link && tcx.is_compiler_builtins(cnum) {
982 compiler_builtins = Some(cnum);
983 return false;
984 }
985 link
986 })
987 .collect();
988 used_crates.extend(compiler_builtins);
990
991 let crates = tcx.crates(());
992 let n_crates = crates.len();
993 let mut info = CrateInfo {
994 target_cpu,
995 target_features: tcx.global_backend_features(()).clone(),
996 crate_types,
997 exported_symbols,
998 linked_symbols,
999 local_crate_name,
1000 compiler_builtins,
1001 profiler_runtime: None,
1002 is_no_builtins: Default::default(),
1003 native_libraries: Default::default(),
1004 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
1005 crate_name: UnordMap::with_capacity(n_crates),
1006 used_crates,
1007 used_crate_source: UnordMap::with_capacity(n_crates),
1008 dependency_formats: Arc::clone(tcx.dependency_formats(())),
1009 windows_subsystem,
1010 natvis_debugger_visualizers: Default::default(),
1011 lint_levels: CodegenLintLevels::from_tcx(tcx),
1012 };
1013
1014 info.native_libraries.reserve(n_crates);
1015
1016 for &cnum in crates.iter() {
1017 info.native_libraries
1018 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
1019 info.crate_name.insert(cnum, tcx.crate_name(cnum));
1020
1021 let used_crate_source = tcx.used_crate_source(cnum);
1022 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
1023 if tcx.is_profiler_runtime(cnum) {
1024 info.profiler_runtime = Some(cnum);
1025 }
1026 if tcx.is_no_builtins(cnum) {
1027 info.is_no_builtins.insert(cnum);
1028 }
1029 }
1030
1031 let target = &tcx.sess.target;
1040 if !are_upstream_rust_objects_already_included(tcx.sess) {
1041 let missing_weak_lang_items: FxIndexSet<Symbol> = info
1042 .used_crates
1043 .iter()
1044 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
1045 .filter(|l| l.is_weak())
1046 .filter_map(|&l| {
1047 let name = l.link_name()?;
1048 lang_items::required(tcx, l).then_some(name)
1049 })
1050 .collect();
1051 let prefix = match (target.is_like_windows, target.arch.as_ref()) {
1052 (true, "x86") => "_",
1053 (true, "arm64ec") => "#",
1054 _ => "",
1055 };
1056
1057 #[allow(rustc::potential_query_instability)]
1060 info.linked_symbols
1061 .iter_mut()
1062 .filter(|(crate_type, _)| {
1063 !matches!(crate_type, CrateType::Rlib | CrateType::Staticlib)
1064 })
1065 .for_each(|(_, linked_symbols)| {
1066 let mut symbols = missing_weak_lang_items
1067 .iter()
1068 .map(|item| {
1069 (
1070 format!("{prefix}{}", mangle_internal_symbol(tcx, item.as_str())),
1071 SymbolExportKind::Text,
1072 )
1073 })
1074 .collect::<Vec<_>>();
1075 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1076 linked_symbols.extend(symbols);
1077 if tcx.allocator_kind(()).is_some() {
1078 linked_symbols.extend(ALLOCATOR_METHODS.iter().map(|method| {
1085 (
1086 format!(
1087 "{prefix}{}",
1088 mangle_internal_symbol(
1089 tcx,
1090 global_fn_name(method.name).as_str()
1091 )
1092 ),
1093 SymbolExportKind::Text,
1094 )
1095 }));
1096 }
1097 });
1098 }
1099
1100 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1101 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1102 true
1105 }
1106 CrateType::ProcMacro => {
1107 false
1111 }
1112 CrateType::Staticlib | CrateType::Rlib => {
1113 false
1116 }
1117 });
1118
1119 if target.is_like_msvc && embed_visualizers {
1120 info.natvis_debugger_visualizers =
1121 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1122 }
1123
1124 info
1125 }
1126}
1127
1128pub(crate) fn provide(providers: &mut Providers) {
1129 providers.backend_optimization_level = |tcx, cratenum| {
1130 let for_speed = match tcx.sess.opts.optimize {
1131 config::OptLevel::No => return config::OptLevel::No,
1138 config::OptLevel::Less => return config::OptLevel::Less,
1140 config::OptLevel::More => return config::OptLevel::More,
1141 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1142 config::OptLevel::Size => config::OptLevel::More,
1145 config::OptLevel::SizeMin => config::OptLevel::More,
1146 };
1147
1148 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1149
1150 let any_for_speed = defids.items().any(|id| {
1151 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1152 matches!(optimize, OptimizeAttr::Speed)
1153 });
1154
1155 if any_for_speed {
1156 return for_speed;
1157 }
1158
1159 tcx.sess.opts.optimize
1160 };
1161}
1162
1163pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1164 if !tcx.dep_graph.is_fully_enabled() {
1165 return CguReuse::No;
1166 }
1167
1168 let work_product_id = &cgu.work_product_id();
1169 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1170 return CguReuse::No;
1173 }
1174
1175 let dep_node = cgu.codegen_dep_node(tcx);
1182 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(&dep_node, || {
1183 format!(
1184 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1185 cgu.name()
1186 )
1187 });
1188
1189 if tcx.try_mark_green(&dep_node) {
1190 match compute_per_cgu_lto_type(
1194 &tcx.sess.lto(),
1195 &tcx.sess.opts,
1196 tcx.crate_types(),
1197 ModuleKind::Regular,
1198 ) {
1199 ComputedLtoType::No => CguReuse::PostLto,
1200 _ => CguReuse::PreLto,
1201 }
1202 } else {
1203 CguReuse::No
1204 }
1205}