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