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