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