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_parsing::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::par_map;
14use rustc_data_structures::unord::UnordMap;
15use rustc_hir::def_id::{DefId, LOCAL_CRATE};
16use rustc_hir::lang_items::LangItem;
17use rustc_metadata::EncodedMetadata;
18use rustc_middle::bug;
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::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem, MonoItemPartitions};
25use rustc_middle::query::Providers;
26use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
27use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
28use rustc_session::Session;
29use rustc_session::config::{self, CrateType, EntryFnType, OutputType};
30use rustc_span::{DUMMY_SP, Symbol, sym};
31use rustc_symbol_mangling::mangle_internal_symbol;
32use rustc_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt};
33use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt};
34use tracing::{debug, info};
35
36use crate::assert_module_sources::CguReuse;
37use crate::back::link::are_upstream_rust_objects_already_included;
38use crate::back::metadata::create_compressed_metadata_file;
39use crate::back::write::{
40 ComputedLtoType, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen,
41 submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm,
42};
43use crate::common::{self, IntPredicate, RealPredicate, TypeKind};
44use crate::meth::load_vtable;
45use crate::mir::operand::OperandValue;
46use crate::mir::place::PlaceRef;
47use crate::traits::*;
48use crate::{
49 CachedModuleCodegen, CodegenLintLevels, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
50 errors, meth, mir,
51};
52
53pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate {
54 match (op, signed) {
55 (BinOp::Eq, _) => IntPredicate::IntEQ,
56 (BinOp::Ne, _) => IntPredicate::IntNE,
57 (BinOp::Lt, true) => IntPredicate::IntSLT,
58 (BinOp::Lt, false) => IntPredicate::IntULT,
59 (BinOp::Le, true) => IntPredicate::IntSLE,
60 (BinOp::Le, false) => IntPredicate::IntULE,
61 (BinOp::Gt, true) => IntPredicate::IntSGT,
62 (BinOp::Gt, false) => IntPredicate::IntUGT,
63 (BinOp::Ge, true) => IntPredicate::IntSGE,
64 (BinOp::Ge, false) => IntPredicate::IntUGE,
65 op => bug!("bin_op_to_icmp_predicate: expected comparison operator, found {:?}", op),
66 }
67}
68
69pub(crate) fn bin_op_to_fcmp_predicate(op: BinOp) -> RealPredicate {
70 match op {
71 BinOp::Eq => RealPredicate::RealOEQ,
72 BinOp::Ne => RealPredicate::RealUNE,
73 BinOp::Lt => RealPredicate::RealOLT,
74 BinOp::Le => RealPredicate::RealOLE,
75 BinOp::Gt => RealPredicate::RealOGT,
76 BinOp::Ge => RealPredicate::RealOGE,
77 op => bug!("bin_op_to_fcmp_predicate: expected comparison operator, found {:?}", op),
78 }
79}
80
81pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
82 bx: &mut Bx,
83 lhs: Bx::Value,
84 rhs: Bx::Value,
85 t: Ty<'tcx>,
86 ret_ty: Bx::Type,
87 op: BinOp,
88) -> Bx::Value {
89 let signed = match t.kind() {
90 ty::Float(_) => {
91 let cmp = bin_op_to_fcmp_predicate(op);
92 let cmp = bx.fcmp(cmp, lhs, rhs);
93 return bx.sext(cmp, ret_ty);
94 }
95 ty::Uint(_) => false,
96 ty::Int(_) => true,
97 _ => bug!("compare_simd_types: invalid SIMD type"),
98 };
99
100 let cmp = bin_op_to_icmp_predicate(op, signed);
101 let cmp = bx.icmp(cmp, lhs, rhs);
102 bx.sext(cmp, ret_ty)
107}
108
109pub fn validate_trivial_unsize<'tcx>(
118 tcx: TyCtxt<'tcx>,
119 source_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
120 target_data: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
121) -> bool {
122 match (source_data.principal(), target_data.principal()) {
123 (Some(hr_source_principal), Some(hr_target_principal)) => {
124 let (infcx, param_env) =
125 tcx.infer_ctxt().build_with_typing_env(ty::TypingEnv::fully_monomorphized());
126 let universe = infcx.universe();
127 let ocx = ObligationCtxt::new(&infcx);
128 infcx.enter_forall(hr_target_principal, |target_principal| {
129 let source_principal = infcx.instantiate_binder_with_fresh_vars(
130 DUMMY_SP,
131 BoundRegionConversionTime::HigherRankedType,
132 hr_source_principal,
133 );
134 let Ok(()) = ocx.eq(
135 &ObligationCause::dummy(),
136 param_env,
137 target_principal,
138 source_principal,
139 ) else {
140 return false;
141 };
142 if !ocx.select_all_or_error().is_empty() {
143 return false;
144 }
145 infcx.leak_check(universe, None).is_ok()
146 })
147 }
148 (_, None) => true,
149 _ => false,
150 }
151}
152
153fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
159 bx: &mut Bx,
160 source: Ty<'tcx>,
161 target: Ty<'tcx>,
162 old_info: Option<Bx::Value>,
163) -> Bx::Value {
164 let cx = bx.cx();
165 let (source, target) =
166 cx.tcx().struct_lockstep_tails_for_codegen(source, target, bx.typing_env());
167 match (source.kind(), target.kind()) {
168 (&ty::Array(_, len), &ty::Slice(_)) => cx.const_usize(
169 len.try_to_target_usize(cx.tcx()).expect("expected monomorphic const in codegen"),
170 ),
171 (&ty::Dynamic(data_a, _, src_dyn_kind), &ty::Dynamic(data_b, _, target_dyn_kind))
172 if src_dyn_kind == target_dyn_kind =>
173 {
174 let old_info =
175 old_info.expect("unsized_info: missing old info for trait upcasting coercion");
176 let b_principal_def_id = data_b.principal_def_id();
177 if data_a.principal_def_id() == b_principal_def_id || b_principal_def_id.is_none() {
178 debug_assert!(
187 validate_trivial_unsize(cx.tcx(), data_a, data_b),
188 "NOP unsize vtable changed principal trait ref: {data_a} -> {data_b}"
189 );
190
191 return old_info;
197 }
198
199 let vptr_entry_idx = cx.tcx().supertrait_vtable_slot((source, target));
202
203 if let Some(entry_idx) = vptr_entry_idx {
204 let ptr_size = bx.data_layout().pointer_size;
205 let vtable_byte_offset = u64::try_from(entry_idx).unwrap() * ptr_size.bytes();
206 load_vtable(bx, old_info, bx.type_ptr(), vtable_byte_offset, source, true)
207 } else {
208 old_info
209 }
210 }
211 (_, ty::Dynamic(data, _, _)) => meth::get_vtable(
212 cx,
213 source,
214 data.principal()
215 .map(|principal| bx.tcx().instantiate_bound_regions_with_erased(principal)),
216 ),
217 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
218 }
219}
220
221pub(crate) fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
223 bx: &mut Bx,
224 src: Bx::Value,
225 src_ty: Ty<'tcx>,
226 dst_ty: Ty<'tcx>,
227 old_info: Option<Bx::Value>,
228) -> (Bx::Value, Bx::Value) {
229 debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
230 match (src_ty.kind(), dst_ty.kind()) {
231 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
232 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
233 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 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 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
252 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
253 assert_eq!(src_layout.size, src_f.size);
254
255 let dst_f = dst_layout.field(bx.cx(), i);
256 assert_ne!(src_f.ty, dst_f.ty);
257 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 _ => bug!("unsize_ptr: called on bad types"),
263 }
264}
265
266pub(crate) fn cast_to_dyn_star<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
268 bx: &mut Bx,
269 src: Bx::Value,
270 src_ty_and_layout: TyAndLayout<'tcx>,
271 dst_ty: Ty<'tcx>,
272 old_info: Option<Bx::Value>,
273) -> (Bx::Value, Bx::Value) {
274 debug!("cast_to_dyn_star: {:?} => {:?}", src_ty_and_layout.ty, dst_ty);
275 assert!(
276 matches!(dst_ty.kind(), ty::Dynamic(_, _, ty::DynStar)),
277 "destination type must be a dyn*"
278 );
279 let src = match bx.cx().type_kind(bx.cx().backend_type(src_ty_and_layout)) {
280 TypeKind::Pointer => src,
281 TypeKind::Integer => bx.inttoptr(src, bx.type_ptr()),
282 kind => bug!("unexpected TypeKind for left-hand side of `dyn*` cast: {kind:?}"),
284 };
285 (src, unsized_info(bx, src_ty_and_layout.ty, dst_ty, old_info))
286}
287
288pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
291 bx: &mut Bx,
292 src: PlaceRef<'tcx, Bx::Value>,
293 dst: PlaceRef<'tcx, Bx::Value>,
294) {
295 let src_ty = src.layout.ty;
296 let dst_ty = dst.layout.ty;
297 match (src_ty.kind(), dst_ty.kind()) {
298 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
299 let (base, info) = match bx.load_operand(src).val {
300 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
301 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
302 OperandValue::Ref(..) | OperandValue::ZeroSized => bug!(),
303 };
304 OperandValue::Pair(base, info).store(bx, dst);
305 }
306
307 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
308 assert_eq!(def_a, def_b); for i in def_a.variant(FIRST_VARIANT).fields.indices() {
311 let src_f = src.project_field(bx, i.as_usize());
312 let dst_f = dst.project_field(bx, i.as_usize());
313
314 if dst_f.layout.is_zst() {
315 continue;
317 }
318
319 if src_f.layout.ty == dst_f.layout.ty {
320 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
321 } else {
322 coerce_unsized_into(bx, src_f, dst_f);
323 }
324 }
325 }
326 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
327 }
328}
329
330pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
346 bx: &mut Bx,
347 lhs: Bx::Value,
348 mut rhs: Bx::Value,
349 is_unchecked: bool,
350) -> Bx::Value {
351 let mut rhs_llty = bx.cx().val_ty(rhs);
353 let mut lhs_llty = bx.cx().val_ty(lhs);
354
355 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
356 if !is_unchecked {
357 rhs = bx.and(rhs, mask);
358 }
359
360 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
361 rhs_llty = bx.cx().element_type(rhs_llty)
362 }
363 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
364 lhs_llty = bx.cx().element_type(lhs_llty)
365 }
366 let rhs_sz = bx.cx().int_width(rhs_llty);
367 let lhs_sz = bx.cx().int_width(lhs_llty);
368 if lhs_sz < rhs_sz {
369 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
370 } else if lhs_sz > rhs_sz {
371 assert!(lhs_sz <= 256);
378 bx.zext(rhs, lhs_llty)
379 } else {
380 rhs
381 }
382}
383
384pub fn wants_wasm_eh(sess: &Session) -> bool {
388 sess.target.is_like_wasm
389 && (sess.target.os != "emscripten" || sess.opts.unstable_opts.emscripten_wasm_eh)
390}
391
392pub fn wants_msvc_seh(sess: &Session) -> bool {
398 sess.target.is_like_msvc
399}
400
401pub(crate) fn wants_new_eh_instructions(sess: &Session) -> bool {
405 wants_wasm_eh(sess) || wants_msvc_seh(sess)
406}
407
408pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
409 cx: &'a Bx::CodegenCx,
410 instance: Instance<'tcx>,
411) {
412 info!("codegen_instance({})", instance);
416
417 mir::codegen_mir::<Bx>(cx, instance);
418}
419
420pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
423 cx: &'a Bx::CodegenCx,
424) -> Option<Bx::Function> {
425 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
426 let main_is_local = main_def_id.is_local();
427 let instance = Instance::mono(cx.tcx(), main_def_id);
428
429 if main_is_local {
430 if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
433 return None;
434 }
435 } else if !cx.codegen_unit().is_primary() {
436 return None;
438 }
439
440 let main_llfn = cx.get_fn_addr(instance);
441
442 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
443 return Some(entry_fn);
444
445 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
446 cx: &'a Bx::CodegenCx,
447 rust_main: Bx::Value,
448 rust_main_def_id: DefId,
449 entry_type: EntryFnType,
450 ) -> Bx::Function {
451 let llfty = if cx.sess().target.os.contains("uefi") {
454 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
455 } else if cx.sess().target.main_needs_argc_argv {
456 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
457 } else {
458 cx.type_func(&[], cx.type_int())
459 };
460
461 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
462 let main_ret_ty = cx
468 .tcx()
469 .normalize_erasing_regions(cx.typing_env(), main_ret_ty.no_bound_vars().unwrap());
470
471 let Some(llfn) = cx.declare_c_main(llfty) else {
472 let span = cx.tcx().def_span(rust_main_def_id);
474 cx.tcx().dcx().emit_fatal(errors::MultipleMainFunctions { span });
475 };
476
477 cx.set_frame_pointer_type(llfn);
479 cx.apply_target_cpu_attr(llfn);
480
481 let llbb = Bx::append_block(cx, llfn, "top");
482 let mut bx = Bx::build(cx, llbb);
483
484 bx.insert_reference_to_gdb_debug_scripts_section_global();
485
486 let isize_ty = cx.type_isize();
487 let ptr_ty = cx.type_ptr();
488 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
489
490 let EntryFnType::Main { sigpipe } = entry_type;
491 let (start_fn, start_ty, args, instance) = {
492 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, None);
493 let start_instance = ty::Instance::expect_resolve(
494 cx.tcx(),
495 cx.typing_env(),
496 start_def_id,
497 cx.tcx().mk_args(&[main_ret_ty.into()]),
498 DUMMY_SP,
499 );
500 let start_fn = cx.get_fn_addr(start_instance);
501
502 let i8_ty = cx.type_i8();
503 let arg_sigpipe = bx.const_u8(sigpipe);
504
505 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
506 (
507 start_fn,
508 start_ty,
509 vec![rust_main, arg_argc, arg_argv, arg_sigpipe],
510 Some(start_instance),
511 )
512 };
513
514 let result = bx.call(start_ty, None, None, start_fn, &args, None, instance);
515 if cx.sess().target.os.contains("uefi") {
516 bx.ret(result);
517 } else {
518 let cast = bx.intcast(result, cx.type_int(), true);
519 bx.ret(cast);
520 }
521
522 llfn
523 }
524}
525
526fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
529 if bx.cx().sess().target.os.contains("uefi") {
530 let param_handle = bx.get_param(0);
532 let param_system_table = bx.get_param(1);
533 let ptr_size = bx.tcx().data_layout.pointer_size;
534 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
535 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
536 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
537 bx.store(param_handle, arg_argv, ptr_align);
538 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
539 bx.store(param_system_table, arg_argv_el1, ptr_align);
540 (arg_argc, arg_argv)
541 } else if bx.cx().sess().target.main_needs_argc_argv {
542 let param_argc = bx.get_param(0);
544 let param_argv = bx.get_param(1);
545 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
546 let arg_argv = param_argv;
547 (arg_argc, arg_argv)
548 } else {
549 let arg_argc = bx.const_int(bx.cx().type_int(), 0);
551 let arg_argv = bx.const_null(bx.cx().type_ptr());
552 (arg_argc, arg_argv)
553 }
554}
555
556pub fn collect_debugger_visualizers_transitive(
560 tcx: TyCtxt<'_>,
561 visualizer_type: DebuggerVisualizerType,
562) -> BTreeSet<DebuggerVisualizerFile> {
563 tcx.debugger_visualizers(LOCAL_CRATE)
564 .iter()
565 .chain(
566 tcx.crates(())
567 .iter()
568 .filter(|&cnum| {
569 let used_crate_source = tcx.used_crate_source(*cnum);
570 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
571 })
572 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
573 )
574 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
575 .cloned()
576 .collect::<BTreeSet<_>>()
577}
578
579pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
583 let any_dynamic_crate = tcx.dependency_formats(()).iter().any(|(_, list)| {
590 use rustc_middle::middle::dependency_format::Linkage;
591 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
592 });
593 if any_dynamic_crate { None } else { tcx.allocator_kind(()) }
594}
595
596pub fn codegen_crate<B: ExtraBackendMethods>(
597 backend: B,
598 tcx: TyCtxt<'_>,
599 target_cpu: String,
600 metadata: EncodedMetadata,
601 need_metadata_module: bool,
602) -> OngoingCodegen<B> {
603 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
605 let ongoing_codegen = start_async_codegen(backend, tcx, target_cpu, metadata, None);
606
607 ongoing_codegen.codegen_finished(tcx);
608
609 ongoing_codegen.check_for_errors(tcx.sess);
610
611 return ongoing_codegen;
612 }
613
614 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
615 tcx.dcx().emit_fatal(errors::CpuRequired);
617 }
618
619 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
620
621 let MonoItemPartitions { codegen_units, autodiff_items, .. } =
624 tcx.collect_and_partition_mono_items(());
625 let autodiff_fncs = autodiff_items.to_vec();
626
627 if tcx.dep_graph.is_fully_enabled() {
633 for cgu in codegen_units {
634 tcx.ensure_ok().codegen_unit(cgu.name());
635 }
636 }
637
638 let metadata_module = need_metadata_module.then(|| {
639 let metadata_cgu_name =
641 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
642 tcx.sess.time("write_compressed_metadata", || {
643 let file_name =
644 tcx.output_filenames(()).temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
645 let data = create_compressed_metadata_file(
646 tcx.sess,
647 &metadata,
648 &exported_symbols::metadata_symbol_name(tcx),
649 );
650 if let Err(error) = std::fs::write(&file_name, data) {
651 tcx.dcx().emit_fatal(errors::MetadataObjectFileWrite { error });
652 }
653 CompiledModule {
654 name: metadata_cgu_name,
655 kind: ModuleKind::Metadata,
656 object: Some(file_name),
657 dwarf_object: None,
658 bytecode: None,
659 assembly: None,
660 llvm_ir: None,
661 links_from_incr_cache: Vec::new(),
662 }
663 })
664 });
665
666 let ongoing_codegen =
667 start_async_codegen(backend.clone(), tcx, target_cpu, metadata, metadata_module);
668
669 if let Some(kind) = allocator_kind_for_codegen(tcx) {
671 let llmod_id =
672 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
673 let module_llvm = tcx.sess.time("write_allocator_module", || {
674 backend.codegen_allocator(
675 tcx,
676 &llmod_id,
677 kind,
678 tcx.alloc_error_handler_kind(()).unwrap(),
681 )
682 });
683
684 ongoing_codegen.wait_for_signal_to_codegen_item();
685 ongoing_codegen.check_for_errors(tcx.sess);
686
687 let cost = 0;
689 submit_codegened_module_to_llvm(
690 &backend,
691 &ongoing_codegen.coordinator.sender,
692 ModuleCodegen::new_allocator(llmod_id, module_llvm),
693 cost,
694 );
695 }
696
697 if !autodiff_fncs.is_empty() {
698 ongoing_codegen.submit_autodiff_items(autodiff_fncs);
699 }
700
701 let codegen_units: Vec<_> = {
713 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
714 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
715
716 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
717 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
718 };
719
720 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
722 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
723 });
724
725 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
726 for (i, cgu) in codegen_units.iter().enumerate() {
727 let cgu_reuse = cgu_reuse[i];
728 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
729 }
730 });
731
732 let mut total_codegen_time = Duration::new(0, 0);
733 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
734
735 let mut pre_compiled_cgus = if tcx.sess.threads() > 1 {
746 tcx.sess.time("compile_first_CGU_batch", || {
747 let cgus: Vec<_> = cgu_reuse
749 .iter()
750 .enumerate()
751 .filter(|&(_, reuse)| reuse == &CguReuse::No)
752 .take(tcx.sess.threads())
753 .collect();
754
755 let start_time = Instant::now();
757
758 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
759 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
760 (i, module)
761 });
762
763 total_codegen_time += start_time.elapsed();
764
765 pre_compiled_cgus
766 })
767 } else {
768 FxHashMap::default()
769 };
770
771 for (i, cgu) in codegen_units.iter().enumerate() {
772 ongoing_codegen.wait_for_signal_to_codegen_item();
773 ongoing_codegen.check_for_errors(tcx.sess);
774
775 let cgu_reuse = cgu_reuse[i];
776
777 match cgu_reuse {
778 CguReuse::No => {
779 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
780 cgu
781 } else {
782 let start_time = Instant::now();
783 let module = backend.compile_codegen_unit(tcx, cgu.name());
784 total_codegen_time += start_time.elapsed();
785 module
786 };
787 tcx.dcx().abort_if_errors();
791
792 submit_codegened_module_to_llvm(
793 &backend,
794 &ongoing_codegen.coordinator.sender,
795 module,
796 cost,
797 );
798 }
799 CguReuse::PreLto => {
800 submit_pre_lto_module_to_llvm(
801 &backend,
802 tcx,
803 &ongoing_codegen.coordinator.sender,
804 CachedModuleCodegen {
805 name: cgu.name().to_string(),
806 source: cgu.previous_work_product(tcx),
807 },
808 );
809 }
810 CguReuse::PostLto => {
811 submit_post_lto_module_to_llvm(
812 &backend,
813 &ongoing_codegen.coordinator.sender,
814 CachedModuleCodegen {
815 name: cgu.name().to_string(),
816 source: cgu.previous_work_product(tcx),
817 },
818 );
819 }
820 }
821 }
822
823 ongoing_codegen.codegen_finished(tcx);
824
825 if tcx.sess.opts.unstable_opts.time_passes {
828 let end_rss = get_resident_set_size();
829
830 print_time_passes_entry(
831 "codegen_to_LLVM_IR",
832 total_codegen_time,
833 start_rss.unwrap(),
834 end_rss,
835 tcx.sess.opts.unstable_opts.time_passes_format,
836 );
837 }
838
839 ongoing_codegen.check_for_errors(tcx.sess);
840 ongoing_codegen
841}
842
843pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
853 tcx: TyCtxt<'tcx>,
854 instance: Instance<'tcx>,
855) -> bool {
856 fn is_llvm_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
857 if let Some(name) = tcx.codegen_fn_attrs(def_id).link_name {
858 name.as_str().starts_with("llvm.")
859 } else {
860 false
861 }
862 }
863
864 let def_id = instance.def_id();
865 !def_id.is_local()
866 && tcx.is_compiler_builtins(LOCAL_CRATE)
867 && !is_llvm_intrinsic(tcx, def_id)
868 && !tcx.should_codegen_locally(instance)
869}
870
871impl CrateInfo {
872 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
873 let crate_types = tcx.crate_types().to_vec();
874 let exported_symbols = crate_types
875 .iter()
876 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
877 .collect();
878 let linked_symbols =
879 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
880 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
881 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
882 let subsystem =
883 ast::attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
884 let windows_subsystem = subsystem.map(|subsystem| {
885 if subsystem != sym::windows && subsystem != sym::console {
886 tcx.dcx().emit_fatal(errors::InvalidWindowsSubsystem { subsystem });
887 }
888 subsystem.to_string()
889 });
890
891 let mut compiler_builtins = None;
900 let mut used_crates: Vec<_> = tcx
901 .postorder_cnums(())
902 .iter()
903 .rev()
904 .copied()
905 .filter(|&cnum| {
906 let link = !tcx.dep_kind(cnum).macros_only();
907 if link && tcx.is_compiler_builtins(cnum) {
908 compiler_builtins = Some(cnum);
909 return false;
910 }
911 link
912 })
913 .collect();
914 used_crates.extend(compiler_builtins);
916
917 let crates = tcx.crates(());
918 let n_crates = crates.len();
919 let mut info = CrateInfo {
920 target_cpu,
921 target_features: tcx.global_backend_features(()).clone(),
922 crate_types,
923 exported_symbols,
924 linked_symbols,
925 local_crate_name,
926 compiler_builtins,
927 profiler_runtime: None,
928 is_no_builtins: Default::default(),
929 native_libraries: Default::default(),
930 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
931 crate_name: UnordMap::with_capacity(n_crates),
932 used_crates,
933 used_crate_source: UnordMap::with_capacity(n_crates),
934 dependency_formats: Arc::clone(tcx.dependency_formats(())),
935 windows_subsystem,
936 natvis_debugger_visualizers: Default::default(),
937 lint_levels: CodegenLintLevels::from_tcx(tcx),
938 };
939
940 info.native_libraries.reserve(n_crates);
941
942 for &cnum in crates.iter() {
943 info.native_libraries
944 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
945 info.crate_name.insert(cnum, tcx.crate_name(cnum));
946
947 let used_crate_source = tcx.used_crate_source(cnum);
948 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
949 if tcx.is_profiler_runtime(cnum) {
950 info.profiler_runtime = Some(cnum);
951 }
952 if tcx.is_no_builtins(cnum) {
953 info.is_no_builtins.insert(cnum);
954 }
955 }
956
957 let target = &tcx.sess.target;
966 if !are_upstream_rust_objects_already_included(tcx.sess) {
967 let missing_weak_lang_items: FxIndexSet<Symbol> = info
968 .used_crates
969 .iter()
970 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
971 .filter(|l| l.is_weak())
972 .filter_map(|&l| {
973 let name = l.link_name()?;
974 lang_items::required(tcx, l).then_some(name)
975 })
976 .collect();
977 let prefix = match (target.is_like_windows, target.arch.as_ref()) {
978 (true, "x86") => "_",
979 (true, "arm64ec") => "#",
980 _ => "",
981 };
982
983 #[allow(rustc::potential_query_instability)]
986 info.linked_symbols
987 .iter_mut()
988 .filter(|(crate_type, _)| {
989 !matches!(crate_type, CrateType::Rlib | CrateType::Staticlib)
990 })
991 .for_each(|(_, linked_symbols)| {
992 let mut symbols = missing_weak_lang_items
993 .iter()
994 .map(|item| {
995 (
996 format!("{prefix}{}", mangle_internal_symbol(tcx, item.as_str())),
997 SymbolExportKind::Text,
998 )
999 })
1000 .collect::<Vec<_>>();
1001 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1002 linked_symbols.extend(symbols);
1003 if tcx.allocator_kind(()).is_some() {
1004 linked_symbols.extend(ALLOCATOR_METHODS.iter().map(|method| {
1011 (
1012 format!(
1013 "{prefix}{}",
1014 mangle_internal_symbol(
1015 tcx,
1016 global_fn_name(method.name).as_str()
1017 )
1018 ),
1019 SymbolExportKind::Text,
1020 )
1021 }));
1022 }
1023 });
1024 }
1025
1026 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1027 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib => {
1028 true
1031 }
1032 CrateType::ProcMacro => {
1033 false
1037 }
1038 CrateType::Staticlib | CrateType::Rlib => {
1039 false
1042 }
1043 });
1044
1045 if target.is_like_msvc && embed_visualizers {
1046 info.natvis_debugger_visualizers =
1047 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1048 }
1049
1050 info
1051 }
1052}
1053
1054pub(crate) fn provide(providers: &mut Providers) {
1055 providers.backend_optimization_level = |tcx, cratenum| {
1056 let for_speed = match tcx.sess.opts.optimize {
1057 config::OptLevel::No => return config::OptLevel::No,
1064 config::OptLevel::Less => return config::OptLevel::Less,
1066 config::OptLevel::More => return config::OptLevel::More,
1067 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1068 config::OptLevel::Size => config::OptLevel::More,
1071 config::OptLevel::SizeMin => config::OptLevel::More,
1072 };
1073
1074 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1075
1076 let any_for_speed = defids.items().any(|id| {
1077 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1078 matches!(optimize, OptimizeAttr::Speed)
1079 });
1080
1081 if any_for_speed {
1082 return for_speed;
1083 }
1084
1085 tcx.sess.opts.optimize
1086 };
1087}
1088
1089pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1090 if !tcx.dep_graph.is_fully_enabled() {
1091 return CguReuse::No;
1092 }
1093
1094 let work_product_id = &cgu.work_product_id();
1095 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1096 return CguReuse::No;
1099 }
1100
1101 let dep_node = cgu.codegen_dep_node(tcx);
1108 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(&dep_node, || {
1109 format!(
1110 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1111 cgu.name()
1112 )
1113 });
1114
1115 if tcx.try_mark_green(&dep_node) {
1116 match compute_per_cgu_lto_type(
1120 &tcx.sess.lto(),
1121 &tcx.sess.opts,
1122 tcx.crate_types(),
1123 ModuleKind::Regular,
1124 ) {
1125 ComputedLtoType::No => CguReuse::PostLto,
1126 _ => CguReuse::PreLto,
1127 }
1128 } else {
1129 CguReuse::No
1130 }
1131}