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