]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/base.rs
Auto merge of #77954 - JohnTitor:rollup-bpoy497, r=JohnTitor
[rust.git] / compiler / rustc_codegen_ssa / src / base.rs
1 //! Codegen the completed AST to the LLVM IR.
2 //!
3 //! Some functions here, such as `codegen_block` and `codegen_expr`, return a value --
4 //! the result of the codegen to LLVM -- while others, such as `codegen_fn`
5 //! and `mono_item`, are called only for the side effect of adding a
6 //! particular definition to the LLVM IR output we're producing.
7 //!
8 //! Hopefully useful general knowledge about codegen:
9 //!
10 //! * There's no way to find out the `Ty` type of a `Value`. Doing so
11 //!   would be "trying to get the eggs out of an omelette" (credit:
12 //!   pcwalton). You can, instead, find out its `llvm::Type` by calling `val_ty`,
13 //!   but one `llvm::Type` corresponds to many `Ty`s; for instance, `tup(int, int,
14 //!   int)` and `rec(x=int, y=int, z=int)` will have the same `llvm::Type`.
15
16 use crate::back::write::{
17     compute_per_cgu_lto_type, start_async_codegen, submit_codegened_module_to_llvm,
18     submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, ComputedLtoType, OngoingCodegen,
19 };
20 use crate::common::{IntPredicate, RealPredicate, TypeKind};
21 use crate::meth;
22 use crate::mir;
23 use crate::mir::operand::OperandValue;
24 use crate::mir::place::PlaceRef;
25 use crate::traits::*;
26 use crate::{CachedModuleCodegen, CrateInfo, MemFlags, ModuleCodegen, ModuleKind};
27
28 use rustc_attr as attr;
29 use rustc_data_structures::fx::FxHashMap;
30 use rustc_data_structures::profiling::print_time_passes_entry;
31 use rustc_data_structures::sync::{par_iter, Lock, ParallelIterator};
32 use rustc_hir as hir;
33 use rustc_hir::def_id::{LocalDefId, LOCAL_CRATE};
34 use rustc_hir::lang_items::LangItem;
35 use rustc_index::vec::Idx;
36 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
37 use rustc_middle::middle::cstore::EncodedMetadata;
38 use rustc_middle::middle::cstore::{self, LinkagePreference};
39 use rustc_middle::middle::lang_items;
40 use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem};
41 use rustc_middle::ty::layout::{HasTyCtxt, TyAndLayout};
42 use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
43 use rustc_middle::ty::query::Providers;
44 use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
45 use rustc_session::cgu_reuse_tracker::CguReuse;
46 use rustc_session::config::{self, EntryFnType};
47 use rustc_session::utils::NativeLibKind;
48 use rustc_session::Session;
49 use rustc_span::Span;
50 use rustc_symbol_mangling::test as symbol_names_test;
51 use rustc_target::abi::{Align, LayoutOf, VariantIdx};
52
53 use std::cmp;
54 use std::ops::{Deref, DerefMut};
55 use std::time::{Duration, Instant};
56
57 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind, signed: bool) -> IntPredicate {
58     match op {
59         hir::BinOpKind::Eq => IntPredicate::IntEQ,
60         hir::BinOpKind::Ne => IntPredicate::IntNE,
61         hir::BinOpKind::Lt => {
62             if signed {
63                 IntPredicate::IntSLT
64             } else {
65                 IntPredicate::IntULT
66             }
67         }
68         hir::BinOpKind::Le => {
69             if signed {
70                 IntPredicate::IntSLE
71             } else {
72                 IntPredicate::IntULE
73             }
74         }
75         hir::BinOpKind::Gt => {
76             if signed {
77                 IntPredicate::IntSGT
78             } else {
79                 IntPredicate::IntUGT
80             }
81         }
82         hir::BinOpKind::Ge => {
83             if signed {
84                 IntPredicate::IntSGE
85             } else {
86                 IntPredicate::IntUGE
87             }
88         }
89         op => bug!(
90             "comparison_op_to_icmp_predicate: expected comparison operator, \
91              found {:?}",
92             op
93         ),
94     }
95 }
96
97 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> RealPredicate {
98     match op {
99         hir::BinOpKind::Eq => RealPredicate::RealOEQ,
100         hir::BinOpKind::Ne => RealPredicate::RealUNE,
101         hir::BinOpKind::Lt => RealPredicate::RealOLT,
102         hir::BinOpKind::Le => RealPredicate::RealOLE,
103         hir::BinOpKind::Gt => RealPredicate::RealOGT,
104         hir::BinOpKind::Ge => RealPredicate::RealOGE,
105         op => {
106             bug!(
107                 "comparison_op_to_fcmp_predicate: expected comparison operator, \
108                  found {:?}",
109                 op
110             );
111         }
112     }
113 }
114
115 pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
116     bx: &mut Bx,
117     lhs: Bx::Value,
118     rhs: Bx::Value,
119     t: Ty<'tcx>,
120     ret_ty: Bx::Type,
121     op: hir::BinOpKind,
122 ) -> Bx::Value {
123     let signed = match t.kind() {
124         ty::Float(_) => {
125             let cmp = bin_op_to_fcmp_predicate(op);
126             let cmp = bx.fcmp(cmp, lhs, rhs);
127             return bx.sext(cmp, ret_ty);
128         }
129         ty::Uint(_) => false,
130         ty::Int(_) => true,
131         _ => bug!("compare_simd_types: invalid SIMD type"),
132     };
133
134     let cmp = bin_op_to_icmp_predicate(op, signed);
135     let cmp = bx.icmp(cmp, lhs, rhs);
136     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
137     // to get the correctly sized type. This will compile to a single instruction
138     // once the IR is converted to assembly if the SIMD instruction is supported
139     // by the target architecture.
140     bx.sext(cmp, ret_ty)
141 }
142
143 /// Retrieves the information we are losing (making dynamic) in an unsizing
144 /// adjustment.
145 ///
146 /// The `old_info` argument is a bit odd. It is intended for use in an upcast,
147 /// where the new vtable for an object will be derived from the old one.
148 pub fn unsized_info<'tcx, Cx: CodegenMethods<'tcx>>(
149     cx: &Cx,
150     source: Ty<'tcx>,
151     target: Ty<'tcx>,
152     old_info: Option<Cx::Value>,
153 ) -> Cx::Value {
154     let (source, target) =
155         cx.tcx().struct_lockstep_tails_erasing_lifetimes(source, target, cx.param_env());
156     match (source.kind(), target.kind()) {
157         (&ty::Array(_, len), &ty::Slice(_)) => {
158             cx.const_usize(len.eval_usize(cx.tcx(), ty::ParamEnv::reveal_all()))
159         }
160         (&ty::Dynamic(..), &ty::Dynamic(..)) => {
161             // For now, upcasts are limited to changes in marker
162             // traits, and hence never actually require an actual
163             // change to the vtable.
164             old_info.expect("unsized_info: missing old info for trait upcast")
165         }
166         (_, &ty::Dynamic(ref data, ..)) => {
167             let vtable_ptr = cx.layout_of(cx.tcx().mk_mut_ptr(target)).field(cx, FAT_PTR_EXTRA);
168             cx.const_ptrcast(
169                 meth::get_vtable(cx, source, data.principal()),
170                 cx.backend_type(vtable_ptr),
171             )
172         }
173         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
174     }
175 }
176
177 /// Coerces `src` to `dst_ty`. `src_ty` must be a thin pointer.
178 pub fn unsize_thin_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
179     bx: &mut Bx,
180     src: Bx::Value,
181     src_ty: Ty<'tcx>,
182     dst_ty: Ty<'tcx>,
183 ) -> (Bx::Value, Bx::Value) {
184     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
185     match (src_ty.kind(), dst_ty.kind()) {
186         (&ty::Ref(_, a, _), &ty::Ref(_, b, _) | &ty::RawPtr(ty::TypeAndMut { ty: b, .. }))
187         | (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
188             assert!(bx.cx().type_is_sized(a));
189             let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
190             (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
191         }
192         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
193             assert_eq!(def_a, def_b);
194
195             let src_layout = bx.cx().layout_of(src_ty);
196             let dst_layout = bx.cx().layout_of(dst_ty);
197             let mut result = None;
198             for i in 0..src_layout.fields.count() {
199                 let src_f = src_layout.field(bx.cx(), i);
200                 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
201                 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
202                 if src_f.is_zst() {
203                     continue;
204                 }
205                 assert_eq!(src_layout.size, src_f.size);
206
207                 let dst_f = dst_layout.field(bx.cx(), i);
208                 assert_ne!(src_f.ty, dst_f.ty);
209                 assert_eq!(result, None);
210                 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
211             }
212             let (lldata, llextra) = result.unwrap();
213             // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
214             // FIXME(eddyb) move these out of this `match` arm, so they're always
215             // applied, uniformly, no matter the source/destination types.
216             (
217                 bx.bitcast(lldata, bx.cx().scalar_pair_element_backend_type(dst_layout, 0, true)),
218                 bx.bitcast(llextra, bx.cx().scalar_pair_element_backend_type(dst_layout, 1, true)),
219             )
220         }
221         _ => bug!("unsize_thin_ptr: called on bad types"),
222     }
223 }
224
225 /// Coerces `src`, which is a reference to a value of type `src_ty`,
226 /// to a value of type `dst_ty`, and stores the result in `dst`.
227 pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
228     bx: &mut Bx,
229     src: PlaceRef<'tcx, Bx::Value>,
230     dst: PlaceRef<'tcx, Bx::Value>,
231 ) {
232     let src_ty = src.layout.ty;
233     let dst_ty = dst.layout.ty;
234     match (src_ty.kind(), dst_ty.kind()) {
235         (&ty::Ref(..), &ty::Ref(..) | &ty::RawPtr(..)) | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
236             let (base, info) = match bx.load_operand(src).val {
237                 OperandValue::Pair(base, info) => {
238                     // fat-ptr to fat-ptr unsize preserves the vtable
239                     // i.e., &'a fmt::Debug+Send => &'a fmt::Debug
240                     // So we need to pointercast the base to ensure
241                     // the types match up.
242                     // FIXME(eddyb) use `scalar_pair_element_backend_type` here,
243                     // like `unsize_thin_ptr` does.
244                     let thin_ptr = dst.layout.field(bx.cx(), FAT_PTR_ADDR);
245                     (bx.pointercast(base, bx.cx().backend_type(thin_ptr)), info)
246                 }
247                 OperandValue::Immediate(base) => unsize_thin_ptr(bx, base, src_ty, dst_ty),
248                 OperandValue::Ref(..) => bug!(),
249             };
250             OperandValue::Pair(base, info).store(bx, dst);
251         }
252
253         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
254             assert_eq!(def_a, def_b);
255
256             for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
257                 let src_f = src.project_field(bx, i);
258                 let dst_f = dst.project_field(bx, i);
259
260                 if dst_f.layout.is_zst() {
261                     continue;
262                 }
263
264                 if src_f.layout.ty == dst_f.layout.ty {
265                     memcpy_ty(
266                         bx,
267                         dst_f.llval,
268                         dst_f.align,
269                         src_f.llval,
270                         src_f.align,
271                         src_f.layout,
272                         MemFlags::empty(),
273                     );
274                 } else {
275                     coerce_unsized_into(bx, src_f, dst_f);
276                 }
277             }
278         }
279         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
280     }
281 }
282
283 pub fn cast_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
284     bx: &mut Bx,
285     op: hir::BinOpKind,
286     lhs: Bx::Value,
287     rhs: Bx::Value,
288 ) -> Bx::Value {
289     cast_shift_rhs(bx, op, lhs, rhs)
290 }
291
292 fn cast_shift_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
293     bx: &mut Bx,
294     op: hir::BinOpKind,
295     lhs: Bx::Value,
296     rhs: Bx::Value,
297 ) -> Bx::Value {
298     // Shifts may have any size int on the rhs
299     if op.is_shift() {
300         let mut rhs_llty = bx.cx().val_ty(rhs);
301         let mut lhs_llty = bx.cx().val_ty(lhs);
302         if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
303             rhs_llty = bx.cx().element_type(rhs_llty)
304         }
305         if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
306             lhs_llty = bx.cx().element_type(lhs_llty)
307         }
308         let rhs_sz = bx.cx().int_width(rhs_llty);
309         let lhs_sz = bx.cx().int_width(lhs_llty);
310         if lhs_sz < rhs_sz {
311             bx.trunc(rhs, lhs_llty)
312         } else if lhs_sz > rhs_sz {
313             // FIXME (#1877: If in the future shifting by negative
314             // values is no longer undefined then this is wrong.
315             bx.zext(rhs, lhs_llty)
316         } else {
317             rhs
318         }
319     } else {
320         rhs
321     }
322 }
323
324 /// Returns `true` if this session's target will use SEH-based unwinding.
325 ///
326 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
327 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
328 /// 64-bit MinGW) instead of "full SEH".
329 pub fn wants_msvc_seh(sess: &Session) -> bool {
330     sess.target.target.options.is_like_msvc
331 }
332
333 pub fn memcpy_ty<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
334     bx: &mut Bx,
335     dst: Bx::Value,
336     dst_align: Align,
337     src: Bx::Value,
338     src_align: Align,
339     layout: TyAndLayout<'tcx>,
340     flags: MemFlags,
341 ) {
342     let size = layout.size.bytes();
343     if size == 0 {
344         return;
345     }
346
347     bx.memcpy(dst, dst_align, src, src_align, bx.cx().const_usize(size), flags);
348 }
349
350 pub fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
351     cx: &'a Bx::CodegenCx,
352     instance: Instance<'tcx>,
353 ) {
354     // this is an info! to allow collecting monomorphization statistics
355     // and to allow finding the last function before LLVM aborts from
356     // release builds.
357     info!("codegen_instance({})", instance);
358
359     mir::codegen_mir::<Bx>(cx, instance);
360 }
361
362 /// Creates the `main` function which will initialize the rust runtime and call
363 /// users main function.
364 pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
365     cx: &'a Bx::CodegenCx,
366 ) -> Option<Bx::Function> {
367     let (main_def_id, span) = match cx.tcx().entry_fn(LOCAL_CRATE) {
368         Some((def_id, _)) => (def_id, cx.tcx().def_span(def_id)),
369         None => return None,
370     };
371
372     let instance = Instance::mono(cx.tcx(), main_def_id.to_def_id());
373
374     if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
375         // We want to create the wrapper in the same codegen unit as Rust's main
376         // function.
377         return None;
378     }
379
380     let main_llfn = cx.get_fn_addr(instance);
381
382     return cx.tcx().entry_fn(LOCAL_CRATE).map(|(_, et)| {
383         let use_start_lang_item = EntryFnType::Start != et;
384         create_entry_fn::<Bx>(cx, span, main_llfn, main_def_id, use_start_lang_item)
385     });
386
387     fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
388         cx: &'a Bx::CodegenCx,
389         sp: Span,
390         rust_main: Bx::Value,
391         rust_main_def_id: LocalDefId,
392         use_start_lang_item: bool,
393     ) -> Bx::Function {
394         // The entry function is either `int main(void)` or `int main(int argc, char **argv)`,
395         // depending on whether the target needs `argc` and `argv` to be passed in.
396         let llfty = if cx.sess().target.target.options.main_needs_argc_argv {
397             cx.type_func(&[cx.type_int(), cx.type_ptr_to(cx.type_i8p())], cx.type_int())
398         } else {
399             cx.type_func(&[], cx.type_int())
400         };
401
402         let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).output();
403         // Given that `main()` has no arguments,
404         // then its return type cannot have
405         // late-bound regions, since late-bound
406         // regions must appear in the argument
407         // listing.
408         let main_ret_ty = cx.tcx().erase_regions(&main_ret_ty.no_bound_vars().unwrap());
409
410         let llfn = match cx.declare_c_main(llfty) {
411             Some(llfn) => llfn,
412             None => {
413                 // FIXME: We should be smart and show a better diagnostic here.
414                 cx.sess()
415                     .struct_span_err(sp, "entry symbol `main` declared multiple times")
416                     .help("did you use `#[no_mangle]` on `fn main`? Use `#[start]` instead")
417                     .emit();
418                 cx.sess().abort_if_errors();
419                 bug!();
420             }
421         };
422
423         // `main` should respect same config for frame pointer elimination as rest of code
424         cx.set_frame_pointer_elimination(llfn);
425         cx.apply_target_cpu_attr(llfn);
426
427         let mut bx = Bx::new_block(&cx, llfn, "top");
428
429         bx.insert_reference_to_gdb_debug_scripts_section_global();
430
431         let (arg_argc, arg_argv) = get_argc_argv(cx, &mut bx);
432
433         let (start_fn, args) = if use_start_lang_item {
434             let start_def_id = cx.tcx().require_lang_item(LangItem::Start, None);
435             let start_fn = cx.get_fn_addr(
436                 ty::Instance::resolve(
437                     cx.tcx(),
438                     ty::ParamEnv::reveal_all(),
439                     start_def_id,
440                     cx.tcx().intern_substs(&[main_ret_ty.into()]),
441                 )
442                 .unwrap()
443                 .unwrap(),
444             );
445             (
446                 start_fn,
447                 vec![bx.pointercast(rust_main, cx.type_ptr_to(cx.type_i8p())), arg_argc, arg_argv],
448             )
449         } else {
450             debug!("using user-defined start fn");
451             (rust_main, vec![arg_argc, arg_argv])
452         };
453
454         let result = bx.call(start_fn, &args, None);
455         let cast = bx.intcast(result, cx.type_int(), true);
456         bx.ret(cast);
457
458         llfn
459     }
460 }
461
462 /// Obtain the `argc` and `argv` values to pass to the rust start function.
463 fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
464     cx: &'a Bx::CodegenCx,
465     bx: &mut Bx,
466 ) -> (Bx::Value, Bx::Value) {
467     if cx.sess().target.target.options.main_needs_argc_argv {
468         // Params from native `main()` used as args for rust start function
469         let param_argc = bx.get_param(0);
470         let param_argv = bx.get_param(1);
471         let arg_argc = bx.intcast(param_argc, cx.type_isize(), true);
472         let arg_argv = param_argv;
473         (arg_argc, arg_argv)
474     } else {
475         // The Rust start function doesn't need `argc` and `argv`, so just pass zeros.
476         let arg_argc = bx.const_int(cx.type_int(), 0);
477         let arg_argv = bx.const_null(cx.type_ptr_to(cx.type_i8p()));
478         (arg_argc, arg_argv)
479     }
480 }
481
482 pub fn codegen_crate<B: ExtraBackendMethods>(
483     backend: B,
484     tcx: TyCtxt<'tcx>,
485     metadata: EncodedMetadata,
486     need_metadata_module: bool,
487 ) -> OngoingCodegen<B> {
488     // Skip crate items and just output metadata in -Z no-codegen mode.
489     if tcx.sess.opts.debugging_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
490         let ongoing_codegen = start_async_codegen(backend, tcx, metadata, 1);
491
492         ongoing_codegen.codegen_finished(tcx);
493
494         finalize_tcx(tcx);
495
496         ongoing_codegen.check_for_errors(tcx.sess);
497
498         return ongoing_codegen;
499     }
500
501     let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
502
503     // Run the monomorphization collector and partition the collected items into
504     // codegen units.
505     let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
506
507     // Force all codegen_unit queries so they are already either red or green
508     // when compile_codegen_unit accesses them. We are not able to re-execute
509     // the codegen_unit query from just the DepNode, so an unknown color would
510     // lead to having to re-execute compile_codegen_unit, possibly
511     // unnecessarily.
512     if tcx.dep_graph.is_fully_enabled() {
513         for cgu in codegen_units {
514             tcx.ensure().codegen_unit(cgu.name());
515         }
516     }
517
518     let ongoing_codegen = start_async_codegen(backend.clone(), tcx, metadata, codegen_units.len());
519     let ongoing_codegen = AbortCodegenOnDrop::<B>(Some(ongoing_codegen));
520
521     // Codegen an allocator shim, if necessary.
522     //
523     // If the crate doesn't have an `allocator_kind` set then there's definitely
524     // no shim to generate. Otherwise we also check our dependency graph for all
525     // our output crate types. If anything there looks like its a `Dynamic`
526     // linkage, then it's already got an allocator shim and we'll be using that
527     // one instead. If nothing exists then it's our job to generate the
528     // allocator!
529     let any_dynamic_crate = tcx.dependency_formats(LOCAL_CRATE).iter().any(|(_, list)| {
530         use rustc_middle::middle::dependency_format::Linkage;
531         list.iter().any(|&linkage| linkage == Linkage::Dynamic)
532     });
533     let allocator_module = if any_dynamic_crate {
534         None
535     } else if let Some(kind) = tcx.allocator_kind() {
536         let llmod_id =
537             cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
538         let mut modules = backend.new_metadata(tcx, &llmod_id);
539         tcx.sess.time("write_allocator_module", || {
540             backend.codegen_allocator(tcx, &mut modules, kind, tcx.lang_items().oom().is_some())
541         });
542
543         Some(ModuleCodegen { name: llmod_id, module_llvm: modules, kind: ModuleKind::Allocator })
544     } else {
545         None
546     };
547
548     if let Some(allocator_module) = allocator_module {
549         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
550     }
551
552     if need_metadata_module {
553         // Codegen the encoded metadata.
554         let metadata_cgu_name =
555             cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
556         let mut metadata_llvm_module = backend.new_metadata(tcx, &metadata_cgu_name);
557         tcx.sess.time("write_compressed_metadata", || {
558             backend.write_compressed_metadata(
559                 tcx,
560                 &ongoing_codegen.metadata,
561                 &mut metadata_llvm_module,
562             );
563         });
564
565         let metadata_module = ModuleCodegen {
566             name: metadata_cgu_name,
567             module_llvm: metadata_llvm_module,
568             kind: ModuleKind::Metadata,
569         };
570         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
571     }
572
573     // We sort the codegen units by size. This way we can schedule work for LLVM
574     // a bit more efficiently.
575     let codegen_units = {
576         let mut codegen_units = codegen_units.iter().collect::<Vec<_>>();
577         codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
578         codegen_units
579     };
580
581     let total_codegen_time = Lock::new(Duration::new(0, 0));
582
583     // The non-parallel compiler can only translate codegen units to LLVM IR
584     // on a single thread, leading to a staircase effect where the N LLVM
585     // threads have to wait on the single codegen threads to generate work
586     // for them. The parallel compiler does not have this restriction, so
587     // we can pre-load the LLVM queue in parallel before handing off
588     // coordination to the OnGoingCodegen scheduler.
589     //
590     // This likely is a temporary measure. Once we don't have to support the
591     // non-parallel compiler anymore, we can compile CGUs end-to-end in
592     // parallel and get rid of the complicated scheduling logic.
593     let pre_compile_cgus = |cgu_reuse: &[CguReuse]| {
594         if cfg!(parallel_compiler) {
595             tcx.sess.time("compile_first_CGU_batch", || {
596                 // Try to find one CGU to compile per thread.
597                 let cgus: Vec<_> = cgu_reuse
598                     .iter()
599                     .enumerate()
600                     .filter(|&(_, reuse)| reuse == &CguReuse::No)
601                     .take(tcx.sess.threads())
602                     .collect();
603
604                 // Compile the found CGUs in parallel.
605                 par_iter(cgus)
606                     .map(|(i, _)| {
607                         let start_time = Instant::now();
608                         let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
609                         let mut time = total_codegen_time.lock();
610                         *time += start_time.elapsed();
611                         (i, module)
612                     })
613                     .collect()
614             })
615         } else {
616             FxHashMap::default()
617         }
618     };
619
620     let mut cgu_reuse = Vec::new();
621     let mut pre_compiled_cgus: Option<FxHashMap<usize, _>> = None;
622
623     for (i, cgu) in codegen_units.iter().enumerate() {
624         ongoing_codegen.wait_for_signal_to_codegen_item();
625         ongoing_codegen.check_for_errors(tcx.sess);
626
627         // Do some setup work in the first iteration
628         if pre_compiled_cgus.is_none() {
629             // Calculate the CGU reuse
630             cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
631                 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, &cgu)).collect()
632             });
633             // Pre compile some CGUs
634             pre_compiled_cgus = Some(pre_compile_cgus(&cgu_reuse));
635         }
636
637         let cgu_reuse = cgu_reuse[i];
638         tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
639
640         match cgu_reuse {
641             CguReuse::No => {
642                 let (module, cost) =
643                     if let Some(cgu) = pre_compiled_cgus.as_mut().unwrap().remove(&i) {
644                         cgu
645                     } else {
646                         let start_time = Instant::now();
647                         let module = backend.compile_codegen_unit(tcx, cgu.name());
648                         let mut time = total_codegen_time.lock();
649                         *time += start_time.elapsed();
650                         module
651                     };
652                 submit_codegened_module_to_llvm(
653                     &backend,
654                     &ongoing_codegen.coordinator_send,
655                     module,
656                     cost,
657                 );
658                 false
659             }
660             CguReuse::PreLto => {
661                 submit_pre_lto_module_to_llvm(
662                     &backend,
663                     tcx,
664                     &ongoing_codegen.coordinator_send,
665                     CachedModuleCodegen {
666                         name: cgu.name().to_string(),
667                         source: cgu.work_product(tcx),
668                     },
669                 );
670                 true
671             }
672             CguReuse::PostLto => {
673                 submit_post_lto_module_to_llvm(
674                     &backend,
675                     &ongoing_codegen.coordinator_send,
676                     CachedModuleCodegen {
677                         name: cgu.name().to_string(),
678                         source: cgu.work_product(tcx),
679                     },
680                 );
681                 true
682             }
683         };
684     }
685
686     ongoing_codegen.codegen_finished(tcx);
687
688     // Since the main thread is sometimes blocked during codegen, we keep track
689     // -Ztime-passes output manually.
690     print_time_passes_entry(
691         tcx.sess.time_passes(),
692         "codegen_to_LLVM_IR",
693         total_codegen_time.into_inner(),
694     );
695
696     rustc_incremental::assert_module_sources::assert_module_sources(tcx);
697
698     symbol_names_test::report_symbol_names(tcx);
699
700     ongoing_codegen.check_for_errors(tcx.sess);
701
702     finalize_tcx(tcx);
703
704     ongoing_codegen.into_inner()
705 }
706
707 /// A curious wrapper structure whose only purpose is to call `codegen_aborted`
708 /// when it's dropped abnormally.
709 ///
710 /// In the process of working on rust-lang/rust#55238 a mysterious segfault was
711 /// stumbled upon. The segfault was never reproduced locally, but it was
712 /// suspected to be related to the fact that codegen worker threads were
713 /// sticking around by the time the main thread was exiting, causing issues.
714 ///
715 /// This structure is an attempt to fix that issue where the `codegen_aborted`
716 /// message will block until all workers have finished. This should ensure that
717 /// even if the main codegen thread panics we'll wait for pending work to
718 /// complete before returning from the main thread, hopefully avoiding
719 /// segfaults.
720 ///
721 /// If you see this comment in the code, then it means that this workaround
722 /// worked! We may yet one day track down the mysterious cause of that
723 /// segfault...
724 struct AbortCodegenOnDrop<B: ExtraBackendMethods>(Option<OngoingCodegen<B>>);
725
726 impl<B: ExtraBackendMethods> AbortCodegenOnDrop<B> {
727     fn into_inner(mut self) -> OngoingCodegen<B> {
728         self.0.take().unwrap()
729     }
730 }
731
732 impl<B: ExtraBackendMethods> Deref for AbortCodegenOnDrop<B> {
733     type Target = OngoingCodegen<B>;
734
735     fn deref(&self) -> &OngoingCodegen<B> {
736         self.0.as_ref().unwrap()
737     }
738 }
739
740 impl<B: ExtraBackendMethods> DerefMut for AbortCodegenOnDrop<B> {
741     fn deref_mut(&mut self) -> &mut OngoingCodegen<B> {
742         self.0.as_mut().unwrap()
743     }
744 }
745
746 impl<B: ExtraBackendMethods> Drop for AbortCodegenOnDrop<B> {
747     fn drop(&mut self) {
748         if let Some(codegen) = self.0.take() {
749             codegen.codegen_aborted();
750         }
751     }
752 }
753
754 fn finalize_tcx(tcx: TyCtxt<'_>) {
755     tcx.sess.time("assert_dep_graph", || rustc_incremental::assert_dep_graph(tcx));
756     tcx.sess.time("serialize_dep_graph", || rustc_incremental::save_dep_graph(tcx));
757
758     // We assume that no queries are run past here. If there are new queries
759     // after this point, they'll show up as "<unknown>" in self-profiling data.
760     {
761         let _prof_timer = tcx.prof.generic_activity("self_profile_alloc_query_strings");
762         tcx.alloc_self_profile_query_strings();
763     }
764 }
765
766 impl CrateInfo {
767     pub fn new(tcx: TyCtxt<'_>) -> CrateInfo {
768         let mut info = CrateInfo {
769             panic_runtime: None,
770             compiler_builtins: None,
771             profiler_runtime: None,
772             is_no_builtins: Default::default(),
773             native_libraries: Default::default(),
774             used_libraries: tcx.native_libraries(LOCAL_CRATE),
775             link_args: tcx.link_args(LOCAL_CRATE),
776             crate_name: Default::default(),
777             used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
778             used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
779             used_crate_source: Default::default(),
780             lang_item_to_crate: Default::default(),
781             missing_lang_items: Default::default(),
782             dependency_formats: tcx.dependency_formats(LOCAL_CRATE),
783         };
784         let lang_items = tcx.lang_items();
785
786         let crates = tcx.crates();
787
788         let n_crates = crates.len();
789         info.native_libraries.reserve(n_crates);
790         info.crate_name.reserve(n_crates);
791         info.used_crate_source.reserve(n_crates);
792         info.missing_lang_items.reserve(n_crates);
793
794         for &cnum in crates.iter() {
795             info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
796             info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
797             info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
798             if tcx.is_panic_runtime(cnum) {
799                 info.panic_runtime = Some(cnum);
800             }
801             if tcx.is_compiler_builtins(cnum) {
802                 info.compiler_builtins = Some(cnum);
803             }
804             if tcx.is_profiler_runtime(cnum) {
805                 info.profiler_runtime = Some(cnum);
806             }
807             if tcx.is_no_builtins(cnum) {
808                 info.is_no_builtins.insert(cnum);
809             }
810             let missing = tcx.missing_lang_items(cnum);
811             for &item in missing.iter() {
812                 if let Ok(id) = lang_items.require(item) {
813                     info.lang_item_to_crate.insert(item, id.krate);
814                 }
815             }
816
817             // No need to look for lang items that don't actually need to exist.
818             let missing =
819                 missing.iter().cloned().filter(|&l| lang_items::required(tcx, l)).collect();
820             info.missing_lang_items.insert(cnum, missing);
821         }
822
823         info
824     }
825 }
826
827 pub fn provide_both(providers: &mut Providers) {
828     providers.backend_optimization_level = |tcx, cratenum| {
829         let for_speed = match tcx.sess.opts.optimize {
830             // If globally no optimisation is done, #[optimize] has no effect.
831             //
832             // This is done because if we ended up "upgrading" to `-O2` here, we’d populate the
833             // pass manager and it is likely that some module-wide passes (such as inliner or
834             // cross-function constant propagation) would ignore the `optnone` annotation we put
835             // on the functions, thus necessarily involving these functions into optimisations.
836             config::OptLevel::No => return config::OptLevel::No,
837             // If globally optimise-speed is already specified, just use that level.
838             config::OptLevel::Less => return config::OptLevel::Less,
839             config::OptLevel::Default => return config::OptLevel::Default,
840             config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
841             // If globally optimize-for-size has been requested, use -O2 instead (if optimize(size)
842             // are present).
843             config::OptLevel::Size => config::OptLevel::Default,
844             config::OptLevel::SizeMin => config::OptLevel::Default,
845         };
846
847         let (defids, _) = tcx.collect_and_partition_mono_items(cratenum);
848         for id in &*defids {
849             let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
850             match optimize {
851                 attr::OptimizeAttr::None => continue,
852                 attr::OptimizeAttr::Size => continue,
853                 attr::OptimizeAttr::Speed => {
854                     return for_speed;
855                 }
856             }
857         }
858         tcx.sess.opts.optimize
859     };
860
861     providers.dllimport_foreign_items = |tcx, krate| {
862         let module_map = tcx.foreign_modules(krate);
863         let module_map =
864             module_map.iter().map(|lib| (lib.def_id, lib)).collect::<FxHashMap<_, _>>();
865
866         let dllimports = tcx
867             .native_libraries(krate)
868             .iter()
869             .filter(|lib| {
870                 if !matches!(lib.kind, NativeLibKind::Dylib | NativeLibKind::Unspecified) {
871                     return false;
872                 }
873                 let cfg = match lib.cfg {
874                     Some(ref cfg) => cfg,
875                     None => return true,
876                 };
877                 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
878             })
879             .filter_map(|lib| lib.foreign_module)
880             .map(|id| &module_map[&id])
881             .flat_map(|module| module.foreign_items.iter().cloned())
882             .collect();
883         dllimports
884     };
885
886     providers.is_dllimport_foreign_item =
887         |tcx, def_id| tcx.dllimport_foreign_items(def_id.krate).contains(&def_id);
888 }
889
890 fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
891     if !tcx.dep_graph.is_fully_enabled() {
892         return CguReuse::No;
893     }
894
895     let work_product_id = &cgu.work_product_id();
896     if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
897         // We don't have anything cached for this CGU. This can happen
898         // if the CGU did not exist in the previous session.
899         return CguReuse::No;
900     }
901
902     // Try to mark the CGU as green. If it we can do so, it means that nothing
903     // affecting the LLVM module has changed and we can re-use a cached version.
904     // If we compile with any kind of LTO, this means we can re-use the bitcode
905     // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
906     // know that later). If we are not doing LTO, there is only one optimized
907     // version of each module, so we re-use that.
908     let dep_node = cgu.codegen_dep_node(tcx);
909     assert!(
910         !tcx.dep_graph.dep_node_exists(&dep_node),
911         "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
912         cgu.name()
913     );
914
915     if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
916         // We can re-use either the pre- or the post-thinlto state. If no LTO is
917         // being performed then we can use post-LTO artifacts, otherwise we must
918         // reuse pre-LTO artifacts
919         match compute_per_cgu_lto_type(
920             &tcx.sess.lto(),
921             &tcx.sess.opts,
922             &tcx.sess.crate_types(),
923             ModuleKind::Regular,
924         ) {
925             ComputedLtoType::No => CguReuse::PostLto,
926             _ => CguReuse::PreLto,
927         }
928     } else {
929         CguReuse::No
930     }
931 }