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_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt};
37use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt};
38use tracing::{debug, info};
39
40use crate::assert_module_sources::CguReuse;
41use crate::back::link::are_upstream_rust_objects_already_included;
42use crate::back::write::{
43 ComputedLtoType, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen,
44 submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm,
45};
46use crate::common::{self, IntPredicate, RealPredicate, TypeKind};
47use crate::meth::load_vtable;
48use crate::mir::operand::OperandValue;
49use crate::mir::place::PlaceRef;
50use crate::traits::*;
51use crate::{
52 CachedModuleCodegen, CodegenLintLevels, CrateInfo, ModuleCodegen, ModuleKind, 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.evaluate_obligations_error_on_ambiguity().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, _), &ty::Dynamic(data_b, _)) => {
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::Pat(a, _), &ty::Pat(b, _)) => unsize_ptr(bx, src, a, b, old_info),
232 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(b, _))
233 | (&ty::RawPtr(a, _), &ty::RawPtr(b, _)) => {
234 assert_eq!(bx.cx().type_is_sized(a), old_info.is_none());
235 (src, unsized_info(bx, a, b, old_info))
236 }
237 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
238 assert_eq!(def_a, def_b); let src_layout = bx.cx().layout_of(src_ty);
240 let dst_layout = bx.cx().layout_of(dst_ty);
241 if src_ty == dst_ty {
242 return (src, old_info.unwrap());
243 }
244 let mut result = None;
245 for i in 0..src_layout.fields.count() {
246 let src_f = src_layout.field(bx.cx(), i);
247 if src_f.is_1zst() {
248 continue;
250 }
251
252 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
253 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
254 assert_eq!(src_layout.size, src_f.size);
255
256 let dst_f = dst_layout.field(bx.cx(), i);
257 assert_ne!(src_f.ty, dst_f.ty);
258 assert_eq!(result, None);
259 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
260 }
261 result.unwrap()
262 }
263 _ => bug!("unsize_ptr: called on bad types"),
264 }
265}
266
267pub(crate) fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
270 bx: &mut Bx,
271 src: PlaceRef<'tcx, Bx::Value>,
272 dst: PlaceRef<'tcx, Bx::Value>,
273) {
274 let src_ty = src.layout.ty;
275 let dst_ty = dst.layout.ty;
276 match (src_ty.kind(), dst_ty.kind()) {
277 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
278 let (base, info) = match bx.load_operand(src).val {
279 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
280 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
281 OperandValue::Ref(..) | OperandValue::ZeroSized => bug!(),
282 };
283 OperandValue::Pair(base, info).store(bx, dst);
284 }
285
286 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
287 assert_eq!(def_a, def_b); for i in def_a.variant(FIRST_VARIANT).fields.indices() {
290 let src_f = src.project_field(bx, i.as_usize());
291 let dst_f = dst.project_field(bx, i.as_usize());
292
293 if dst_f.layout.is_zst() {
294 continue;
296 }
297
298 if src_f.layout.ty == dst_f.layout.ty {
299 bx.typed_place_copy(dst_f.val, src_f.val, src_f.layout);
300 } else {
301 coerce_unsized_into(bx, src_f, dst_f);
302 }
303 }
304 }
305 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
306 }
307}
308
309pub(crate) fn build_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
325 bx: &mut Bx,
326 lhs: Bx::Value,
327 mut rhs: Bx::Value,
328 is_unchecked: bool,
329) -> Bx::Value {
330 let mut rhs_llty = bx.cx().val_ty(rhs);
332 let mut lhs_llty = bx.cx().val_ty(lhs);
333
334 let mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, false);
335 if !is_unchecked {
336 rhs = bx.and(rhs, mask);
337 }
338
339 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
340 rhs_llty = bx.cx().element_type(rhs_llty)
341 }
342 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
343 lhs_llty = bx.cx().element_type(lhs_llty)
344 }
345 let rhs_sz = bx.cx().int_width(rhs_llty);
346 let lhs_sz = bx.cx().int_width(lhs_llty);
347 if lhs_sz < rhs_sz {
348 if is_unchecked { bx.unchecked_utrunc(rhs, lhs_llty) } else { bx.trunc(rhs, lhs_llty) }
349 } else if lhs_sz > rhs_sz {
350 assert!(lhs_sz <= 256);
357 bx.zext(rhs, lhs_llty)
358 } else {
359 rhs
360 }
361}
362
363pub fn wants_wasm_eh(sess: &Session) -> bool {
367 sess.target.is_like_wasm
368 && (sess.target.os != "emscripten" || sess.opts.unstable_opts.emscripten_wasm_eh)
369}
370
371pub fn wants_msvc_seh(sess: &Session) -> bool {
377 sess.target.is_like_msvc
378}
379
380pub(crate) fn wants_new_eh_instructions(sess: &Session) -> bool {
384 wants_wasm_eh(sess) || wants_msvc_seh(sess)
385}
386
387pub(crate) fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
388 cx: &'a Bx::CodegenCx,
389 instance: Instance<'tcx>,
390) {
391 info!("codegen_instance({})", instance);
395
396 mir::codegen_mir::<Bx>(cx, instance);
397}
398
399pub fn codegen_global_asm<'tcx, Cx>(cx: &mut Cx, item_id: ItemId)
400where
401 Cx: LayoutOf<'tcx, LayoutOfResult = TyAndLayout<'tcx>> + AsmCodegenMethods<'tcx>,
402{
403 let item = cx.tcx().hir_item(item_id);
404 if let rustc_hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
405 let operands: Vec<_> = asm
406 .operands
407 .iter()
408 .map(|(op, op_sp)| match *op {
409 rustc_hir::InlineAsmOperand::Const { ref anon_const } => {
410 match cx.tcx().const_eval_poly(anon_const.def_id.to_def_id()) {
411 Ok(const_value) => {
412 let ty =
413 cx.tcx().typeck_body(anon_const.body).node_type(anon_const.hir_id);
414 let string = common::asm_const_to_str(
415 cx.tcx(),
416 *op_sp,
417 const_value,
418 cx.layout_of(ty),
419 );
420 GlobalAsmOperandRef::Const { string }
421 }
422 Err(ErrorHandled::Reported { .. }) => {
423 GlobalAsmOperandRef::Const { string: String::new() }
428 }
429 Err(ErrorHandled::TooGeneric(_)) => {
430 span_bug!(*op_sp, "asm const cannot be resolved; too generic")
431 }
432 }
433 }
434 rustc_hir::InlineAsmOperand::SymFn { expr } => {
435 let ty = cx.tcx().typeck(item_id.owner_id).expr_ty(expr);
436 let instance = match ty.kind() {
437 &ty::FnDef(def_id, args) => Instance::expect_resolve(
438 cx.tcx(),
439 ty::TypingEnv::fully_monomorphized(),
440 def_id,
441 args,
442 expr.span,
443 ),
444 _ => span_bug!(*op_sp, "asm sym is not a function"),
445 };
446
447 GlobalAsmOperandRef::SymFn { instance }
448 }
449 rustc_hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
450 GlobalAsmOperandRef::SymStatic { def_id }
451 }
452 rustc_hir::InlineAsmOperand::In { .. }
453 | rustc_hir::InlineAsmOperand::Out { .. }
454 | rustc_hir::InlineAsmOperand::InOut { .. }
455 | rustc_hir::InlineAsmOperand::SplitInOut { .. }
456 | rustc_hir::InlineAsmOperand::Label { .. } => {
457 span_bug!(*op_sp, "invalid operand type for global_asm!")
458 }
459 })
460 .collect();
461
462 cx.codegen_global_asm(asm.template, &operands, asm.options, asm.line_spans);
463 } else {
464 span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
465 }
466}
467
468pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
471 cx: &'a Bx::CodegenCx,
472 cgu: &CodegenUnit<'tcx>,
473) -> Option<Bx::Function> {
474 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
475 let main_is_local = main_def_id.is_local();
476 let instance = Instance::mono(cx.tcx(), main_def_id);
477
478 if main_is_local {
479 if !cgu.contains_item(&MonoItem::Fn(instance)) {
482 return None;
483 }
484 } else if !cgu.is_primary() {
485 return None;
487 }
488
489 let main_llfn = cx.get_fn_addr(instance);
490
491 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
492 return Some(entry_fn);
493
494 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
495 cx: &'a Bx::CodegenCx,
496 rust_main: Bx::Value,
497 rust_main_def_id: DefId,
498 entry_type: EntryFnType,
499 ) -> Bx::Function {
500 let llfty = if cx.sess().target.os.contains("uefi") {
503 cx.type_func(&[cx.type_ptr(), cx.type_ptr()], cx.type_isize())
504 } else if cx.sess().target.main_needs_argc_argv {
505 cx.type_func(&[cx.type_int(), cx.type_ptr()], cx.type_int())
506 } else {
507 cx.type_func(&[], cx.type_int())
508 };
509
510 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
511 let main_ret_ty = cx
517 .tcx()
518 .normalize_erasing_regions(cx.typing_env(), main_ret_ty.no_bound_vars().unwrap());
519
520 let Some(llfn) = cx.declare_c_main(llfty) else {
521 let span = cx.tcx().def_span(rust_main_def_id);
523 cx.tcx().dcx().emit_fatal(errors::MultipleMainFunctions { span });
524 };
525
526 cx.set_frame_pointer_type(llfn);
528 cx.apply_target_cpu_attr(llfn);
529
530 let llbb = Bx::append_block(cx, llfn, "top");
531 let mut bx = Bx::build(cx, llbb);
532
533 bx.insert_reference_to_gdb_debug_scripts_section_global();
534
535 let isize_ty = cx.type_isize();
536 let ptr_ty = cx.type_ptr();
537 let (arg_argc, arg_argv) = get_argc_argv(&mut bx);
538
539 let EntryFnType::Main { sigpipe } = entry_type;
540 let (start_fn, start_ty, args, instance) = {
541 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, DUMMY_SP);
542 let start_instance = ty::Instance::expect_resolve(
543 cx.tcx(),
544 cx.typing_env(),
545 start_def_id,
546 cx.tcx().mk_args(&[main_ret_ty.into()]),
547 DUMMY_SP,
548 );
549 let start_fn = cx.get_fn_addr(start_instance);
550
551 let i8_ty = cx.type_i8();
552 let arg_sigpipe = bx.const_u8(sigpipe);
553
554 let start_ty = cx.type_func(&[cx.val_ty(rust_main), isize_ty, ptr_ty, i8_ty], isize_ty);
555 (
556 start_fn,
557 start_ty,
558 vec![rust_main, arg_argc, arg_argv, arg_sigpipe],
559 Some(start_instance),
560 )
561 };
562
563 let result = bx.call(start_ty, None, None, start_fn, &args, None, instance);
564 if cx.sess().target.os.contains("uefi") {
565 bx.ret(result);
566 } else {
567 let cast = bx.intcast(result, cx.type_int(), true);
568 bx.ret(cast);
569 }
570
571 llfn
572 }
573}
574
575fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(bx: &mut Bx) -> (Bx::Value, Bx::Value) {
578 if bx.cx().sess().target.os.contains("uefi") {
579 let param_handle = bx.get_param(0);
581 let param_system_table = bx.get_param(1);
582 let ptr_size = bx.tcx().data_layout.pointer_size();
583 let ptr_align = bx.tcx().data_layout.pointer_align().abi;
584 let arg_argc = bx.const_int(bx.cx().type_isize(), 2);
585 let arg_argv = bx.alloca(2 * ptr_size, ptr_align);
586 bx.store(param_handle, arg_argv, ptr_align);
587 let arg_argv_el1 = bx.inbounds_ptradd(arg_argv, bx.const_usize(ptr_size.bytes()));
588 bx.store(param_system_table, arg_argv_el1, ptr_align);
589 (arg_argc, arg_argv)
590 } else if bx.cx().sess().target.main_needs_argc_argv {
591 let param_argc = bx.get_param(0);
593 let param_argv = bx.get_param(1);
594 let arg_argc = bx.intcast(param_argc, bx.cx().type_isize(), true);
595 let arg_argv = param_argv;
596 (arg_argc, arg_argv)
597 } else {
598 let arg_argc = bx.const_int(bx.cx().type_int(), 0);
600 let arg_argv = bx.const_null(bx.cx().type_ptr());
601 (arg_argc, arg_argv)
602 }
603}
604
605pub fn collect_debugger_visualizers_transitive(
609 tcx: TyCtxt<'_>,
610 visualizer_type: DebuggerVisualizerType,
611) -> BTreeSet<DebuggerVisualizerFile> {
612 tcx.debugger_visualizers(LOCAL_CRATE)
613 .iter()
614 .chain(
615 tcx.crates(())
616 .iter()
617 .filter(|&cnum| {
618 let used_crate_source = tcx.used_crate_source(*cnum);
619 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
620 })
621 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
622 )
623 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
624 .cloned()
625 .collect::<BTreeSet<_>>()
626}
627
628pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
632 let all_crate_types_any_dynamic_crate = tcx.dependency_formats(()).iter().all(|(_, list)| {
642 use rustc_middle::middle::dependency_format::Linkage;
643 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
644 });
645 if all_crate_types_any_dynamic_crate { None } else { tcx.allocator_kind(()) }
646}
647
648pub(crate) fn needs_allocator_shim_for_linking(
652 dependency_formats: &Dependencies,
653 crate_type: CrateType,
654) -> bool {
655 use rustc_middle::middle::dependency_format::Linkage;
656 let any_dynamic_crate =
657 dependency_formats[&crate_type].iter().any(|&linkage| linkage == Linkage::Dynamic);
658 !any_dynamic_crate
659}
660
661pub fn allocator_shim_contents(tcx: TyCtxt<'_>, kind: AllocatorKind) -> Vec<AllocatorMethod> {
662 let mut methods = Vec::new();
663
664 if kind == AllocatorKind::Default {
665 methods.extend(ALLOCATOR_METHODS.into_iter().copied());
666 }
667
668 if tcx.alloc_error_handler_kind(()).unwrap() == AllocatorKind::Default {
671 methods.push(AllocatorMethod {
672 name: ALLOC_ERROR_HANDLER,
673 special: None,
674 inputs: &[],
675 output: AllocatorTy::Never,
676 });
677 }
678
679 methods
680}
681
682pub fn codegen_crate<B: ExtraBackendMethods>(
683 backend: B,
684 tcx: TyCtxt<'_>,
685 target_cpu: String,
686) -> OngoingCodegen<B> {
687 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
689 let ongoing_codegen = start_async_codegen(backend, tcx, target_cpu, None);
690
691 ongoing_codegen.codegen_finished(tcx);
692
693 ongoing_codegen.check_for_errors(tcx.sess);
694
695 return ongoing_codegen;
696 }
697
698 if tcx.sess.target.need_explicit_cpu && tcx.sess.opts.cg.target_cpu.is_none() {
699 tcx.dcx().emit_fatal(errors::CpuRequired);
701 }
702
703 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
704
705 let MonoItemPartitions { codegen_units, .. } = tcx.collect_and_partition_mono_items(());
708
709 if tcx.dep_graph.is_fully_enabled() {
715 for cgu in codegen_units {
716 tcx.ensure_ok().codegen_unit(cgu.name());
717 }
718 }
719
720 let allocator_module = if let Some(kind) = allocator_kind_for_codegen(tcx) {
722 let llmod_id =
723 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
724
725 tcx.sess.time("write_allocator_module", || {
726 let module =
727 backend.codegen_allocator(tcx, &llmod_id, &allocator_shim_contents(tcx, kind));
728 Some(ModuleCodegen::new_allocator(llmod_id, module))
729 })
730 } else {
731 None
732 };
733
734 let ongoing_codegen = start_async_codegen(backend.clone(), tcx, target_cpu, allocator_module);
735
736 let codegen_units: Vec<_> = {
748 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
749 sorted_cgus.sort_by_key(|cgu| cmp::Reverse(cgu.size_estimate()));
750
751 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
752 first_half.iter().interleave(second_half.iter().rev()).copied().collect()
753 };
754
755 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
757 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, cgu)).collect::<Vec<_>>()
758 });
759
760 crate::assert_module_sources::assert_module_sources(tcx, &|cgu_reuse_tracker| {
761 for (i, cgu) in codegen_units.iter().enumerate() {
762 let cgu_reuse = cgu_reuse[i];
763 cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
764 }
765 });
766
767 let mut total_codegen_time = Duration::new(0, 0);
768 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
769
770 let mut pre_compiled_cgus = if tcx.sess.threads() > 1 {
781 tcx.sess.time("compile_first_CGU_batch", || {
782 let cgus: Vec<_> = cgu_reuse
784 .iter()
785 .enumerate()
786 .filter(|&(_, reuse)| reuse == &CguReuse::No)
787 .take(tcx.sess.threads())
788 .collect();
789
790 let start_time = Instant::now();
792
793 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
794 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
795 (i, IntoDynSyncSend(module))
796 });
797
798 total_codegen_time += start_time.elapsed();
799
800 pre_compiled_cgus
801 })
802 } else {
803 FxHashMap::default()
804 };
805
806 for (i, cgu) in codegen_units.iter().enumerate() {
807 ongoing_codegen.wait_for_signal_to_codegen_item();
808 ongoing_codegen.check_for_errors(tcx.sess);
809
810 let cgu_reuse = cgu_reuse[i];
811
812 match cgu_reuse {
813 CguReuse::No => {
814 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
815 cgu.0
816 } else {
817 let start_time = Instant::now();
818 let module = backend.compile_codegen_unit(tcx, cgu.name());
819 total_codegen_time += start_time.elapsed();
820 module
821 };
822 tcx.dcx().abort_if_errors();
826
827 submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost);
828 }
829 CguReuse::PreLto => {
830 submit_pre_lto_module_to_llvm(
831 tcx,
832 &ongoing_codegen.coordinator,
833 CachedModuleCodegen {
834 name: cgu.name().to_string(),
835 source: cgu.previous_work_product(tcx),
836 },
837 );
838 }
839 CguReuse::PostLto => {
840 submit_post_lto_module_to_llvm(
841 &ongoing_codegen.coordinator,
842 CachedModuleCodegen {
843 name: cgu.name().to_string(),
844 source: cgu.previous_work_product(tcx),
845 },
846 );
847 }
848 }
849 }
850
851 ongoing_codegen.codegen_finished(tcx);
852
853 if tcx.sess.opts.unstable_opts.time_passes {
856 let end_rss = get_resident_set_size();
857
858 print_time_passes_entry(
859 "codegen_to_LLVM_IR",
860 total_codegen_time,
861 start_rss.unwrap(),
862 end_rss,
863 tcx.sess.opts.unstable_opts.time_passes_format,
864 );
865 }
866
867 ongoing_codegen.check_for_errors(tcx.sess);
868 ongoing_codegen
869}
870
871pub fn is_call_from_compiler_builtins_to_upstream_monomorphization<'tcx>(
881 tcx: TyCtxt<'tcx>,
882 instance: Instance<'tcx>,
883) -> bool {
884 fn is_llvm_intrinsic(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
885 if let Some(name) = tcx.codegen_fn_attrs(def_id).symbol_name {
886 name.as_str().starts_with("llvm.")
887 } else {
888 false
889 }
890 }
891
892 let def_id = instance.def_id();
893 !def_id.is_local()
894 && tcx.is_compiler_builtins(LOCAL_CRATE)
895 && !is_llvm_intrinsic(tcx, def_id)
896 && !tcx.should_codegen_locally(instance)
897}
898
899impl CrateInfo {
900 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
901 let crate_types = tcx.crate_types().to_vec();
902 let exported_symbols = crate_types
903 .iter()
904 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
905 .collect();
906 let linked_symbols =
907 crate_types.iter().map(|&c| (c, crate::back::linker::linked_symbols(tcx, c))).collect();
908 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
909 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
910 let subsystem =
911 ast::attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
912 let windows_subsystem = subsystem.map(|subsystem| {
913 if subsystem != sym::windows && subsystem != sym::console {
914 tcx.dcx().emit_fatal(errors::InvalidWindowsSubsystem { subsystem });
915 }
916 subsystem.to_string()
917 });
918
919 let mut compiler_builtins = None;
928 let mut used_crates: Vec<_> = tcx
929 .postorder_cnums(())
930 .iter()
931 .rev()
932 .copied()
933 .filter(|&cnum| {
934 let link = !tcx.dep_kind(cnum).macros_only();
935 if link && tcx.is_compiler_builtins(cnum) {
936 compiler_builtins = Some(cnum);
937 return false;
938 }
939 link
940 })
941 .collect();
942 used_crates.extend(compiler_builtins);
944
945 let crates = tcx.crates(());
946 let n_crates = crates.len();
947 let mut info = CrateInfo {
948 target_cpu,
949 target_features: tcx.global_backend_features(()).clone(),
950 crate_types,
951 exported_symbols,
952 linked_symbols,
953 local_crate_name,
954 compiler_builtins,
955 profiler_runtime: None,
956 is_no_builtins: Default::default(),
957 native_libraries: Default::default(),
958 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
959 crate_name: UnordMap::with_capacity(n_crates),
960 used_crates,
961 used_crate_source: UnordMap::with_capacity(n_crates),
962 dependency_formats: Arc::clone(tcx.dependency_formats(())),
963 windows_subsystem,
964 natvis_debugger_visualizers: Default::default(),
965 lint_levels: CodegenLintLevels::from_tcx(tcx),
966 metadata_symbol: exported_symbols::metadata_symbol_name(tcx),
967 };
968
969 info.native_libraries.reserve(n_crates);
970
971 for &cnum in crates.iter() {
972 info.native_libraries
973 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
974 info.crate_name.insert(cnum, tcx.crate_name(cnum));
975
976 let used_crate_source = tcx.used_crate_source(cnum);
977 info.used_crate_source.insert(cnum, Arc::clone(used_crate_source));
978 if tcx.is_profiler_runtime(cnum) {
979 info.profiler_runtime = Some(cnum);
980 }
981 if tcx.is_no_builtins(cnum) {
982 info.is_no_builtins.insert(cnum);
983 }
984 }
985
986 let target = &tcx.sess.target;
995 if !are_upstream_rust_objects_already_included(tcx.sess) {
996 let add_prefix = match (target.is_like_windows, target.arch.as_ref()) {
997 (true, "x86") => |name: String, _: SymbolExportKind| format!("_{name}"),
998 (true, "arm64ec") => {
999 |name: String, export_kind: SymbolExportKind| match export_kind {
1001 SymbolExportKind::Text => format!("#{name}"),
1002 _ => name,
1003 }
1004 }
1005 _ => |name: String, _: SymbolExportKind| name,
1006 };
1007 let missing_weak_lang_items: FxIndexSet<(Symbol, SymbolExportKind)> = info
1008 .used_crates
1009 .iter()
1010 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
1011 .filter(|l| l.is_weak())
1012 .filter_map(|&l| {
1013 let name = l.link_name()?;
1014 let export_kind = match l.target() {
1015 Target::Fn => SymbolExportKind::Text,
1016 Target::Static => SymbolExportKind::Data,
1017 _ => bug!(
1018 "Don't know what the export kind is for lang item of kind {:?}",
1019 l.target()
1020 ),
1021 };
1022 lang_items::required(tcx, l).then_some((name, export_kind))
1023 })
1024 .collect();
1025
1026 #[allow(rustc::potential_query_instability)]
1029 info.linked_symbols
1030 .iter_mut()
1031 .filter(|(crate_type, _)| {
1032 !matches!(crate_type, CrateType::Rlib | CrateType::Staticlib)
1033 })
1034 .for_each(|(_, linked_symbols)| {
1035 let mut symbols = missing_weak_lang_items
1036 .iter()
1037 .map(|(item, export_kind)| {
1038 (
1039 add_prefix(
1040 mangle_internal_symbol(tcx, item.as_str()),
1041 *export_kind,
1042 ),
1043 *export_kind,
1044 )
1045 })
1046 .collect::<Vec<_>>();
1047 symbols.sort_unstable_by(|a, b| a.0.cmp(&b.0));
1048 linked_symbols.extend(symbols);
1049 });
1050 }
1051
1052 let embed_visualizers = tcx.crate_types().iter().any(|&crate_type| match crate_type {
1053 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
1054 true
1057 }
1058 CrateType::ProcMacro => {
1059 false
1063 }
1064 CrateType::Staticlib | CrateType::Rlib => {
1065 false
1068 }
1069 });
1070
1071 if target.is_like_msvc && embed_visualizers {
1072 info.natvis_debugger_visualizers =
1073 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
1074 }
1075
1076 info
1077 }
1078}
1079
1080pub(crate) fn provide(providers: &mut Providers) {
1081 providers.backend_optimization_level = |tcx, cratenum| {
1082 let for_speed = match tcx.sess.opts.optimize {
1083 config::OptLevel::No => return config::OptLevel::No,
1090 config::OptLevel::Less => return config::OptLevel::Less,
1092 config::OptLevel::More => return config::OptLevel::More,
1093 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
1094 config::OptLevel::Size => config::OptLevel::More,
1097 config::OptLevel::SizeMin => config::OptLevel::More,
1098 };
1099
1100 let defids = tcx.collect_and_partition_mono_items(cratenum).all_mono_items;
1101
1102 let any_for_speed = defids.items().any(|id| {
1103 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
1104 matches!(optimize, OptimizeAttr::Speed)
1105 });
1106
1107 if any_for_speed {
1108 return for_speed;
1109 }
1110
1111 tcx.sess.opts.optimize
1112 };
1113}
1114
1115pub fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
1116 if !tcx.dep_graph.is_fully_enabled() {
1117 return CguReuse::No;
1118 }
1119
1120 let work_product_id = &cgu.work_product_id();
1121 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1122 return CguReuse::No;
1125 }
1126
1127 let dep_node = cgu.codegen_dep_node(tcx);
1134 tcx.dep_graph.assert_dep_node_not_yet_allocated_in_current_session(&dep_node, || {
1135 format!(
1136 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
1137 cgu.name()
1138 )
1139 });
1140
1141 if tcx.try_mark_green(&dep_node) {
1142 match compute_per_cgu_lto_type(
1146 &tcx.sess.lto(),
1147 &tcx.sess.opts,
1148 tcx.crate_types(),
1149 ModuleKind::Regular,
1150 ) {
1151 ComputedLtoType::No => CguReuse::PostLto,
1152 _ => CguReuse::PreLto,
1153 }
1154 } else {
1155 CguReuse::No
1156 }
1157}