]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_codegen_ssa/src/base.rs
New upstream version 1.71.1+dfsg1
[rustc.git] / compiler / rustc_codegen_ssa / src / base.rs
CommitLineData
f2b60f7d 1use crate::back::link::are_upstream_rust_objects_already_included;
a2a8927a 2use crate::back::metadata::create_compressed_metadata_file;
60c5eb7d 3use crate::back::write::{
f9f354fc
XL
4 compute_per_cgu_lto_type, start_async_codegen, submit_codegened_module_to_llvm,
5 submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, ComputedLtoType, OngoingCodegen,
60c5eb7d 6};
dfeec247 7use crate::common::{IntPredicate, RealPredicate, TypeKind};
9c376795 8use crate::errors;
60c5eb7d
XL
9use crate::meth;
10use crate::mir;
11use crate::mir::operand::OperandValue;
12use crate::mir::place::PlaceRef;
13use crate::traits::*;
a2a8927a 14use crate::{CachedModuleCodegen, CompiledModule, CrateInfo, MemFlags, ModuleCodegen, ModuleKind};
a1dfa0c6 15
49aad941 16use rustc_ast::expand::allocator::{global_fn_name, AllocatorKind, ALLOCATOR_METHODS};
74b04a01 17use rustc_attr as attr;
f2b60f7d 18use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5869c6ff 19use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry};
49aad941 20use rustc_data_structures::sync::par_map;
dfeec247 21use rustc_hir as hir;
cdc7bbd5 22use rustc_hir::def_id::{DefId, LOCAL_CRATE};
3dfed10e 23use rustc_hir::lang_items::LangItem;
c295e0f8 24use rustc_metadata::EncodedMetadata;
ba9703b0 25use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
49aad941 26use rustc_middle::middle::debugger_visualizer::{DebuggerVisualizerFile, DebuggerVisualizerType};
a2a8927a 27use rustc_middle::middle::exported_symbols;
f2b60f7d 28use rustc_middle::middle::exported_symbols::SymbolExportKind;
ba9703b0
XL
29use rustc_middle::middle::lang_items;
30use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem};
49aad941 31use rustc_middle::query::Providers;
c295e0f8 32use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout};
ba9703b0 33use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
dfeec247 34use rustc_session::cgu_reuse_tracker::CguReuse;
923072b8 35use rustc_session::config::{self, CrateType, EntryFnType, OutputType};
ba9703b0 36use rustc_session::Session;
17df50a5 37use rustc_span::symbol::sym;
f2b60f7d 38use rustc_span::Symbol;
353b0b11 39use rustc_target::abi::{Align, FIRST_VARIANT};
a1dfa0c6 40
923072b8 41use std::collections::BTreeSet;
dfeec247 42use std::time::{Duration, Instant};
a1dfa0c6 43
5869c6ff
XL
44use itertools::Itertools;
45
dfeec247 46pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind, signed: bool) -> IntPredicate {
a1dfa0c6
XL
47 match op {
48 hir::BinOpKind::Eq => IntPredicate::IntEQ,
49 hir::BinOpKind::Ne => IntPredicate::IntNE,
dfeec247
XL
50 hir::BinOpKind::Lt => {
51 if signed {
52 IntPredicate::IntSLT
53 } else {
54 IntPredicate::IntULT
55 }
a1dfa0c6 56 }
dfeec247
XL
57 hir::BinOpKind::Le => {
58 if signed {
59 IntPredicate::IntSLE
60 } else {
61 IntPredicate::IntULE
62 }
63 }
64 hir::BinOpKind::Gt => {
65 if signed {
66 IntPredicate::IntSGT
67 } else {
68 IntPredicate::IntUGT
69 }
70 }
71 hir::BinOpKind::Ge => {
72 if signed {
73 IntPredicate::IntSGE
74 } else {
75 IntPredicate::IntUGE
76 }
77 }
78 op => bug!(
79 "comparison_op_to_icmp_predicate: expected comparison operator, \
80 found {:?}",
81 op
82 ),
a1dfa0c6
XL
83 }
84}
85
86pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> RealPredicate {
87 match op {
88 hir::BinOpKind::Eq => RealPredicate::RealOEQ,
89 hir::BinOpKind::Ne => RealPredicate::RealUNE,
90 hir::BinOpKind::Lt => RealPredicate::RealOLT,
91 hir::BinOpKind::Le => RealPredicate::RealOLE,
92 hir::BinOpKind::Gt => RealPredicate::RealOGT,
93 hir::BinOpKind::Ge => RealPredicate::RealOGE,
94 op => {
dfeec247
XL
95 bug!(
96 "comparison_op_to_fcmp_predicate: expected comparison operator, \
97 found {:?}",
98 op
99 );
a1dfa0c6
XL
100 }
101 }
102}
103
dc9dc135 104pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
a1dfa0c6
XL
105 bx: &mut Bx,
106 lhs: Bx::Value,
107 rhs: Bx::Value,
108 t: Ty<'tcx>,
109 ret_ty: Bx::Type,
dc9dc135 110 op: hir::BinOpKind,
a1dfa0c6 111) -> Bx::Value {
1b1a35ee 112 let signed = match t.kind() {
a1dfa0c6
XL
113 ty::Float(_) => {
114 let cmp = bin_op_to_fcmp_predicate(op);
115 let cmp = bx.fcmp(cmp, lhs, rhs);
116 return bx.sext(cmp, ret_ty);
dfeec247 117 }
a1dfa0c6
XL
118 ty::Uint(_) => false,
119 ty::Int(_) => true,
120 _ => bug!("compare_simd_types: invalid SIMD type"),
121 };
122
123 let cmp = bin_op_to_icmp_predicate(op, signed);
124 let cmp = bx.icmp(cmp, lhs, rhs);
125 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
126 // to get the correctly sized type. This will compile to a single instruction
127 // once the IR is converted to assembly if the SIMD instruction is supported
128 // by the target architecture.
129 bx.sext(cmp, ret_ty)
130}
131
9fa01778 132/// Retrieves the information we are losing (making dynamic) in an unsizing
a1dfa0c6
XL
133/// adjustment.
134///
60c5eb7d
XL
135/// The `old_info` argument is a bit odd. It is intended for use in an upcast,
136/// where the new vtable for an object will be derived from the old one.
94222f64
XL
137pub fn unsized_info<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
138 bx: &mut Bx,
a1dfa0c6
XL
139 source: Ty<'tcx>,
140 target: Ty<'tcx>,
94222f64
XL
141 old_info: Option<Bx::Value>,
142) -> Bx::Value {
143 let cx = bx.cx();
416331ca 144 let (source, target) =
94222f64 145 cx.tcx().struct_lockstep_tails_erasing_lifetimes(source, target, bx.param_env());
1b1a35ee 146 match (source.kind(), target.kind()) {
a1dfa0c6 147 (&ty::Array(_, len), &ty::Slice(_)) => {
9ffffee4 148 cx.const_usize(len.eval_target_usize(cx.tcx(), ty::ParamEnv::reveal_all()))
a1dfa0c6 149 }
2b03887a
FG
150 (
151 &ty::Dynamic(ref data_a, _, src_dyn_kind),
152 &ty::Dynamic(ref data_b, _, target_dyn_kind),
9c376795 153 ) if src_dyn_kind == target_dyn_kind => {
94222f64
XL
154 let old_info =
155 old_info.expect("unsized_info: missing old info for trait upcasting coercion");
156 if data_a.principal_def_id() == data_b.principal_def_id() {
f2b60f7d 157 // A NOP cast that doesn't actually change anything, should be allowed even with invalid vtables.
94222f64
XL
158 return old_info;
159 }
160
161 // trait upcasting coercion
162
163 let vptr_entry_idx =
164 cx.tcx().vtable_trait_upcasting_coercion_new_vptr_slot((source, target));
165
166 if let Some(entry_idx) = vptr_entry_idx {
167 let ptr_ty = cx.type_i8p();
168 let ptr_align = cx.tcx().data_layout.pointer_align.abi;
2b03887a 169 let vtable_ptr_ty = vtable_ptr_ty(cx, target, target_dyn_kind);
94222f64
XL
170 let llvtable = bx.pointercast(old_info, bx.type_ptr_to(ptr_ty));
171 let gep = bx.inbounds_gep(
172 ptr_ty,
173 llvtable,
174 &[bx.const_usize(u64::try_from(entry_idx).unwrap())],
175 );
176 let new_vptr = bx.load(ptr_ty, gep, ptr_align);
177 bx.nonnull_metadata(new_vptr);
064997fb 178 // VTable loads are invariant.
94222f64 179 bx.set_invariant_load(new_vptr);
f2b60f7d 180 bx.pointercast(new_vptr, vtable_ptr_ty)
94222f64
XL
181 } else {
182 old_info
183 }
a1dfa0c6 184 }
2b03887a
FG
185 (_, &ty::Dynamic(ref data, _, target_dyn_kind)) => {
186 let vtable_ptr_ty = vtable_ptr_ty(cx, target, target_dyn_kind);
94222f64 187 cx.const_ptrcast(meth::get_vtable(cx, source, data.principal()), vtable_ptr_ty)
a1dfa0c6 188 }
dfeec247 189 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
a1dfa0c6
XL
190 }
191}
192
2b03887a
FG
193// Returns the vtable pointer type of a `dyn` or `dyn*` type
194fn vtable_ptr_ty<'tcx, Cx: CodegenMethods<'tcx>>(
195 cx: &Cx,
196 target: Ty<'tcx>,
197 kind: ty::DynKind,
198) -> <Cx as BackendTypes>::Type {
199 cx.scalar_pair_element_backend_type(
200 cx.layout_of(match kind {
201 // vtable is the second field of `*mut dyn Trait`
202 ty::Dyn => cx.tcx().mk_mut_ptr(target),
203 // vtable is the second field of `dyn* Trait`
204 ty::DynStar => target,
205 }),
206 1,
207 true,
208 )
209}
210
94222f64
XL
211/// Coerces `src` to `dst_ty`. `src_ty` must be a pointer.
212pub fn unsize_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
a1dfa0c6
XL
213 bx: &mut Bx,
214 src: Bx::Value,
215 src_ty: Ty<'tcx>,
dc9dc135 216 dst_ty: Ty<'tcx>,
94222f64 217 old_info: Option<Bx::Value>,
a1dfa0c6 218) -> (Bx::Value, Bx::Value) {
94222f64 219 debug!("unsize_ptr: {:?} => {:?}", src_ty, dst_ty);
1b1a35ee 220 match (src_ty.kind(), dst_ty.kind()) {
ba9703b0 221 (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(ty::TypeAndMut { ty: b, .. }))
dfeec247 222 | (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
94222f64 223 assert_eq!(bx.cx().type_is_sized(a), old_info.is_none());
a1dfa0c6 224 let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
94222f64 225 (bx.pointercast(src, ptr_ty), unsized_info(bx, a, b, old_info))
a1dfa0c6 226 }
a1dfa0c6
XL
227 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
228 assert_eq!(def_a, def_b);
a1dfa0c6
XL
229 let src_layout = bx.cx().layout_of(src_ty);
230 let dst_layout = bx.cx().layout_of(dst_ty);
94222f64
XL
231 if src_ty == dst_ty {
232 return (src, old_info.unwrap());
233 }
a1dfa0c6
XL
234 let mut result = None;
235 for i in 0..src_layout.fields.count() {
236 let src_f = src_layout.field(bx.cx(), i);
a1dfa0c6
XL
237 if src_f.is_zst() {
238 continue;
239 }
923072b8
FG
240
241 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
242 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
a1dfa0c6
XL
243 assert_eq!(src_layout.size, src_f.size);
244
245 let dst_f = dst_layout.field(bx.cx(), i);
246 assert_ne!(src_f.ty, dst_f.ty);
247 assert_eq!(result, None);
94222f64 248 result = Some(unsize_ptr(bx, src, src_f.ty, dst_f.ty, old_info));
a1dfa0c6
XL
249 }
250 let (lldata, llextra) = result.unwrap();
94222f64
XL
251 let lldata_ty = bx.cx().scalar_pair_element_backend_type(dst_layout, 0, true);
252 let llextra_ty = bx.cx().scalar_pair_element_backend_type(dst_layout, 1, true);
a1dfa0c6 253 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
94222f64 254 (bx.bitcast(lldata, lldata_ty), bx.bitcast(llextra, llextra_ty))
a1dfa0c6 255 }
94222f64 256 _ => bug!("unsize_ptr: called on bad types"),
a1dfa0c6
XL
257 }
258}
259
2b03887a
FG
260/// Coerces `src` to `dst_ty` which is guaranteed to be a `dyn*` type.
261pub fn cast_to_dyn_star<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
262 bx: &mut Bx,
263 src: Bx::Value,
264 src_ty_and_layout: TyAndLayout<'tcx>,
265 dst_ty: Ty<'tcx>,
266 old_info: Option<Bx::Value>,
267) -> (Bx::Value, Bx::Value) {
268 debug!("cast_to_dyn_star: {:?} => {:?}", src_ty_and_layout.ty, dst_ty);
269 assert!(
270 matches!(dst_ty.kind(), ty::Dynamic(_, _, ty::DynStar)),
271 "destination type must be a dyn*"
272 );
9ffffee4
FG
273 // FIXME(dyn-star): We can remove this when all supported LLVMs use opaque ptrs only.
274 let unit_ptr = bx.cx().type_ptr_to(bx.cx().type_struct(&[], false));
275 let src = match bx.cx().type_kind(bx.cx().backend_type(src_ty_and_layout)) {
276 TypeKind::Pointer => bx.pointercast(src, unit_ptr),
277 TypeKind::Integer => bx.inttoptr(src, unit_ptr),
278 // FIXME(dyn-star): We probably have to do a bitcast first, then inttoptr.
279 kind => bug!("unexpected TypeKind for left-hand side of `dyn*` cast: {kind:?}"),
2b03887a
FG
280 };
281 (src, unsized_info(bx, src_ty_and_layout.ty, dst_ty, old_info))
282}
283
60c5eb7d
XL
284/// Coerces `src`, which is a reference to a value of type `src_ty`,
285/// to a value of type `dst_ty`, and stores the result in `dst`.
dc9dc135 286pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
a1dfa0c6
XL
287 bx: &mut Bx,
288 src: PlaceRef<'tcx, Bx::Value>,
dc9dc135
XL
289 dst: PlaceRef<'tcx, Bx::Value>,
290) {
a1dfa0c6
XL
291 let src_ty = src.layout.ty;
292 let dst_ty = dst.layout.ty;
1b1a35ee 293 match (src_ty.kind(), dst_ty.kind()) {
ba9703b0 294 (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
e74abb32 295 let (base, info) = match bx.load_operand(src).val {
94222f64
XL
296 OperandValue::Pair(base, info) => unsize_ptr(bx, base, src_ty, dst_ty, Some(info)),
297 OperandValue::Immediate(base) => unsize_ptr(bx, base, src_ty, dst_ty, None),
dfeec247 298 OperandValue::Ref(..) => bug!(),
e74abb32
XL
299 };
300 OperandValue::Pair(base, info).store(bx, dst);
a1dfa0c6
XL
301 }
302
303 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
304 assert_eq!(def_a, def_b);
305
353b0b11
FG
306 for i in def_a.variant(FIRST_VARIANT).fields.indices() {
307 let src_f = src.project_field(bx, i.as_usize());
308 let dst_f = dst.project_field(bx, i.as_usize());
a1dfa0c6
XL
309
310 if dst_f.layout.is_zst() {
311 continue;
312 }
313
314 if src_f.layout.ty == dst_f.layout.ty {
dfeec247
XL
315 memcpy_ty(
316 bx,
317 dst_f.llval,
318 dst_f.align,
319 src_f.llval,
320 src_f.align,
321 src_f.layout,
322 MemFlags::empty(),
323 );
a1dfa0c6
XL
324 } else {
325 coerce_unsized_into(bx, src_f, dst_f);
326 }
327 }
328 }
dfeec247 329 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
a1dfa0c6
XL
330 }
331}
332
dc9dc135 333pub fn cast_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
a1dfa0c6 334 bx: &mut Bx,
a1dfa0c6
XL
335 lhs: Bx::Value,
336 rhs: Bx::Value,
337) -> Bx::Value {
338 // Shifts may have any size int on the rhs
2b03887a
FG
339 let mut rhs_llty = bx.cx().val_ty(rhs);
340 let mut lhs_llty = bx.cx().val_ty(lhs);
341 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
342 rhs_llty = bx.cx().element_type(rhs_llty)
343 }
344 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
345 lhs_llty = bx.cx().element_type(lhs_llty)
346 }
347 let rhs_sz = bx.cx().int_width(rhs_llty);
348 let lhs_sz = bx.cx().int_width(lhs_llty);
349 if lhs_sz < rhs_sz {
350 bx.trunc(rhs, lhs_llty)
351 } else if lhs_sz > rhs_sz {
352 // FIXME (#1877: If in the future shifting by negative
353 // values is no longer undefined then this is wrong.
354 bx.zext(rhs, lhs_llty)
a1dfa0c6
XL
355 } else {
356 rhs
357 }
358}
359
9fa01778 360/// Returns `true` if this session's target will use SEH-based unwinding.
a1dfa0c6
XL
361///
362/// This is only true for MSVC targets, and even then the 64-bit MSVC target
363/// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
364/// 64-bit MinGW) instead of "full SEH".
365pub fn wants_msvc_seh(sess: &Session) -> bool {
29967ef6 366 sess.target.is_like_msvc
a1dfa0c6
XL
367}
368
dc9dc135 369pub fn memcpy_ty<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
a1dfa0c6
XL
370 bx: &mut Bx,
371 dst: Bx::Value,
372 dst_align: Align,
373 src: Bx::Value,
374 src_align: Align,
ba9703b0 375 layout: TyAndLayout<'tcx>,
a1dfa0c6
XL
376 flags: MemFlags,
377) {
378 let size = layout.size.bytes();
379 if size == 0 {
380 return;
381 }
382
383 bx.memcpy(dst, dst_align, src, src_align, bx.cx().const_usize(size), flags);
384}
385
386pub fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
387 cx: &'a Bx::CodegenCx,
388 instance: Instance<'tcx>,
389) {
a1dfa0c6
XL
390 // this is an info! to allow collecting monomorphization statistics
391 // and to allow finding the last function before LLVM aborts from
392 // release builds.
393 info!("codegen_instance({})", instance);
394
60c5eb7d 395 mir::codegen_mir::<Bx>(cx, instance);
a1dfa0c6
XL
396}
397
9fa01778 398/// Creates the `main` function which will initialize the rust runtime and call
a1dfa0c6 399/// users main function.
74b04a01
XL
400pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
401 cx: &'a Bx::CodegenCx,
402) -> Option<Bx::Function> {
17df50a5 403 let (main_def_id, entry_type) = cx.tcx().entry_fn(())?;
cdc7bbd5
XL
404 let main_is_local = main_def_id.is_local();
405 let instance = Instance::mono(cx.tcx(), main_def_id);
a1dfa0c6 406
cdc7bbd5 407 if main_is_local {
a1dfa0c6
XL
408 // We want to create the wrapper in the same codegen unit as Rust's main
409 // function.
cdc7bbd5
XL
410 if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
411 return None;
412 }
17df50a5
XL
413 } else if !cx.codegen_unit().is_primary() {
414 // We want to create the wrapper only when the codegen unit is the primary one
415 return None;
a1dfa0c6
XL
416 }
417
e74abb32 418 let main_llfn = cx.get_fn_addr(instance);
a1dfa0c6 419
f2b60f7d 420 let entry_fn = create_entry_fn::<Bx>(cx, main_llfn, main_def_id, entry_type);
17df50a5 421 return Some(entry_fn);
a1dfa0c6 422
dc9dc135 423 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
a1dfa0c6 424 cx: &'a Bx::CodegenCx,
a1dfa0c6 425 rust_main: Bx::Value,
cdc7bbd5 426 rust_main_def_id: DefId,
f2b60f7d 427 entry_type: EntryFnType,
74b04a01 428 ) -> Bx::Function {
e74abb32
XL
429 // The entry function is either `int main(void)` or `int main(int argc, char **argv)`,
430 // depending on whether the target needs `argc` and `argv` to be passed in.
29967ef6 431 let llfty = if cx.sess().target.main_needs_argc_argv {
e74abb32
XL
432 cx.type_func(&[cx.type_int(), cx.type_ptr_to(cx.type_i8p())], cx.type_int())
433 } else {
434 cx.type_func(&[], cx.type_int())
435 };
a1dfa0c6 436
9ffffee4 437 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).no_bound_vars().unwrap().output();
a1dfa0c6
XL
438 // Given that `main()` has no arguments,
439 // then its return type cannot have
440 // late-bound regions, since late-bound
441 // regions must appear in the argument
442 // listing.
5e7ed085
FG
443 let main_ret_ty = cx.tcx().normalize_erasing_regions(
444 ty::ParamEnv::reveal_all(),
445 main_ret_ty.no_bound_vars().unwrap(),
446 );
447
448 let Some(llfn) = cx.declare_c_main(llfty) else {
449 // FIXME: We should be smart and show a better diagnostic here.
450 let span = cx.tcx().def_span(rust_main_def_id);
9c376795 451 cx.sess().emit_err(errors::MultipleMainFunctions { span });
5e7ed085
FG
452 cx.sess().abort_if_errors();
453 bug!();
1b1a35ee 454 };
a1dfa0c6
XL
455
456 // `main` should respect same config for frame pointer elimination as rest of code
136023e0 457 cx.set_frame_pointer_type(llfn);
a1dfa0c6
XL
458 cx.apply_target_cpu_attr(llfn);
459
17df50a5
XL
460 let llbb = Bx::append_block(&cx, llfn, "top");
461 let mut bx = Bx::build(&cx, llbb);
a1dfa0c6
XL
462
463 bx.insert_reference_to_gdb_debug_scripts_section_global();
464
94222f64
XL
465 let isize_ty = cx.type_isize();
466 let i8pp_ty = cx.type_ptr_to(cx.type_i8p());
e74abb32 467 let (arg_argc, arg_argv) = get_argc_argv(cx, &mut bx);
a1dfa0c6 468
f2b60f7d 469 let (start_fn, start_ty, args) = if let EntryFnType::Main { sigpipe } = entry_type {
3dfed10e 470 let start_def_id = cx.tcx().require_lang_item(LangItem::Start, None);
e74abb32
XL
471 let start_fn = cx.get_fn_addr(
472 ty::Instance::resolve(
473 cx.tcx(),
474 ty::ParamEnv::reveal_all(),
475 start_def_id,
9ffffee4 476 cx.tcx().mk_substs(&[main_ret_ty.into()]),
dfeec247 477 )
f9f354fc 478 .unwrap()
dfeec247 479 .unwrap(),
a1dfa0c6 480 );
f2b60f7d
FG
481
482 let i8_ty = cx.type_i8();
483 let arg_sigpipe = bx.const_u8(sigpipe);
484
485 let start_ty =
486 cx.type_func(&[cx.val_ty(rust_main), isize_ty, i8pp_ty, i8_ty], isize_ty);
487 (start_fn, start_ty, vec![rust_main, arg_argc, arg_argv, arg_sigpipe])
a1dfa0c6
XL
488 } else {
489 debug!("using user-defined start fn");
94222f64
XL
490 let start_ty = cx.type_func(&[isize_ty, i8pp_ty], isize_ty);
491 (rust_main, start_ty, vec![arg_argc, arg_argv])
a1dfa0c6
XL
492 };
493
49aad941 494 let result = bx.call(start_ty, None, None, start_fn, &args, None);
a1dfa0c6
XL
495 let cast = bx.intcast(result, cx.type_int(), true);
496 bx.ret(cast);
74b04a01
XL
497
498 llfn
a1dfa0c6
XL
499 }
500}
501
e74abb32
XL
502/// Obtain the `argc` and `argv` values to pass to the rust start function.
503fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
504 cx: &'a Bx::CodegenCx,
dfeec247
XL
505 bx: &mut Bx,
506) -> (Bx::Value, Bx::Value) {
29967ef6 507 if cx.sess().target.main_needs_argc_argv {
e74abb32
XL
508 // Params from native `main()` used as args for rust start function
509 let param_argc = bx.get_param(0);
510 let param_argv = bx.get_param(1);
511 let arg_argc = bx.intcast(param_argc, cx.type_isize(), true);
512 let arg_argv = param_argv;
513 (arg_argc, arg_argv)
514 } else {
515 // The Rust start function doesn't need `argc` and `argv`, so just pass zeros.
516 let arg_argc = bx.const_int(cx.type_int(), 0);
517 let arg_argv = bx.const_null(cx.type_ptr_to(cx.type_i8p()));
518 (arg_argc, arg_argv)
519 }
520}
521
923072b8
FG
522/// This function returns all of the debugger visualizers specified for the
523/// current crate as well as all upstream crates transitively that match the
524/// `visualizer_type` specified.
525pub fn collect_debugger_visualizers_transitive(
526 tcx: TyCtxt<'_>,
527 visualizer_type: DebuggerVisualizerType,
528) -> BTreeSet<DebuggerVisualizerFile> {
529 tcx.debugger_visualizers(LOCAL_CRATE)
530 .iter()
531 .chain(
532 tcx.crates(())
533 .iter()
534 .filter(|&cnum| {
535 let used_crate_source = tcx.used_crate_source(*cnum);
536 used_crate_source.rlib.is_some() || used_crate_source.rmeta.is_some()
537 })
538 .flat_map(|&cnum| tcx.debugger_visualizers(cnum)),
539 )
540 .filter(|visualizer| visualizer.visualizer_type == visualizer_type)
541 .cloned()
542 .collect::<BTreeSet<_>>()
543}
544
353b0b11
FG
545/// Decide allocator kind to codegen. If `Some(_)` this will be the same as
546/// `tcx.allocator_kind`, but it may be `None` in more cases (e.g. if using
547/// allocator definitions from a dylib dependency).
548pub fn allocator_kind_for_codegen(tcx: TyCtxt<'_>) -> Option<AllocatorKind> {
549 // If the crate doesn't have an `allocator_kind` set then there's definitely
550 // no shim to generate. Otherwise we also check our dependency graph for all
551 // our output crate types. If anything there looks like its a `Dynamic`
552 // linkage, then it's already got an allocator shim and we'll be using that
553 // one instead. If nothing exists then it's our job to generate the
554 // allocator!
555 let any_dynamic_crate = tcx.dependency_formats(()).iter().any(|(_, list)| {
556 use rustc_middle::middle::dependency_format::Linkage;
557 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
558 });
559 if any_dynamic_crate { None } else { tcx.allocator_kind(()) }
560}
561
a1dfa0c6
XL
562pub fn codegen_crate<B: ExtraBackendMethods>(
563 backend: B,
a2a8927a 564 tcx: TyCtxt<'_>,
17df50a5 565 target_cpu: String,
48663c56
XL
566 metadata: EncodedMetadata,
567 need_metadata_module: bool,
a1dfa0c6 568) -> OngoingCodegen<B> {
a1dfa0c6 569 // Skip crate items and just output metadata in -Z no-codegen mode.
064997fb 570 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
a2a8927a 571 let ongoing_codegen = start_async_codegen(backend, tcx, target_cpu, metadata, None, 1);
a1dfa0c6 572
a1dfa0c6
XL
573 ongoing_codegen.codegen_finished(tcx);
574
a1dfa0c6
XL
575 ongoing_codegen.check_for_errors(tcx.sess);
576
577 return ongoing_codegen;
578 }
579
48663c56
XL
580 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
581
a1dfa0c6
XL
582 // Run the monomorphization collector and partition the collected items into
583 // codegen units.
17df50a5 584 let codegen_units = tcx.collect_and_partition_mono_items(()).1;
a1dfa0c6
XL
585
586 // Force all codegen_unit queries so they are already either red or green
587 // when compile_codegen_unit accesses them. We are not able to re-execute
588 // the codegen_unit query from just the DepNode, so an unknown color would
589 // lead to having to re-execute compile_codegen_unit, possibly
590 // unnecessarily.
591 if tcx.dep_graph.is_fully_enabled() {
ba9703b0 592 for cgu in codegen_units {
f9f354fc 593 tcx.ensure().codegen_unit(cgu.name());
a1dfa0c6
XL
594 }
595 }
596
9ffffee4 597 let metadata_module = need_metadata_module.then(|| {
a2a8927a
XL
598 // Emit compressed metadata object.
599 let metadata_cgu_name =
600 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
601 tcx.sess.time("write_compressed_metadata", || {
602 let file_name =
603 tcx.output_filenames(()).temp_path(OutputType::Metadata, Some(&metadata_cgu_name));
604 let data = create_compressed_metadata_file(
605 tcx.sess,
606 &metadata,
607 &exported_symbols::metadata_symbol_name(tcx),
608 );
9c376795
FG
609 if let Err(error) = std::fs::write(&file_name, data) {
610 tcx.sess.emit_fatal(errors::MetadataObjectFileWrite { error });
a2a8927a 611 }
9ffffee4 612 CompiledModule {
a2a8927a
XL
613 name: metadata_cgu_name,
614 kind: ModuleKind::Metadata,
615 object: Some(file_name),
616 dwarf_object: None,
617 bytecode: None,
9ffffee4 618 }
a2a8927a 619 })
9ffffee4 620 });
a2a8927a
XL
621
622 let ongoing_codegen = start_async_codegen(
623 backend.clone(),
624 tcx,
625 target_cpu,
626 metadata,
627 metadata_module,
628 codegen_units.len(),
629 );
a1dfa0c6
XL
630
631 // Codegen an allocator shim, if necessary.
353b0b11 632 if let Some(kind) = allocator_kind_for_codegen(tcx) {
dfeec247
XL
633 let llmod_id =
634 cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
04454e1e 635 let module_llvm = tcx.sess.time("write_allocator_module", || {
487cf647
FG
636 backend.codegen_allocator(
637 tcx,
638 &llmod_id,
639 kind,
640 // If allocator_kind is Some then alloc_error_handler_kind must
641 // also be Some.
642 tcx.alloc_error_handler_kind(()).unwrap(),
643 )
29967ef6 644 });
a1dfa0c6 645
353b0b11
FG
646 ongoing_codegen.submit_pre_codegened_module_to_llvm(
647 tcx,
648 ModuleCodegen { name: llmod_id, module_llvm, kind: ModuleKind::Allocator },
649 );
a1dfa0c6
XL
650 }
651
5869c6ff
XL
652 // For better throughput during parallel processing by LLVM, we used to sort
653 // CGUs largest to smallest. This would lead to better thread utilization
654 // by, for example, preventing a large CGU from being processed last and
655 // having only one LLVM thread working while the rest remained idle.
656 //
657 // However, this strategy would lead to high memory usage, as it meant the
658 // LLVM-IR for all of the largest CGUs would be resident in memory at once.
659 //
660 // Instead, we can compromise by ordering CGUs such that the largest and
661 // smallest are first, second largest and smallest are next, etc. If there
662 // are large size variations, this can reduce memory usage significantly.
663 let codegen_units: Vec<_> = {
664 let mut sorted_cgus = codegen_units.iter().collect::<Vec<_>>();
665 sorted_cgus.sort_by_cached_key(|cgu| cgu.size_estimate());
666
667 let (first_half, second_half) = sorted_cgus.split_at(sorted_cgus.len() / 2);
668 second_half.iter().rev().interleave(first_half).copied().collect()
a1dfa0c6
XL
669 };
670
923072b8
FG
671 // Calculate the CGU reuse
672 let cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
673 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, &cgu)).collect::<Vec<_>>()
674 });
675
676 let mut total_codegen_time = Duration::new(0, 0);
9c376795 677 let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size());
923072b8 678
dfeec247
XL
679 // The non-parallel compiler can only translate codegen units to LLVM IR
680 // on a single thread, leading to a staircase effect where the N LLVM
681 // threads have to wait on the single codegen threads to generate work
682 // for them. The parallel compiler does not have this restriction, so
683 // we can pre-load the LLVM queue in parallel before handing off
684 // coordination to the OnGoingCodegen scheduler.
685 //
686 // This likely is a temporary measure. Once we don't have to support the
687 // non-parallel compiler anymore, we can compile CGUs end-to-end in
688 // parallel and get rid of the complicated scheduling logic.
49aad941 689 let mut pre_compiled_cgus = if tcx.sess.threads() > 1 {
5e7ed085
FG
690 tcx.sess.time("compile_first_CGU_batch", || {
691 // Try to find one CGU to compile per thread.
692 let cgus: Vec<_> = cgu_reuse
693 .iter()
694 .enumerate()
695 .filter(|&(_, reuse)| reuse == &CguReuse::No)
696 .take(tcx.sess.threads())
697 .collect();
698
699 // Compile the found CGUs in parallel.
700 let start_time = Instant::now();
701
49aad941
FG
702 let pre_compiled_cgus = par_map(cgus, |(i, _)| {
703 let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
704 (i, module)
705 });
5e7ed085 706
923072b8
FG
707 total_codegen_time += start_time.elapsed();
708
709 pre_compiled_cgus
5e7ed085 710 })
923072b8
FG
711 } else {
712 FxHashMap::default()
dfeec247
XL
713 };
714
dfeec247 715 for (i, cgu) in codegen_units.iter().enumerate() {
a1dfa0c6
XL
716 ongoing_codegen.wait_for_signal_to_codegen_item();
717 ongoing_codegen.check_for_errors(tcx.sess);
718
dfeec247 719 let cgu_reuse = cgu_reuse[i];
a2a8927a 720 tcx.sess.cgu_reuse_tracker.set_actual_reuse(cgu.name().as_str(), cgu_reuse);
a1dfa0c6
XL
721
722 match cgu_reuse {
723 CguReuse::No => {
923072b8
FG
724 let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) {
725 cgu
726 } else {
727 let start_time = Instant::now();
728 let module = backend.compile_codegen_unit(tcx, cgu.name());
729 total_codegen_time += start_time.elapsed();
730 module
731 };
5869c6ff
XL
732 // This will unwind if there are errors, which triggers our `AbortCodegenOnDrop`
733 // guard. Unfortunately, just skipping the `submit_codegened_module_to_llvm` makes
734 // compilation hang on post-monomorphization errors.
735 tcx.sess.abort_if_errors();
736
dfeec247
XL
737 submit_codegened_module_to_llvm(
738 &backend,
064997fb 739 &ongoing_codegen.coordinator.sender,
dfeec247
XL
740 module,
741 cost,
742 );
a1dfa0c6
XL
743 false
744 }
745 CguReuse::PreLto => {
dfeec247
XL
746 submit_pre_lto_module_to_llvm(
747 &backend,
748 tcx,
064997fb 749 &ongoing_codegen.coordinator.sender,
dfeec247
XL
750 CachedModuleCodegen {
751 name: cgu.name().to_string(),
923072b8 752 source: cgu.previous_work_product(tcx),
dfeec247
XL
753 },
754 );
a1dfa0c6
XL
755 true
756 }
757 CguReuse::PostLto => {
dfeec247
XL
758 submit_post_lto_module_to_llvm(
759 &backend,
064997fb 760 &ongoing_codegen.coordinator.sender,
dfeec247
XL
761 CachedModuleCodegen {
762 name: cgu.name().to_string(),
923072b8 763 source: cgu.previous_work_product(tcx),
dfeec247
XL
764 },
765 );
a1dfa0c6
XL
766 true
767 }
768 };
769 }
770
771 ongoing_codegen.codegen_finished(tcx);
772
773 // Since the main thread is sometimes blocked during codegen, we keep track
774 // -Ztime-passes output manually.
9c376795 775 if tcx.sess.opts.unstable_opts.time_passes {
5869c6ff
XL
776 let end_rss = get_resident_set_size();
777
778 print_time_passes_entry(
779 "codegen_to_LLVM_IR",
780 total_codegen_time,
781 start_rss.unwrap(),
782 end_rss,
353b0b11 783 tcx.sess.opts.unstable_opts.time_passes_format,
5869c6ff
XL
784 );
785 }
a1dfa0c6 786
a1dfa0c6 787 ongoing_codegen.check_for_errors(tcx.sess);
064997fb 788 ongoing_codegen
a1dfa0c6
XL
789}
790
a1dfa0c6 791impl CrateInfo {
136023e0
XL
792 pub fn new(tcx: TyCtxt<'_>, target_cpu: String) -> CrateInfo {
793 let exported_symbols = tcx
794 .sess
795 .crate_types()
796 .iter()
797 .map(|&c| (c, crate::back::linker::exported_symbols(tcx, c)))
798 .collect();
04454e1e
FG
799 let linked_symbols = tcx
800 .sess
801 .crate_types()
802 .iter()
803 .map(|&c| (c, crate::back::linker::linked_symbols(tcx, c)))
804 .collect();
17df50a5
XL
805 let local_crate_name = tcx.crate_name(LOCAL_CRATE);
806 let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID);
353b0b11 807 let subsystem = attr::first_attr_value_str_by_name(crate_attrs, sym::windows_subsystem);
17df50a5
XL
808 let windows_subsystem = subsystem.map(|subsystem| {
809 if subsystem != sym::windows && subsystem != sym::console {
9c376795 810 tcx.sess.emit_fatal(errors::InvalidWindowsSubsystem { subsystem });
17df50a5
XL
811 }
812 subsystem.to_string()
813 });
814
136023e0
XL
815 // This list is used when generating the command line to pass through to
816 // system linker. The linker expects undefined symbols on the left of the
817 // command line to be defined in libraries on the right, not the other way
818 // around. For more info, see some comments in the add_used_library function
819 // below.
820 //
821 // In order to get this left-to-right dependency ordering, we use the reverse
822 // postorder of all crates putting the leaves at the right-most positions.
487cf647
FG
823 let mut compiler_builtins = None;
824 let mut used_crates: Vec<_> = tcx
136023e0
XL
825 .postorder_cnums(())
826 .iter()
827 .rev()
828 .copied()
487cf647
FG
829 .filter(|&cnum| {
830 let link = !tcx.dep_kind(cnum).macros_only();
831 if link && tcx.is_compiler_builtins(cnum) {
832 compiler_builtins = Some(cnum);
833 return false;
834 }
835 link
836 })
136023e0 837 .collect();
487cf647
FG
838 // `compiler_builtins` are always placed last to ensure that they're linked correctly.
839 used_crates.extend(compiler_builtins);
136023e0 840
a1dfa0c6 841 let mut info = CrateInfo {
136023e0
XL
842 target_cpu,
843 exported_symbols,
04454e1e 844 linked_symbols,
17df50a5 845 local_crate_name,
487cf647 846 compiler_builtins,
a1dfa0c6 847 profiler_runtime: None,
a1dfa0c6
XL
848 is_no_builtins: Default::default(),
849 native_libraries: Default::default(),
fc512014 850 used_libraries: tcx.native_libraries(LOCAL_CRATE).iter().map(Into::into).collect(),
a1dfa0c6 851 crate_name: Default::default(),
136023e0 852 used_crates,
a1dfa0c6 853 used_crate_source: Default::default(),
5099ac24 854 dependency_formats: tcx.dependency_formats(()).clone(),
17df50a5 855 windows_subsystem,
923072b8 856 natvis_debugger_visualizers: Default::default(),
9ffffee4 857 feature_packed_bundled_libs: tcx.features().packed_bundled_libs,
a1dfa0c6 858 };
136023e0 859 let crates = tcx.crates(());
a1dfa0c6
XL
860
861 let n_crates = crates.len();
862 info.native_libraries.reserve(n_crates);
863 info.crate_name.reserve(n_crates);
864 info.used_crate_source.reserve(n_crates);
a1dfa0c6
XL
865
866 for &cnum in crates.iter() {
fc512014
XL
867 info.native_libraries
868 .insert(cnum, tcx.native_libraries(cnum).iter().map(Into::into).collect());
04454e1e
FG
869 info.crate_name.insert(cnum, tcx.crate_name(cnum));
870
871 let used_crate_source = tcx.used_crate_source(cnum);
872 info.used_crate_source.insert(cnum, used_crate_source.clone());
a1dfa0c6
XL
873 if tcx.is_profiler_runtime(cnum) {
874 info.profiler_runtime = Some(cnum);
875 }
a1dfa0c6
XL
876 if tcx.is_no_builtins(cnum) {
877 info.is_no_builtins.insert(cnum);
878 }
f2b60f7d 879 }
a1dfa0c6 880
f2b60f7d
FG
881 // Handle circular dependencies in the standard library.
882 // See comment before `add_linked_symbol_object` function for the details.
883 // If global LTO is enabled then almost everything (*) is glued into a single object file,
884 // so this logic is not necessary and can cause issues on some targets (due to weak lang
885 // item symbols being "privatized" to that object file), so we disable it.
886 // (*) Native libs, and `#[compiler_builtins]` and `#[no_builtins]` crates are not glued,
887 // and we assume that they cannot define weak lang items. This is not currently enforced
888 // by the compiler, but that's ok because all this stuff is unstable anyway.
889 let target = &tcx.sess.target;
890 if !are_upstream_rust_objects_already_included(tcx.sess) {
487cf647 891 let missing_weak_lang_items: FxHashSet<Symbol> = info
f2b60f7d
FG
892 .used_crates
893 .iter()
487cf647
FG
894 .flat_map(|&cnum| tcx.missing_lang_items(cnum))
895 .filter(|l| l.is_weak())
896 .filter_map(|&l| {
897 let name = l.link_name()?;
898 lang_items::required(tcx, l).then_some(name)
f2b60f7d
FG
899 })
900 .collect();
901 let prefix = if target.is_like_windows && target.arch == "x86" { "_" } else { "" };
902 info.linked_symbols
903 .iter_mut()
904 .filter(|(crate_type, _)| {
905 !matches!(crate_type, CrateType::Rlib | CrateType::Staticlib)
906 })
907 .for_each(|(_, linked_symbols)| {
908 linked_symbols.extend(
909 missing_weak_lang_items
910 .iter()
911 .map(|item| (format!("{prefix}{item}"), SymbolExportKind::Text)),
49aad941
FG
912 );
913 if tcx.allocator_kind(()).is_some() {
914 // At least one crate needs a global allocator. This crate may be placed
915 // after the crate that defines it in the linker order, in which case some
916 // linkers return an error. By adding the global allocator shim methods to
917 // the linked_symbols list, linking the generated symbols.o will ensure that
918 // circular dependencies involving the global allocator don't lead to linker
919 // errors.
920 linked_symbols.extend(ALLOCATOR_METHODS.iter().map(|method| {
921 (
922 format!("{prefix}{}", global_fn_name(method.name).as_str()),
923 SymbolExportKind::Text,
924 )
925 }));
926 }
f2b60f7d 927 });
923072b8 928 }
04454e1e 929
923072b8
FG
930 let embed_visualizers = tcx.sess.crate_types().iter().any(|&crate_type| match crate_type {
931 CrateType::Executable | CrateType::Dylib | CrateType::Cdylib => {
932 // These are crate types for which we invoke the linker and can embed
933 // NatVis visualizers.
934 true
935 }
936 CrateType::ProcMacro => {
937 // We could embed NatVis for proc macro crates too (to improve the debugging
938 // experience for them) but it does not seem like a good default, since
939 // this is a rare use case and we don't want to slow down the common case.
940 false
04454e1e 941 }
923072b8
FG
942 CrateType::Staticlib | CrateType::Rlib => {
943 // We don't invoke the linker for these, so we don't need to collect the NatVis for them.
944 false
945 }
946 });
947
f2b60f7d 948 if target.is_like_msvc && embed_visualizers {
923072b8
FG
949 info.natvis_debugger_visualizers =
950 collect_debugger_visualizers_transitive(tcx, DebuggerVisualizerType::Natvis);
a1dfa0c6
XL
951 }
952
ba9703b0 953 info
a1dfa0c6 954 }
a1dfa0c6
XL
955}
956
5869c6ff 957pub fn provide(providers: &mut Providers) {
9fa01778
XL
958 providers.backend_optimization_level = |tcx, cratenum| {
959 let for_speed = match tcx.sess.opts.optimize {
960 // If globally no optimisation is done, #[optimize] has no effect.
961 //
962 // This is done because if we ended up "upgrading" to `-O2` here, we’d populate the
963 // pass manager and it is likely that some module-wide passes (such as inliner or
964 // cross-function constant propagation) would ignore the `optnone` annotation we put
965 // on the functions, thus necessarily involving these functions into optimisations.
966 config::OptLevel::No => return config::OptLevel::No,
967 // If globally optimise-speed is already specified, just use that level.
968 config::OptLevel::Less => return config::OptLevel::Less,
969 config::OptLevel::Default => return config::OptLevel::Default,
970 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
971 // If globally optimize-for-size has been requested, use -O2 instead (if optimize(size)
972 // are present).
973 config::OptLevel::Size => config::OptLevel::Default,
974 config::OptLevel::SizeMin => config::OptLevel::Default,
975 };
976
977 let (defids, _) = tcx.collect_and_partition_mono_items(cratenum);
9c376795
FG
978
979 let any_for_speed = defids.items().any(|id| {
dfeec247 980 let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
9fa01778 981 match optimize {
9c376795
FG
982 attr::OptimizeAttr::None | attr::OptimizeAttr::Size => false,
983 attr::OptimizeAttr::Speed => true,
9fa01778 984 }
9c376795
FG
985 });
986
987 if any_for_speed {
988 return for_speed;
9fa01778 989 }
9c376795 990
ba9703b0 991 tcx.sess.opts.optimize
9fa01778 992 };
a1dfa0c6
XL
993}
994
dc9dc135 995fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
a1dfa0c6 996 if !tcx.dep_graph.is_fully_enabled() {
dfeec247 997 return CguReuse::No;
a1dfa0c6
XL
998 }
999
1000 let work_product_id = &cgu.work_product_id();
1001 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
1002 // We don't have anything cached for this CGU. This can happen
1003 // if the CGU did not exist in the previous session.
dfeec247 1004 return CguReuse::No;
a1dfa0c6
XL
1005 }
1006
1007 // Try to mark the CGU as green. If it we can do so, it means that nothing
1008 // affecting the LLVM module has changed and we can re-use a cached version.
1009 // If we compile with any kind of LTO, this means we can re-use the bitcode
1010 // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
1011 // know that later). If we are not doing LTO, there is only one optimized
1012 // version of each module, so we re-use that.
1013 let dep_node = cgu.codegen_dep_node(tcx);
dfeec247
XL
1014 assert!(
1015 !tcx.dep_graph.dep_node_exists(&dep_node),
a1dfa0c6 1016 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
dfeec247
XL
1017 cgu.name()
1018 );
a1dfa0c6 1019
6a06907d 1020 if tcx.try_mark_green(&dep_node) {
f9f354fc
XL
1021 // We can re-use either the pre- or the post-thinlto state. If no LTO is
1022 // being performed then we can use post-LTO artifacts, otherwise we must
1023 // reuse pre-LTO artifacts
1024 match compute_per_cgu_lto_type(
1025 &tcx.sess.lto(),
1026 &tcx.sess.opts,
1027 &tcx.sess.crate_types(),
1028 ModuleKind::Regular,
1029 ) {
1030 ComputedLtoType::No => CguReuse::PostLto,
1031 _ => CguReuse::PreLto,
1032 }
a1dfa0c6
XL
1033 } else {
1034 CguReuse::No
1035 }
1036}