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