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::{
10 ALLOC_ERROR_HANDLER, ALLOCATOR_METHODS, AllocatorKind, AllocatorMethod, 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};
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, sym};
35use rustc_symbol_mangling::mangle_internal_symbol;
36use rustc_target::spec::Arch;
37use rustc_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt};
38use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt};
39use tracing::{debug, info};
40
41use crate::assert_module_sources::CguReuse;
42use crate::back::link::are_upstream_rust_objects_already_included;
43use crate::back::write::{
44 ComputedLtoType, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen,
45 submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm,
46};
47use crate::common::{self, IntPredicate, RealPredicate, TypeKind};
48use crate::meth::load_vtable;
49use crate::mir::operand::OperandValue;
50use crate::mir::place::PlaceRef;
51use crate::traits::*;
52use crate::{
53 CachedModuleCodegen, CodegenLintLevels, CrateInfo, ModuleCodegen, ModuleKind, errors, meth, mir,
54};
55
56pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
57 match (op, signed) {
58 (BinOp::Eq, _) => IntPredicate::IntEQ,
59 (BinOp::Ne, _) => IntPredicate::IntNE,
60 (BinOp::Lt, true) => IntPredicate::IntSLT,
61 (BinOp::Lt, false) => IntPredicate::IntULT,
62 (BinOp::Le, true) => IntPredicate::IntSLE,
63 (BinOp::Le, false) => IntPredicate::IntULE,
64 (BinOp::Gt, true) => IntPredicate::IntSGT,
65 (BinOp::Gt, false) => IntPredicate::IntUGT,
66 (BinOp::Ge, true) => IntPredicate::IntSGE,
67 (BinOp::Ge, false) => IntPredicate::IntUGE,
68 op => bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),
69 }
70}
71
72pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
73 match op {
74 BinOp::Eq => RealPredicate::RealOEQ,
75 BinOp::Ne => RealPredicate::RealUNE,
76 BinOp::Lt => RealPredicate::RealOLT,
77 BinOp::Le => RealPredicate::RealOLE,
78 BinOp::Gt => RealPredicate::RealOGT,
79 BinOp::Ge => RealPredicate::RealOGE,
80 op => bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),
81 }
82}
83
84pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
85 bx: &mut Bx,
86 lhs: Bx::Value,
87 rhs: Bx::Value,
88 t: Ty<'tcx>,
89 ret_ty: Bx::Type,
90 op: BinOp,
91) -> Bx::Value {
92 let signed = match t.kind() {
93 ty::Float(_) => {
94 let cmp = bin_op_to_fcmp_predicate(op);
95 let cmp = bx.fcmp(cmp, lhs, rhs);
96 return bx.sext(cmp, ret_ty);
97 }
98 ty::Uint(_) => false,
99 ty::Int(_) => true,
100 _ => bug!("compare_simd_types: invalid SIMD type"),
101 };
102
103 let cmp = bin_op_to_icmp_predicate(op, signed);
104 let cmp = bx.icmp(cmp, lhs, rhs);
105 bx.sext(cmp, ret_ty)
110}
111
112pub fn validate_trivial_unsize<'tcx>(
121 tcx: TyCtxt<'tcx>,
122 source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
123 target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
124) -> bool {
125 match (source_data.principal(), target_data.principal()) {
126 (Some(hr_source_principal), Some(hr_target_principal)) => {
127 let (infcx, param_env) =
128 tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
129 let universe = infcx.universe();
130 let ocx = ObligationCtxt::new(&infcx);
131 infcx.enter_forall(hr_target_principal, |target_principal| {
132 let source_principal = infcx.instantiate_binder_with_fresh_vars(
133 DUMMY_SP,
134 BoundRegionConversionTime::HigherRankedType,
135 hr_source_principal,
136 );
137 let Ok(()) = ocx.eq(
138 &ObligationCause::dummy(),
139 param_env,
140 target_principal,
141 source_principal,
142 ) else {
143 return false;
144 };
145 if !ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
146 return false;
147 }
148 infcx.leak_check(universe, None).is_ok()
149 })
150 }
151 (_, None) => true,
152 _ => false,
153 }
154}
155
156fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
162 bx: &mut Bx,
163 source: Ty<'tcx>,
164 target: Ty<'tcx>,
165 old_info: Option<Bx::Value>,
166) -> Bx::Value {
167 let cx = bx.cx();
168 let (source, target) =
169 cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
170 match (source.kind(), target.kind()) {
171 (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
172 len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
173 ),
174 (&ty::Dynamic(data_a, _), &ty::Dynamic(data_b, _)) => {
175 let old_info =
176 old_info.expect("unsized_info: missing old info for trait upcasting coercion");
177 let b_principal_def_id = data_b.principal_def_id();
178 if data_a.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {
179 debug_assert!(
188 validate_trivial_unsize(cx.tcx(), data_a, data_b),
189 "NOP unsize vtable changed principal trait ref: {data_a} -> {data_b}"
190 );
191
192 return old_info;
198 }
199
200 let vptr_entry_idx = cx.tcx().supertrait_vtable_slot((source, target));
203
204 if let Some(entry_idx) = vptr_entry_idx {
205 let ptr_size = bx.data_layout().pointer_size();
206 let vtable_byte_offset = u64::try_from(entry_idx).unwrap() * ptr_size.bytes();
207 load_vtable(bx, old_info, bx.type_ptr(), vtable_byte_offset, source, true)
208 } else {
209 old_info
210 }
211 }
212 (_, ty::Dynamic(data, _)) => meth::get_vtable(
213 cx,
214 source,
215 data.principal()
216 .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),
217 ),
218 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
219 }
220}
221
222pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
224 bx: &mut Bx,
225 src: Bx::Value,
226 src_ty: Ty<'tcx>,
227 dst_ty: Ty<'tcx>,
228 old_info: Option<Bx::Value>,
229) -> (Bx::Value, Bx::Value) {
230 debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
231 match (src_ty.kind(), dst_ty.kind()) {
232 (&ty::Pat(a, _), &ty::Pat(b, _)) => unsize_ptr(bx, src, a, b, old_info),
233 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
234 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
235 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 coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
271 bx: &mut Bx,
272 src: PlaceRef<'tcx, Bx::Value>,
273 dst: PlaceRef<'tcx, Bx::Value>,
274) {
275 let src_ty = src.layout.ty;
276 let dst_ty = dst.layout.ty;
277 match (src_ty.kind(), dst_ty.kind()) {
278 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
279 let (base, info) = match bx.load_operand(src).val {
280 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
281 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
282 OperandValue::Ref(..) | OperandValue::ZeroSized => bug!(),
283 };
284 OperandValue::Pair(base, info).store(bx, dst);
285 }
286
287 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
288 assert_eq!(def_a, def_b); for i in def_a.variant(FIRST_VARIANT).fields.indices() {
291 let src_f = src.project_field(bx, i.as_usize());
292 let dst_f = dst.project_field(bx, i.as_usize());
293
294 if dst_f.layout.is_zst() {
295 continue;
297 }
298
299 if src_f.layout.ty == dst_f.layout.ty {
300 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
301 } else {
302 coerce_unsized_into(bx, src_f, dst_f);
303 }
304 }
305 }
306 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
307 }
308}
309
310pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
326 bx: &mut Bx,
327 lhs: Bx::Value,
328 mut rhs: Bx::Value,
329 is_unchecked: bool,
330) -> Bx::Value {
331 let mut rhs_llty = bx.cx().val_ty(rhs);
333 let mut lhs_llty = bx.cx().val_ty(lhs);
334
335 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
336 if !is_unchecked {
337 rhs = bx.and(rhs, mask);
338 }
339
340 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
341 rhs_llty = bx.cx().element_type(rhs_llty)
342 }
343 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
344 lhs_llty = bx.cx().element_type(lhs_llty)
345 }
346 let rhs_sz = bx.cx().int_width(rhs_llty);
347 let lhs_sz = bx.cx().int_width(lhs_llty);
348 if lhs_sz < rhs_sz {
349 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
350 } else if lhs_sz > rhs_sz {
351 assert!(lhs_sz <= 256);
358 bx.zext(rhs, lhs_llty)
359 } else {
360 rhs
361 }
362}
363
364pub fn wants_wasm_eh(sess: &Session) -> bool {
368 sess.target.is_like_wasm
369 && (sess.target.os != "emscripten" || sess.opts.unstable_opts.emscripten_wasm_eh)
370}
371
372pub fn wants_msvc_seh(sess: &Session) -> bool {
378 sess.target.is_like_msvc
379}
380
381pub(crate) fn wants_new_eh_instructions(sess: &Session) -> bool {
385 wants_wasm_eh(sess) || wants_msvc_seh(sess)
386}
387
388pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
389 cx: &'a Bx::CodegenCx,
390 instance: Instance<'tcx>,
391) {
392 info!("codegen_instance({})", instance);
396
397 mir::codegen_mir::<Bx>(cx, instance);
398}
399
400pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: ItemId)
401where
402 Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + AsmCodegenMethods<'tcx>,
403{
404 let item = cx.tcx().hir_item(item_id);
405 if let rustc_hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
406 let operands: Vec<_> = asm
407 .operands
408 .iter()
409 .map(|(op, op_sp)| match *op {
410 rustc_hir::InlineAsmOperand::Const { ref anon_const } => {
411 match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) {
412 Ok(const_value) => {
413 let ty =
414 cx.tcx().typeck_body(anon_const.body).node_type(anon_const.hir_id);
415 let string = common::asm_const_to_str(
416 cx.tcx(),
417 *op_sp,
418 const_value,
419 cx.layout_of(ty),
420 );
421 GlobalAsmOperandRef::Const { string }
422 }
423 Err(ErrorHandled::Reported { .. }) => {
424 GlobalAsmOperandRef::Const { string: String::new() }
429 }
430 Err(ErrorHandled::TooGeneric(_)) => {
431 span_bug!(*op_sp, "asm const cannot be resolved; too generic")
432 }
433 }
434 }
435 rustc_hir::InlineAsmOperand::SymFn { expr } => {
436 let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
437 let instance = match ty.kind() {
438 &ty::FnDef(def_id, args) => Instance::expect_resolve(
439 cx.tcx(),
440 ty::TypingEnv::fully_monomorphized(),
441 def_id,
442 args,
443 expr.span,
444 ),
445 _ => span_bug!(*op_sp, "asm sym is not a function"),
446 };
447
448 GlobalAsmOperandRef::SymFn { instance }
449 }
450 rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
451 GlobalAsmOperandRef::SymStatic { def_id }
452 }
453 rustc_hir::InlineAsmOperand::In { .. }
454 | rustc_hir::InlineAsmOperand::Out { .. }
455 | rustc_hir::InlineAsmOperand::InOut { .. }
456 | rustc_hir::InlineAsmOperand::SplitInOut { .. }
457 | rustc_hir::InlineAsmOperand::Label { .. } => {
458 span_bug!(*op_sp, "invalid operand type for global_asm!")
459 }
460 })
461 .collect();
462
463 cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans);
464 } else {
465 span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
466 }
467}
468
469pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
472 cx: &'a Bx::CodegenCx,
473 cgu: &CodegenUnit<'tcx>,
474) -> Option<Bx::Function> {
475 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
476 let main_is_local = main_def_id.is_local();
477 let instance = Instance::mono(cx.tcx(), main_def_id);
478
479 if main_is_local {
480 if !cgu.contains_item(&MonoItem::Fn(instance)) {
483 return None;
484 }
485 } else if !cgu.is_primary() {
486 return None;
488 }
489
490 let main_llfn = cx.get_fn_addr(instance);
491
492 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
493 return Some(entry_fn);
494
495 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
496 cx: &'a Bx::CodegenCx,
497 rust_main: Bx::Value,
498 rust_main_def_id: DefId,
499 entry_type: EntryFnType,
500 ) -> Bx::Function {
501 let llfty = if cx.sess().target.os.contains("uefi") {
504 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
505 } else if cx.sess().target.main_needs_argc_argv {
506 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
507 } else {
508 cx.type_func(&[], cx.type_int())
509 };
510
511 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
512 let main_ret_ty = cx
518 .tcx()
519 .normalize_erasing_regions(cx.typing_env(), main_ret_ty.no_bound_vars().unwrap());
520
521 let Some(llfn) = cx.declare_c_main(llfty) else {
522 let span = cx.tcx().def_span(rust_main_def_id);
524 cx.tcx().dcx().emit_fatal(errors::MultipleMainFunctions { span });
525 };
526
527 cx.set_frame_pointer_type(llfn);
529 cx.apply_target_cpu_attr(llfn);
530
531 let llbb = Bx::append_block(cx, llfn, "top");
532 let mut bx = Bx::build(cx, llbb);
533
534 bx.insert_reference_to_gdb_debug_scripts_section_global();
535
536 let isize_ty = cx.type_isize();
537 let ptr_ty = cx.type_ptr();
538 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
539
540 let EntryFnType::Main { sigpipe } = entry_type;
541 let (start_fn, start_ty, args, instance) = {
542 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, DUMMY_SP);
543 let start_instance = ty::Instance::expect_resolve(
544 cx.tcx(),
545 cx.typing_env(),
546 start_def_id,
547 cx.tcx().mk_args(&[main_ret_ty.into()]),
548 DUMMY_SP,
549 );
550 let start_fn = cx.get_fn_addr(start_instance);
551
552 let i8_ty = cx.type_i8();
553 let arg_sigpipe = bx.const_u8(sigpipe);
554
555 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
556 (
557 start_fn,
558 start_ty,
559 vec![rust_main, arg_argc, arg_argv, arg_sigpipe],
560 Some(start_instance),
561 )
562 };
563
564 let result = bx.call(start_ty, None, None, start_fn, &args, None, instance);
565 if cx.sess().target.os.contains("uefi") {
566 bx.ret(result);
567 } else {
568 let cast = bx.intcast(result, cx.type_int(), true);
569 bx.ret(cast);
570 }
571
572 llfn
573 }
574}
575
576fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
579 if bx.cx().sess().target.os.contains("uefi") {
580 let param_handle = bx.get_param(0);
582 let param_system_table = bx.get_param(1);
583 let ptr_size = bx.tcx().data_layout.pointer_size();
584 let ptr_align = bx.tcx().data_layout.pointer_align().abi;
585 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
586 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
587 bx.store(param_handle, arg_argv, ptr_align);
588 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
589 bx.store(param_system_table, arg_argv_el1, ptr_align);
590 (arg_argc, arg_argv)
591 } else if bx.cx().sess().target.main_needs_argc_argv {
592 let param_argc = bx.get_param(0);
594 let param_argv = bx.get_param(1);
595 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
596 let arg_argv = param_argv;
597 (arg_argc, arg_argv)
598 } else {
599 let arg_argc = bx.const_int(bx.cx().type_int(), 0);
601 let arg_argv = bx.const_null(bx.cx().type_ptr());
602 (arg_argc, arg_argv)
603 }
604}
605
606pub fn collect_debugger_visualizers_transitive(
610 tcx: TyCtxt<'_>,
611 visualizer_type: DebuggerVisualizerType,
612) -> BTreeSet<DebuggerVisualizerFile> {
613 tcx.debugger_visualizers(LOCAL_CRATE)
614 .iter()
615 .chain(
616 tcx.crates(())
617 .iter()
618 .filter(|&cnum| {
619 let used_crate_source = tcx.used_crate_source(*cnum);
620 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
621 })
622 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
623 )
624 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
625 .cloned()
626 .collect::<BTreeSet<_>>()
627}
628
629pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
633 let all_crate_types_any_dynamic_crate = tcx.dependency_formats(()).iter().all(|(_, list)| {
643 use rustc_middle::middle::dependency_format::Linkage;
644 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
645 });
646 if all_crate_types_any_dynamic_crate { None } else { tcx.allocator_kind(()) }
647}
648
649pub(crate) fn needs_allocator_shim_for_linking(
653 dependency_formats: &Dependencies,
654 crate_type: CrateType,
655) -> bool {
656 use rustc_middle::middle::dependency_format::Linkage;
657 let any_dynamic_crate =
658 dependency_formats[&crate_type].iter().any(|&linkage| linkage == Linkage::Dynamic);
659 !any_dynamic_crate
660}
661
662pub fn allocator_shim_contents(tcx: TyCtxt<'_>, kind: AllocatorKind) -> Vec<AllocatorMethod> {
663 let mut methods = Vec::new();
664
665 if kind == AllocatorKind::Default {
666 methods.extend(ALLOCATOR_METHODS.into_iter().copied());
667 }
668
669 if tcx.alloc_error_handler_kind(()).unwrap() == AllocatorKind::Default {
672 methods.push(AllocatorMethod {
673 name: ALLOC_ERROR_HANDLER,
674 special: None,
675 inputs: &[],
676 output: AllocatorTy::Never,
677 });
678 }
679
680 methods
681}
682
683pub fn codegen_crate<B: ExtraBackendMethods>(
684 backend: B,
685 tcx: TyCtxt<'_>,
686 target_cpu: String,
687) -> OngoingCodegen<B> {
688 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
689 tcx.dcx().emit_fatal(errors::CpuRequired);
691 }
692
693 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
694
695 let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());
698
699 if tcx.dep_graph.is_fully_enabled() {
705 for cgu in codegen_units {
706 tcx.ensure_ok().codegen_unit(cgu.name());
707 }
708 }
709
710 let allocator_module = if let Some(kind) = allocator_kind_for_codegen(tcx) {
712 let llmod_id =
713 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
714
715 tcx.sess.time("write_allocator_module", || {
716 let module =
717 backend.codegen_allocator(tcx, &llmod_id, &allocator_shim_contents(tcx, kind));
718 Some(ModuleCodegen::new_allocator(llmod_id, module))
719 })
720 } else {
721 None
722 };
723
724 let ongoing_codegen = start_async_codegen(backend.clone(), tcx, target_cpu, allocator_module);
725
726 let codegen_units: Vec<_> = {
738 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
739 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
740
741 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
742 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
743 };
744
745 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
747 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
748 });
749
750 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
751 for (i, cgu) in codegen_units.iter().enumerate() {
752 let cgu_reuse = cgu_reuse[i];
753 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
754 }
755 });
756
757 let mut total_codegen_time = Duration::new(0, 0);
758 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
759
760 let mut pre_compiled_cgus = if tcx.sess.threads() > 1 {
771 tcx.sess.time("compile_first_CGU_batch", || {
772 let cgus: Vec<_> = cgu_reuse
774 .iter()
775 .enumerate()
776 .filter(|&(_, reuse)| reuse == &CguReuse::No)
777 .take(tcx.sess.threads())
778 .collect();
779
780 let start_time = Instant::now();
782
783 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
784 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
785 (i, IntoDynSyncSend(module))
786 });
787
788 total_codegen_time += start_time.elapsed();
789
790 pre_compiled_cgus
791 })
792 } else {
793 FxHashMap::default()
794 };
795
796 for (i, cgu) in codegen_units.iter().enumerate() {
797 ongoing_codegen.wait_for_signal_to_codegen_item();
798 ongoing_codegen.check_for_errors(tcx.sess);
799
800 let cgu_reuse = cgu_reuse[i];
801
802 match cgu_reuse {
803 CguReuse::No => {
804 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
805 cgu.0
806 } else {
807 let start_time = Instant::now();
808 let module = backend.compile_codegen_unit(tcx, cgu.name());
809 total_codegen_time += start_time.elapsed();
810 module
811 };
812 tcx.dcx().abort_if_errors();
816
817 submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);
818 }
819 CguReuse::PreLto => {
820 submit_pre_lto_module_to_llvm(
821 tcx,
822 &ongoing_codegen.coordinator,
823 CachedModuleCodegen {
824 name: cgu.name().to_string(),
825 source: cgu.previous_work_product(tcx),
826 },
827 );
828 }
829 CguReuse::PostLto => {
830 submit_post_lto_module_to_llvm(
831 &ongoing_codegen.coordinator,
832 CachedModuleCodegen {
833 name: cgu.name().to_string(),
834 source: cgu.previous_work_product(tcx),
835 },
836 );
837 }
838 }
839 }
840
841 ongoing_codegen.codegen_finished(tcx);
842
843 if tcx.sess.opts.unstable_opts.time_passes {
846 let end_rss = get_resident_set_size();
847
848 print_time_passes_entry(
849 "codegen_to_LLVM_IR",
850 total_codegen_time,
851 start_rss.unwrap(),
852 end_rss,
853 tcx.sess.opts.unstable_opts.time_passes_format,
854 );
855 }
856
857 ongoing_codegen.check_for_errors(tcx.sess);
858 ongoing_codegen
859}
860
861pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
871 tcx: TyCtxt<'tcx>,
872 instance: Instance<'tcx>,
873) -> bool {
874 fn is_llvm_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
875 if let Some(name) = tcx.codegen_fn_attrs(def_id).symbol_name {
876 name.as_str().starts_with("llvm.")
877 } else {
878 false
879 }
880 }
881
882 let def_id = instance.def_id();
883 !def_id.is_local()
884 && tcx.is_compiler_builtins(LOCAL_CRATE)
885 && !is_llvm_intrinsic(tcx, def_id)
886 && !tcx.should_codegen_locally(instance)
887}
888
889impl CrateInfo {
890 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
891 let crate_types = tcx.crate_types().to_vec();
892 let exported_symbols = crate_types
893 .iter()
894 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
895 .collect();
896 let linked_symbols =
897 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
898 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
899 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
900 let subsystem =
901 ast::attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
902 let windows_subsystem = subsystem.map(|subsystem| {
903 if subsystem != sym::windows && subsystem != sym::console {
904 tcx.dcx().emit_fatal(errors::InvalidWindowsSubsystem { subsystem });
905 }
906 subsystem.to_string()
907 });
908
909 let mut compiler_builtins = None;
918 let mut used_crates: Vec<_> = tcx
919 .postorder_cnums(())
920 .iter()
921 .rev()
922 .copied()
923 .filter(|&cnum| {
924 let link = !tcx.dep_kind(cnum).macros_only();
925 if link && tcx.is_compiler_builtins(cnum) {
926 compiler_builtins = Some(cnum);
927 return false;
928 }
929 link
930 })
931 .collect();
932 used_crates.extend(compiler_builtins);
934
935 let crates = tcx.crates(());
936 let n_crates = crates.len();
937 let mut info = CrateInfo {
938 target_cpu,
939 target_features: tcx.global_backend_features(()).clone(),
940 crate_types,
941 exported_symbols,
942 linked_symbols,
943 local_crate_name,
944 compiler_builtins,
945 profiler_runtime: None,
946 is_no_builtins: Default::default(),
947 native_libraries: Default::default(),
948 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
949 crate_name: UnordMap::with_capacity(n_crates),
950 used_crates,
951 used_crate_source: UnordMap::with_capacity(n_crates),
952 dependency_formats: Arc::clone(tcx.dependency_formats(())),
953 windows_subsystem,
954 natvis_debugger_visualizers: Default::default(),
955 lint_levels: CodegenLintLevels::from_tcx(tcx),
956 metadata_symbol: exported_symbols::metadata_symbol_name(tcx),
957 };
958
959 info.native_libraries.reserve(n_crates);
960
961 for &cnum in crates.iter() {
962 info.native_libraries
963 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
964 info.crate_name.insert(cnum, tcx.crate_name(cnum));
965
966 let used_crate_source = tcx.used_crate_source(cnum);
967 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
968 if tcx.is_profiler_runtime(cnum) {
969 info.profiler_runtime = Some(cnum);
970 }
971 if tcx.is_no_builtins(cnum) {
972 info.is_no_builtins.insert(cnum);
973 }
974 }
975
976 let target = &tcx.sess.target;
985 if !are_upstream_rust_objects_already_included(tcx.sess) {
986 let add_prefix = match (target.is_like_windows, &target.arch) {
987 (true, Arch::X86) => |name: String, _: SymbolExportKind| format!("_{name}"),
988 (true, Arch::Arm64EC) => {
989 |name: String, export_kind: SymbolExportKind| match export_kind {
991 SymbolExportKind::Text => format!("#{name}"),
992 _ => name,
993 }
994 }
995 _ => |name: String, _: SymbolExportKind| name,
996 };
997 let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info
998 .used_crates
999 .iter()
1000 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
1001 .filter(|l| l.is_weak())
1002 .filter_map(|&l| {
1003 let name = l.link_name()?;
1004 let export_kind = match l.target() {
1005 Target::Fn => SymbolExportKind::Text,
1006 Target::Static => SymbolExportKind::Data,
1007 _ => bug!(
1008 "Don't know what the export kind is for lang item of kind {:?}",
1009 l.target()
1010 ),
1011 };
1012 lang_items::required(tcx, l).then_some((name, export_kind))
1013 })
1014 .collect();
1015
1016 #[allow(rustc::potential_query_instability)]
1019 info.linked_symbols
1020 .iter_mut()
1021 .filter(|(crate_type, _)| {
1022 !matches!(crate_type, CrateType::Rlib | CrateType::Staticlib)
1023 })
1024 .for_each(|(_, linked_symbols)| {
1025 let mut symbols = missing_weak_lang_items
1026 .iter()
1027 .map(|(item, export_kind)| {
1028 (
1029 add_prefix(
1030 mangle_internal_symbol(tcx, item.as_str()),
1031 *export_kind,
1032 ),
1033 *export_kind,
1034 )
1035 })
1036 .collect::<Vec<_>>();
1037 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1038 linked_symbols.extend(symbols);
1039 });
1040 }
1041
1042 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1043 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1044 true
1047 }
1048 CrateType::ProcMacro => {
1049 false
1053 }
1054 CrateType::Staticlib | CrateType::Rlib => {
1055 false
1058 }
1059 });
1060
1061 if target.is_like_msvc && embed_visualizers {
1062 info.natvis_debugger_visualizers =
1063 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1064 }
1065
1066 info
1067 }
1068}
1069
1070pub(crate) fn provide(providers: &mut Providers) {
1071 providers.backend_optimization_level = |tcx, cratenum| {
1072 let for_speed = match tcx.sess.opts.optimize {
1073 config::OptLevel::No => return config::OptLevel::No,
1080 config::OptLevel::Less => return config::OptLevel::Less,
1082 config::OptLevel::More => return config::OptLevel::More,
1083 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1084 config::OptLevel::Size => config::OptLevel::More,
1087 config::OptLevel::SizeMin => config::OptLevel::More,
1088 };
1089
1090 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1091
1092 let any_for_speed = defids.items().any(|id| {
1093 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1094 matches!(optimize, OptimizeAttr::Speed)
1095 });
1096
1097 if any_for_speed {
1098 return for_speed;
1099 }
1100
1101 tcx.sess.opts.optimize
1102 };
1103}
1104
1105pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1106 if !tcx.dep_graph.is_fully_enabled() {
1107 return CguReuse::No;
1108 }
1109
1110 let work_product_id = &cgu.work_product_id();
1111 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1112 return CguReuse::No;
1115 }
1116
1117 let dep_node = cgu.codegen_dep_node(tcx);
1124 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(&dep_node, || {
1125 format!(
1126 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1127 cgu.name()
1128 )
1129 });
1130
1131 if tcx.try_mark_green(&dep_node) {
1132 match compute_per_cgu_lto_type(
1136 &tcx.sess.lto(),
1137 &tcx.sess.opts,
1138 tcx.crate_types(),
1139 ModuleKind::Regular,
1140 ) {
1141 ComputedLtoType::No => CguReuse::PostLto,
1142 _ => CguReuse::PreLto,
1143 }
1144 } else {
1145 CguReuse::No
1146 }
1147}