]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/base.rs
Auto merge of #54183 - qnighy:by-value-object-safety, r=oli-obk
[rust.git] / src / librustc_codegen_llvm / 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 super::ModuleLlvm;
27 use super::ModuleCodegen;
28 use super::ModuleKind;
29 use super::CachedModuleCodegen;
30
31 use abi;
32 use back::write::{self, OngoingCodegen};
33 use llvm::{self, TypeKind, get_param};
34 use metadata;
35 use rustc::dep_graph::cgu_reuse_tracker::CguReuse;
36 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
37 use rustc::middle::lang_items::StartFnLangItem;
38 use rustc::middle::weak_lang_items;
39 use rustc::mir::mono::{Linkage, Visibility, Stats, CodegenUnitNameBuilder};
40 use rustc::middle::cstore::{EncodedMetadata};
41 use rustc::ty::{self, Ty, TyCtxt};
42 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf};
43 use rustc::ty::query::Providers;
44 use rustc::middle::cstore::{self, LinkagePreference};
45 use rustc::middle::exported_symbols;
46 use rustc::util::common::{time, print_time_passes_entry};
47 use rustc::util::profiling::ProfileCategory;
48 use rustc::session::config::{self, DebugInfo, EntryFnType, Lto};
49 use rustc::session::Session;
50 use rustc_incremental;
51 use allocator;
52 use mir::place::PlaceRef;
53 use attributes;
54 use builder::{Builder, MemFlags};
55 use callee;
56 use common::{C_bool, C_bytes_in_context, C_i32, C_usize};
57 use rustc_mir::monomorphize::collector::{self, MonoItemCollectionMode};
58 use rustc_mir::monomorphize::item::DefPathBasedNames;
59 use common::{C_struct_in_context, C_array, val_ty};
60 use consts;
61 use context::CodegenCx;
62 use debuginfo;
63 use declare;
64 use meth;
65 use mir;
66 use monomorphize::Instance;
67 use monomorphize::partitioning::{self, PartitioningStrategy, CodegenUnit, CodegenUnitExt};
68 use rustc_codegen_utils::symbol_names_test;
69 use time_graph;
70 use mono_item::{MonoItem, BaseMonoItemExt, MonoItemExt};
71 use type_::Type;
72 use type_of::LayoutLlvmExt;
73 use rustc::util::nodemap::{FxHashMap, DefIdSet};
74 use CrateInfo;
75 use rustc_data_structures::small_c_str::SmallCStr;
76 use rustc_data_structures::sync::Lrc;
77
78 use std::any::Any;
79 use std::ffi::CString;
80 use std::sync::Arc;
81 use std::time::{Instant, Duration};
82 use std::i32;
83 use std::cmp;
84 use std::sync::mpsc;
85 use syntax_pos::Span;
86 use syntax_pos::symbol::InternedString;
87 use syntax::attr;
88 use rustc::hir::{self, CodegenFnAttrs};
89
90 use value::Value;
91
92 use mir::operand::OperandValue;
93
94 use rustc_codegen_utils::check_for_rustc_errors_attr;
95
96 pub struct StatRecorder<'a, 'll: 'a, 'tcx: 'll> {
97     cx: &'a CodegenCx<'ll, 'tcx>,
98     name: Option<String>,
99     istart: usize,
100 }
101
102 impl StatRecorder<'a, 'll, 'tcx> {
103     pub fn new(cx: &'a CodegenCx<'ll, 'tcx>, name: String) -> Self {
104         let istart = cx.stats.borrow().n_llvm_insns;
105         StatRecorder {
106             cx,
107             name: Some(name),
108             istart,
109         }
110     }
111 }
112
113 impl Drop for StatRecorder<'a, 'll, 'tcx> {
114     fn drop(&mut self) {
115         if self.cx.sess().codegen_stats() {
116             let mut stats = self.cx.stats.borrow_mut();
117             let iend = stats.n_llvm_insns;
118             stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
119             stats.n_fns += 1;
120             // Reset LLVM insn count to avoid compound costs.
121             stats.n_llvm_insns = self.istart;
122         }
123     }
124 }
125
126 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind,
127                                 signed: bool)
128                                 -> llvm::IntPredicate {
129     match op {
130         hir::BinOpKind::Eq => llvm::IntEQ,
131         hir::BinOpKind::Ne => llvm::IntNE,
132         hir::BinOpKind::Lt => if signed { llvm::IntSLT } else { llvm::IntULT },
133         hir::BinOpKind::Le => if signed { llvm::IntSLE } else { llvm::IntULE },
134         hir::BinOpKind::Gt => if signed { llvm::IntSGT } else { llvm::IntUGT },
135         hir::BinOpKind::Ge => if signed { llvm::IntSGE } else { llvm::IntUGE },
136         op => {
137             bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
138                   found {:?}",
139                  op)
140         }
141     }
142 }
143
144 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> llvm::RealPredicate {
145     match op {
146         hir::BinOpKind::Eq => llvm::RealOEQ,
147         hir::BinOpKind::Ne => llvm::RealUNE,
148         hir::BinOpKind::Lt => llvm::RealOLT,
149         hir::BinOpKind::Le => llvm::RealOLE,
150         hir::BinOpKind::Gt => llvm::RealOGT,
151         hir::BinOpKind::Ge => llvm::RealOGE,
152         op => {
153             bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
154                   found {:?}",
155                  op);
156         }
157     }
158 }
159
160 pub fn compare_simd_types(
161     bx: &Builder<'a, 'll, 'tcx>,
162     lhs: &'ll Value,
163     rhs: &'ll Value,
164     t: Ty<'tcx>,
165     ret_ty: &'ll Type,
166     op: hir::BinOpKind
167 ) -> &'ll Value {
168     let signed = match t.sty {
169         ty::Float(_) => {
170             let cmp = bin_op_to_fcmp_predicate(op);
171             return bx.sext(bx.fcmp(cmp, lhs, rhs), ret_ty);
172         },
173         ty::Uint(_) => false,
174         ty::Int(_) => true,
175         _ => bug!("compare_simd_types: invalid SIMD type"),
176     };
177
178     let cmp = bin_op_to_icmp_predicate(op, signed);
179     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
180     // to get the correctly sized type. This will compile to a single instruction
181     // once the IR is converted to assembly if the SIMD instruction is supported
182     // by the target architecture.
183     bx.sext(bx.icmp(cmp, lhs, rhs), ret_ty)
184 }
185
186 /// Retrieve the information we are losing (making dynamic) in an unsizing
187 /// adjustment.
188 ///
189 /// The `old_info` argument is a bit funny. It is intended for use
190 /// in an upcast, where the new vtable for an object will be derived
191 /// from the old one.
192 pub fn unsized_info(
193     cx: &CodegenCx<'ll, 'tcx>,
194     source: Ty<'tcx>,
195     target: Ty<'tcx>,
196     old_info: Option<&'ll Value>,
197 ) -> &'ll Value {
198     let (source, target) = cx.tcx.struct_lockstep_tails(source, target);
199     match (&source.sty, &target.sty) {
200         (&ty::Array(_, len), &ty::Slice(_)) => {
201             C_usize(cx, len.unwrap_usize(cx.tcx))
202         }
203         (&ty::Dynamic(..), &ty::Dynamic(..)) => {
204             // For now, upcasts are limited to changes in marker
205             // traits, and hence never actually require an actual
206             // change to the vtable.
207             old_info.expect("unsized_info: missing old info for trait upcast")
208         }
209         (_, &ty::Dynamic(ref data, ..)) => {
210             let vtable_ptr = cx.layout_of(cx.tcx.mk_mut_ptr(target))
211                 .field(cx, abi::FAT_PTR_EXTRA);
212             consts::ptrcast(meth::get_vtable(cx, source, data.principal()),
213                             vtable_ptr.llvm_type(cx))
214         }
215         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
216                   source,
217                   target),
218     }
219 }
220
221 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
222 pub fn unsize_thin_ptr(
223     bx: &Builder<'a, 'll, 'tcx>,
224     src: &'ll Value,
225     src_ty: Ty<'tcx>,
226     dst_ty: Ty<'tcx>
227 ) -> (&'ll Value, &'ll Value) {
228     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
229     match (&src_ty.sty, &dst_ty.sty) {
230         (&ty::Ref(_, a, _),
231          &ty::Ref(_, b, _)) |
232         (&ty::Ref(_, a, _),
233          &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) |
234         (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }),
235          &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
236             assert!(bx.cx.type_is_sized(a));
237             let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
238             (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
239         }
240         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
241             let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
242             assert!(bx.cx.type_is_sized(a));
243             let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
244             (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
245         }
246         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
247             assert_eq!(def_a, def_b);
248
249             let src_layout = bx.cx.layout_of(src_ty);
250             let dst_layout = bx.cx.layout_of(dst_ty);
251             let mut result = None;
252             for i in 0..src_layout.fields.count() {
253                 let src_f = src_layout.field(bx.cx, i);
254                 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
255                 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
256                 if src_f.is_zst() {
257                     continue;
258                 }
259                 assert_eq!(src_layout.size, src_f.size);
260
261                 let dst_f = dst_layout.field(bx.cx, i);
262                 assert_ne!(src_f.ty, dst_f.ty);
263                 assert_eq!(result, None);
264                 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
265             }
266             let (lldata, llextra) = result.unwrap();
267             // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
268             (bx.bitcast(lldata, dst_layout.scalar_pair_element_llvm_type(bx.cx, 0, true)),
269              bx.bitcast(llextra, dst_layout.scalar_pair_element_llvm_type(bx.cx, 1, true)))
270         }
271         _ => bug!("unsize_thin_ptr: called on bad types"),
272     }
273 }
274
275 /// Coerce `src`, which is a reference to a value of type `src_ty`,
276 /// to a value of type `dst_ty` and store the result in `dst`
277 pub fn coerce_unsized_into(
278     bx: &Builder<'a, 'll, 'tcx>,
279     src: PlaceRef<'ll, 'tcx>,
280     dst: PlaceRef<'ll, 'tcx>
281 ) {
282     let src_ty = src.layout.ty;
283     let dst_ty = dst.layout.ty;
284     let coerce_ptr = || {
285         let (base, info) = match src.load(bx).val {
286             OperandValue::Pair(base, info) => {
287                 // fat-ptr to fat-ptr unsize preserves the vtable
288                 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
289                 // So we need to pointercast the base to ensure
290                 // the types match up.
291                 let thin_ptr = dst.layout.field(bx.cx, abi::FAT_PTR_ADDR);
292                 (bx.pointercast(base, thin_ptr.llvm_type(bx.cx)), info)
293             }
294             OperandValue::Immediate(base) => {
295                 unsize_thin_ptr(bx, base, src_ty, dst_ty)
296             }
297             OperandValue::Ref(..) => bug!()
298         };
299         OperandValue::Pair(base, info).store(bx, dst);
300     };
301     match (&src_ty.sty, &dst_ty.sty) {
302         (&ty::Ref(..), &ty::Ref(..)) |
303         (&ty::Ref(..), &ty::RawPtr(..)) |
304         (&ty::RawPtr(..), &ty::RawPtr(..)) => {
305             coerce_ptr()
306         }
307         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
308             coerce_ptr()
309         }
310
311         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
312             assert_eq!(def_a, def_b);
313
314             for i in 0..def_a.variants[0].fields.len() {
315                 let src_f = src.project_field(bx, i);
316                 let dst_f = dst.project_field(bx, i);
317
318                 if dst_f.layout.is_zst() {
319                     continue;
320                 }
321
322                 if src_f.layout.ty == dst_f.layout.ty {
323                     memcpy_ty(bx, dst_f.llval, src_f.llval, src_f.layout,
324                               src_f.align.min(dst_f.align), MemFlags::empty());
325                 } else {
326                     coerce_unsized_into(bx, src_f, dst_f);
327                 }
328             }
329         }
330         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
331                   src_ty,
332                   dst_ty),
333     }
334 }
335
336 pub fn cast_shift_expr_rhs(
337     cx: &Builder<'_, 'll, '_>, op: hir::BinOpKind, lhs: &'ll Value, rhs: &'ll Value
338 ) -> &'ll Value {
339     cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
340 }
341
342 fn cast_shift_rhs<'ll, F, G>(op: hir::BinOpKind,
343                              lhs: &'ll Value,
344                              rhs: &'ll Value,
345                              trunc: F,
346                              zext: G)
347                              -> &'ll Value
348     where F: FnOnce(&'ll Value, &'ll Type) -> &'ll Value,
349           G: FnOnce(&'ll Value, &'ll Type) -> &'ll Value
350 {
351     // Shifts may have any size int on the rhs
352     if op.is_shift() {
353         let mut rhs_llty = val_ty(rhs);
354         let mut lhs_llty = val_ty(lhs);
355         if rhs_llty.kind() == TypeKind::Vector {
356             rhs_llty = rhs_llty.element_type()
357         }
358         if lhs_llty.kind() == TypeKind::Vector {
359             lhs_llty = lhs_llty.element_type()
360         }
361         let rhs_sz = rhs_llty.int_width();
362         let lhs_sz = lhs_llty.int_width();
363         if lhs_sz < rhs_sz {
364             trunc(rhs, lhs_llty)
365         } else if lhs_sz > rhs_sz {
366             // FIXME (#1877: If in the future shifting by negative
367             // values is no longer undefined then this is wrong.
368             zext(rhs, lhs_llty)
369         } else {
370             rhs
371         }
372     } else {
373         rhs
374     }
375 }
376
377 /// Returns whether this session's target will use SEH-based unwinding.
378 ///
379 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
380 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
381 /// 64-bit MinGW) instead of "full SEH".
382 pub fn wants_msvc_seh(sess: &Session) -> bool {
383     sess.target.target.options.is_like_msvc
384 }
385
386 pub fn call_assume(bx: &Builder<'_, 'll, '_>, val: &'ll Value) {
387     let assume_intrinsic = bx.cx.get_intrinsic("llvm.assume");
388     bx.call(assume_intrinsic, &[val], None);
389 }
390
391 pub fn from_immediate(bx: &Builder<'_, 'll, '_>, val: &'ll Value) -> &'ll Value {
392     if val_ty(val) == Type::i1(bx.cx) {
393         bx.zext(val, Type::i8(bx.cx))
394     } else {
395         val
396     }
397 }
398
399 pub fn to_immediate(
400     bx: &Builder<'_, 'll, '_>,
401     val: &'ll Value,
402     layout: layout::TyLayout,
403 ) -> &'ll Value {
404     if let layout::Abi::Scalar(ref scalar) = layout.abi {
405         return to_immediate_scalar(bx, val, scalar);
406     }
407     val
408 }
409
410 pub fn to_immediate_scalar(
411     bx: &Builder<'_, 'll, '_>,
412     val: &'ll Value,
413     scalar: &layout::Scalar,
414 ) -> &'ll Value {
415     if scalar.is_bool() {
416         return bx.trunc(val, Type::i1(bx.cx));
417     }
418     val
419 }
420
421 pub fn call_memcpy(
422     bx: &Builder<'_, 'll, '_>,
423     dst: &'ll Value,
424     src: &'ll Value,
425     n_bytes: &'ll Value,
426     align: Align,
427     flags: MemFlags,
428 ) {
429     if flags.contains(MemFlags::NONTEMPORAL) {
430         // HACK(nox): This is inefficient but there is no nontemporal memcpy.
431         let val = bx.load(src, align);
432         let ptr = bx.pointercast(dst, val_ty(val).ptr_to());
433         bx.store_with_flags(val, ptr, align, flags);
434         return;
435     }
436     let cx = bx.cx;
437     let ptr_width = &cx.sess().target.target.target_pointer_width;
438     let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
439     let memcpy = cx.get_intrinsic(&key);
440     let src_ptr = bx.pointercast(src, Type::i8p(cx));
441     let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
442     let size = bx.intcast(n_bytes, cx.isize_ty, false);
443     let align = C_i32(cx, align.abi() as i32);
444     let volatile = C_bool(cx, flags.contains(MemFlags::VOLATILE));
445     bx.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
446 }
447
448 pub fn memcpy_ty(
449     bx: &Builder<'_, 'll, 'tcx>,
450     dst: &'ll Value,
451     src: &'ll Value,
452     layout: TyLayout<'tcx>,
453     align: Align,
454     flags: MemFlags,
455 ) {
456     let size = layout.size.bytes();
457     if size == 0 {
458         return;
459     }
460
461     call_memcpy(bx, dst, src, C_usize(bx.cx, size), align, flags);
462 }
463
464 pub fn call_memset(
465     bx: &Builder<'_, 'll, '_>,
466     ptr: &'ll Value,
467     fill_byte: &'ll Value,
468     size: &'ll Value,
469     align: &'ll Value,
470     volatile: bool,
471 ) -> &'ll Value {
472     let ptr_width = &bx.cx.sess().target.target.target_pointer_width;
473     let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
474     let llintrinsicfn = bx.cx.get_intrinsic(&intrinsic_key);
475     let volatile = C_bool(bx.cx, volatile);
476     bx.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
477 }
478
479 pub fn codegen_instance<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, instance: Instance<'tcx>) {
480     let _s = if cx.sess().codegen_stats() {
481         let mut instance_name = String::new();
482         DefPathBasedNames::new(cx.tcx, true, true)
483             .push_def_path(instance.def_id(), &mut instance_name);
484         Some(StatRecorder::new(cx, instance_name))
485     } else {
486         None
487     };
488
489     // this is an info! to allow collecting monomorphization statistics
490     // and to allow finding the last function before LLVM aborts from
491     // release builds.
492     info!("codegen_instance({})", instance);
493
494     let sig = instance.fn_sig(cx.tcx);
495     let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
496
497     let lldecl = cx.instances.borrow().get(&instance).cloned().unwrap_or_else(||
498         bug!("Instance `{:?}` not already declared", instance));
499
500     cx.stats.borrow_mut().n_closures += 1;
501
502     let mir = cx.tcx.instance_mir(instance.def);
503     mir::codegen_mir(cx, lldecl, &mir, instance, sig);
504 }
505
506 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
507     let sect = match attrs.link_section {
508         Some(name) => name,
509         None => return,
510     };
511     unsafe {
512         let buf = SmallCStr::new(&sect.as_str());
513         llvm::LLVMSetSection(llval, buf.as_ptr());
514     }
515 }
516
517 /// Create the `main` function which will initialize the rust runtime and call
518 /// users main function.
519 fn maybe_create_entry_wrapper(cx: &CodegenCx) {
520     let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
521         Some((id, span, _)) => {
522             (cx.tcx.hir.local_def_id(id), span)
523         }
524         None => return,
525     };
526
527     let instance = Instance::mono(cx.tcx, main_def_id);
528
529     if !cx.codegen_unit.contains_item(&MonoItem::Fn(instance)) {
530         // We want to create the wrapper in the same codegen unit as Rust's main
531         // function.
532         return;
533     }
534
535     let main_llfn = callee::get_fn(cx, instance);
536
537     let et = cx.sess().entry_fn.get().map(|e| e.2);
538     match et {
539         Some(EntryFnType::Main) => create_entry_fn(cx, span, main_llfn, main_def_id, true),
540         Some(EntryFnType::Start) => create_entry_fn(cx, span, main_llfn, main_def_id, false),
541         None => {}    // Do nothing.
542     }
543
544     fn create_entry_fn(
545         cx: &CodegenCx<'ll, '_>,
546         sp: Span,
547         rust_main: &'ll Value,
548         rust_main_def_id: DefId,
549         use_start_lang_item: bool,
550     ) {
551         let llfty = Type::func(&[Type::c_int(cx), Type::i8p(cx).ptr_to()], Type::c_int(cx));
552
553         let main_ret_ty = cx.tcx.fn_sig(rust_main_def_id).output();
554         // Given that `main()` has no arguments,
555         // then its return type cannot have
556         // late-bound regions, since late-bound
557         // regions must appear in the argument
558         // listing.
559         let main_ret_ty = cx.tcx.erase_regions(
560             &main_ret_ty.no_late_bound_regions().unwrap(),
561         );
562
563         if declare::get_defined_value(cx, "main").is_some() {
564             // FIXME: We should be smart and show a better diagnostic here.
565             cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
566                      .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
567                      .emit();
568             cx.sess().abort_if_errors();
569             bug!();
570         }
571         let llfn = declare::declare_cfn(cx, "main", llfty);
572
573         // `main` should respect same config for frame pointer elimination as rest of code
574         attributes::set_frame_pointer_elimination(cx, llfn);
575         attributes::apply_target_cpu_attr(cx, llfn);
576
577         let bx = Builder::new_block(cx, llfn, "top");
578
579         debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(&bx);
580
581         // Params from native main() used as args for rust start function
582         let param_argc = get_param(llfn, 0);
583         let param_argv = get_param(llfn, 1);
584         let arg_argc = bx.intcast(param_argc, cx.isize_ty, true);
585         let arg_argv = param_argv;
586
587         let (start_fn, args) = if use_start_lang_item {
588             let start_def_id = cx.tcx.require_lang_item(StartFnLangItem);
589             let start_fn = callee::resolve_and_get_fn(
590                 cx,
591                 start_def_id,
592                 cx.tcx.intern_substs(&[main_ret_ty.into()]),
593             );
594             (start_fn, vec![bx.pointercast(rust_main, Type::i8p(cx).ptr_to()),
595                             arg_argc, arg_argv])
596         } else {
597             debug!("using user-defined start fn");
598             (rust_main, vec![arg_argc, arg_argv])
599         };
600
601         let result = bx.call(start_fn, &args, None);
602         bx.ret(bx.intcast(result, Type::c_int(cx), true));
603     }
604 }
605
606 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
607                             llvm_module: &ModuleLlvm)
608                             -> EncodedMetadata {
609     use std::io::Write;
610     use flate2::Compression;
611     use flate2::write::DeflateEncoder;
612
613     let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
614
615     #[derive(PartialEq, Eq, PartialOrd, Ord)]
616     enum MetadataKind {
617         None,
618         Uncompressed,
619         Compressed
620     }
621
622     let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
623         match *ty {
624             config::CrateType::Executable |
625             config::CrateType::Staticlib |
626             config::CrateType::Cdylib => MetadataKind::None,
627
628             config::CrateType::Rlib => MetadataKind::Uncompressed,
629
630             config::CrateType::Dylib |
631             config::CrateType::ProcMacro => MetadataKind::Compressed,
632         }
633     }).max().unwrap_or(MetadataKind::None);
634
635     if kind == MetadataKind::None {
636         return EncodedMetadata::new();
637     }
638
639     let metadata = tcx.encode_metadata();
640     if kind == MetadataKind::Uncompressed {
641         return metadata;
642     }
643
644     assert!(kind == MetadataKind::Compressed);
645     let mut compressed = tcx.metadata_encoding_version();
646     DeflateEncoder::new(&mut compressed, Compression::fast())
647         .write_all(&metadata.raw_data).unwrap();
648
649     let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
650     let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
651     let name = exported_symbols::metadata_symbol_name(tcx);
652     let buf = CString::new(name).unwrap();
653     let llglobal = unsafe {
654         llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst), buf.as_ptr())
655     };
656     unsafe {
657         llvm::LLVMSetInitializer(llglobal, llconst);
658         let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
659         let name = SmallCStr::new(section_name);
660         llvm::LLVMSetSection(llglobal, name.as_ptr());
661
662         // Also generate a .section directive to force no
663         // flags, at least for ELF outputs, so that the
664         // metadata doesn't get loaded into memory.
665         let directive = format!(".section {}", section_name);
666         let directive = CString::new(directive).unwrap();
667         llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
668     }
669     return metadata;
670 }
671
672 pub struct ValueIter<'ll> {
673     cur: Option<&'ll Value>,
674     step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
675 }
676
677 impl Iterator for ValueIter<'ll> {
678     type Item = &'ll Value;
679
680     fn next(&mut self) -> Option<&'ll Value> {
681         let old = self.cur;
682         if let Some(old) = old {
683             self.cur = unsafe { (self.step)(old) };
684         }
685         old
686     }
687 }
688
689 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
690     unsafe {
691         ValueIter {
692             cur: llvm::LLVMGetFirstGlobal(llmod),
693             step: llvm::LLVMGetNextGlobal,
694         }
695     }
696 }
697
698 fn determine_cgu_reuse<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
699                                  cgu: &CodegenUnit<'tcx>)
700                                  -> CguReuse {
701     if !tcx.dep_graph.is_fully_enabled() {
702         return CguReuse::No
703     }
704
705     let work_product_id = &cgu.work_product_id();
706     if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
707         // We don't have anything cached for this CGU. This can happen
708         // if the CGU did not exist in the previous session.
709         return CguReuse::No
710     }
711
712     // Try to mark the CGU as green. If it we can do so, it means that nothing
713     // affecting the LLVM module has changed and we can re-use a cached version.
714     // If we compile with any kind of LTO, this means we can re-use the bitcode
715     // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
716     // know that later). If we are not doing LTO, there is only one optimized
717     // version of each module, so we re-use that.
718     let dep_node = cgu.codegen_dep_node(tcx);
719     assert!(!tcx.dep_graph.dep_node_exists(&dep_node),
720         "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
721         cgu.name());
722
723     if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
724         // We can re-use either the pre- or the post-thinlto state
725         if tcx.sess.lto() != Lto::No {
726             CguReuse::PreLto
727         } else {
728             CguReuse::PostLto
729         }
730     } else {
731         CguReuse::No
732     }
733 }
734
735 pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
736                                rx: mpsc::Receiver<Box<dyn Any + Send>>)
737                                -> OngoingCodegen
738 {
739     check_for_rustc_errors_attr(tcx);
740
741     if let Some(true) = tcx.sess.opts.debugging_opts.thinlto {
742         if unsafe { !llvm::LLVMRustThinLTOAvailable() } {
743             tcx.sess.fatal("this compiler's LLVM does not support ThinLTO");
744         }
745     }
746
747     if (tcx.sess.opts.debugging_opts.pgo_gen.is_some() ||
748         !tcx.sess.opts.debugging_opts.pgo_use.is_empty()) &&
749         unsafe { !llvm::LLVMRustPGOAvailable() }
750     {
751         tcx.sess.fatal("this compiler's LLVM does not support PGO");
752     }
753
754     let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
755
756     // Codegen the metadata.
757     tcx.sess.profiler(|p| p.start_activity(ProfileCategory::Codegen));
758
759     let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
760                                                             &["crate"],
761                                                             Some("metadata")).as_str()
762                                                                              .to_string();
763     let metadata_llvm_module = ModuleLlvm::new(tcx.sess, &metadata_cgu_name);
764     let metadata = time(tcx.sess, "write metadata", || {
765         write_metadata(tcx, &metadata_llvm_module)
766     });
767     tcx.sess.profiler(|p| p.end_activity(ProfileCategory::Codegen));
768
769     let metadata_module = ModuleCodegen {
770         name: metadata_cgu_name,
771         module_llvm: metadata_llvm_module,
772         kind: ModuleKind::Metadata,
773     };
774
775     let time_graph = if tcx.sess.opts.debugging_opts.codegen_time_graph {
776         Some(time_graph::TimeGraph::new())
777     } else {
778         None
779     };
780
781     // Skip crate items and just output metadata in -Z no-codegen mode.
782     if tcx.sess.opts.debugging_opts.no_codegen ||
783        !tcx.sess.opts.output_types.should_codegen() {
784         let ongoing_codegen = write::start_async_codegen(
785             tcx,
786             time_graph,
787             metadata,
788             rx,
789             1);
790
791         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
792         ongoing_codegen.codegen_finished(tcx);
793
794         assert_and_save_dep_graph(tcx);
795
796         ongoing_codegen.check_for_errors(tcx.sess);
797
798         return ongoing_codegen;
799     }
800
801     // Run the monomorphization collector and partition the collected items into
802     // codegen units.
803     let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
804     let codegen_units = (*codegen_units).clone();
805
806     // Force all codegen_unit queries so they are already either red or green
807     // when compile_codegen_unit accesses them. We are not able to re-execute
808     // the codegen_unit query from just the DepNode, so an unknown color would
809     // lead to having to re-execute compile_codegen_unit, possibly
810     // unnecessarily.
811     if tcx.dep_graph.is_fully_enabled() {
812         for cgu in &codegen_units {
813             tcx.codegen_unit(cgu.name().clone());
814         }
815     }
816
817     let ongoing_codegen = write::start_async_codegen(
818         tcx,
819         time_graph.clone(),
820         metadata,
821         rx,
822         codegen_units.len());
823
824     // Codegen an allocator shim, if necessary.
825     //
826     // If the crate doesn't have an `allocator_kind` set then there's definitely
827     // no shim to generate. Otherwise we also check our dependency graph for all
828     // our output crate types. If anything there looks like its a `Dynamic`
829     // linkage, then it's already got an allocator shim and we'll be using that
830     // one instead. If nothing exists then it's our job to generate the
831     // allocator!
832     let any_dynamic_crate = tcx.sess.dependency_formats.borrow()
833         .iter()
834         .any(|(_, list)| {
835             use rustc::middle::dependency_format::Linkage;
836             list.iter().any(|&linkage| linkage == Linkage::Dynamic)
837         });
838     let allocator_module = if any_dynamic_crate {
839         None
840     } else if let Some(kind) = *tcx.sess.allocator_kind.get() {
841         let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
842                                                        &["crate"],
843                                                        Some("allocator")).as_str()
844                                                                          .to_string();
845         let modules = ModuleLlvm::new(tcx.sess, &llmod_id);
846         time(tcx.sess, "write allocator module", || {
847             unsafe {
848                 allocator::codegen(tcx, &modules, kind)
849             }
850         });
851
852         Some(ModuleCodegen {
853             name: llmod_id,
854             module_llvm: modules,
855             kind: ModuleKind::Allocator,
856         })
857     } else {
858         None
859     };
860
861     if let Some(allocator_module) = allocator_module {
862         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
863     }
864
865     ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
866
867     // We sort the codegen units by size. This way we can schedule work for LLVM
868     // a bit more efficiently.
869     let codegen_units = {
870         let mut codegen_units = codegen_units;
871         codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
872         codegen_units
873     };
874
875     let mut total_codegen_time = Duration::new(0, 0);
876     let mut all_stats = Stats::default();
877
878     for cgu in codegen_units.into_iter() {
879         ongoing_codegen.wait_for_signal_to_codegen_item();
880         ongoing_codegen.check_for_errors(tcx.sess);
881
882         let cgu_reuse = determine_cgu_reuse(tcx, &cgu);
883         tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
884
885         match cgu_reuse {
886             CguReuse::No => {
887                 let _timing_guard = time_graph.as_ref().map(|time_graph| {
888                     time_graph.start(write::CODEGEN_WORKER_TIMELINE,
889                                      write::CODEGEN_WORK_PACKAGE_KIND,
890                                      &format!("codegen {}", cgu.name()))
891                 });
892                 let start_time = Instant::now();
893                 let stats = compile_codegen_unit(tcx, *cgu.name());
894                 all_stats.extend(stats);
895                 total_codegen_time += start_time.elapsed();
896                 false
897             }
898             CguReuse::PreLto => {
899                 write::submit_pre_lto_module_to_llvm(tcx, CachedModuleCodegen {
900                     name: cgu.name().to_string(),
901                     source: cgu.work_product(tcx),
902                 });
903                 true
904             }
905             CguReuse::PostLto => {
906                 write::submit_post_lto_module_to_llvm(tcx, CachedModuleCodegen {
907                     name: cgu.name().to_string(),
908                     source: cgu.work_product(tcx),
909                 });
910                 true
911             }
912         };
913     }
914
915     ongoing_codegen.codegen_finished(tcx);
916
917     // Since the main thread is sometimes blocked during codegen, we keep track
918     // -Ztime-passes output manually.
919     print_time_passes_entry(tcx.sess.time_passes(),
920                             "codegen to LLVM IR",
921                             total_codegen_time);
922
923     rustc_incremental::assert_module_sources::assert_module_sources(tcx);
924
925     symbol_names_test::report_symbol_names(tcx);
926
927     if tcx.sess.codegen_stats() {
928         println!("--- codegen stats ---");
929         println!("n_glues_created: {}", all_stats.n_glues_created);
930         println!("n_null_glues: {}", all_stats.n_null_glues);
931         println!("n_real_glues: {}", all_stats.n_real_glues);
932
933         println!("n_fns: {}", all_stats.n_fns);
934         println!("n_inlines: {}", all_stats.n_inlines);
935         println!("n_closures: {}", all_stats.n_closures);
936         println!("fn stats:");
937         all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
938         for &(ref name, insns) in all_stats.fn_stats.iter() {
939             println!("{} insns, {}", insns, *name);
940         }
941     }
942
943     if tcx.sess.count_llvm_insns() {
944         for (k, v) in all_stats.llvm_insns.iter() {
945             println!("{:7} {}", *v, *k);
946         }
947     }
948
949     ongoing_codegen.check_for_errors(tcx.sess);
950
951     assert_and_save_dep_graph(tcx);
952     ongoing_codegen
953 }
954
955 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
956     time(tcx.sess,
957          "assert dep graph",
958          || rustc_incremental::assert_dep_graph(tcx));
959
960     time(tcx.sess,
961          "serialize dep graph",
962          || rustc_incremental::save_dep_graph(tcx));
963 }
964
965 fn collect_and_partition_mono_items<'a, 'tcx>(
966     tcx: TyCtxt<'a, 'tcx, 'tcx>,
967     cnum: CrateNum,
968 ) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
969 {
970     assert_eq!(cnum, LOCAL_CRATE);
971
972     let collection_mode = match tcx.sess.opts.debugging_opts.print_mono_items {
973         Some(ref s) => {
974             let mode_string = s.to_lowercase();
975             let mode_string = mode_string.trim();
976             if mode_string == "eager" {
977                 MonoItemCollectionMode::Eager
978             } else {
979                 if mode_string != "lazy" {
980                     let message = format!("Unknown codegen-item collection mode '{}'. \
981                                            Falling back to 'lazy' mode.",
982                                           mode_string);
983                     tcx.sess.warn(&message);
984                 }
985
986                 MonoItemCollectionMode::Lazy
987             }
988         }
989         None => {
990             if tcx.sess.opts.cg.link_dead_code {
991                 MonoItemCollectionMode::Eager
992             } else {
993                 MonoItemCollectionMode::Lazy
994             }
995         }
996     };
997
998     let (items, inlining_map) =
999         time(tcx.sess, "monomorphization collection", || {
1000             collector::collect_crate_mono_items(tcx, collection_mode)
1001     });
1002
1003     tcx.sess.abort_if_errors();
1004
1005     ::rustc_mir::monomorphize::assert_symbols_are_distinct(tcx, items.iter());
1006
1007     let strategy = if tcx.sess.opts.incremental.is_some() {
1008         PartitioningStrategy::PerModule
1009     } else {
1010         PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
1011     };
1012
1013     let codegen_units = time(tcx.sess, "codegen unit partitioning", || {
1014         partitioning::partition(tcx,
1015                                 items.iter().cloned(),
1016                                 strategy,
1017                                 &inlining_map)
1018             .into_iter()
1019             .map(Arc::new)
1020             .collect::<Vec<_>>()
1021     });
1022
1023     let mono_items: DefIdSet = items.iter().filter_map(|mono_item| {
1024         match *mono_item {
1025             MonoItem::Fn(ref instance) => Some(instance.def_id()),
1026             MonoItem::Static(def_id) => Some(def_id),
1027             _ => None,
1028         }
1029     }).collect();
1030
1031     if tcx.sess.opts.debugging_opts.print_mono_items.is_some() {
1032         let mut item_to_cgus: FxHashMap<_, Vec<_>> = Default::default();
1033
1034         for cgu in &codegen_units {
1035             for (&mono_item, &linkage) in cgu.items() {
1036                 item_to_cgus.entry(mono_item)
1037                             .or_default()
1038                             .push((cgu.name().clone(), linkage));
1039             }
1040         }
1041
1042         let mut item_keys: Vec<_> = items
1043             .iter()
1044             .map(|i| {
1045                 let mut output = i.to_string(tcx);
1046                 output.push_str(" @@");
1047                 let mut empty = Vec::new();
1048                 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1049                 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1050                 cgus.dedup();
1051                 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1052                     output.push_str(" ");
1053                     output.push_str(&cgu_name.as_str());
1054
1055                     let linkage_abbrev = match linkage {
1056                         Linkage::External => "External",
1057                         Linkage::AvailableExternally => "Available",
1058                         Linkage::LinkOnceAny => "OnceAny",
1059                         Linkage::LinkOnceODR => "OnceODR",
1060                         Linkage::WeakAny => "WeakAny",
1061                         Linkage::WeakODR => "WeakODR",
1062                         Linkage::Appending => "Appending",
1063                         Linkage::Internal => "Internal",
1064                         Linkage::Private => "Private",
1065                         Linkage::ExternalWeak => "ExternalWeak",
1066                         Linkage::Common => "Common",
1067                     };
1068
1069                     output.push_str("[");
1070                     output.push_str(linkage_abbrev);
1071                     output.push_str("]");
1072                 }
1073                 output
1074             })
1075             .collect();
1076
1077         item_keys.sort();
1078
1079         for item in item_keys {
1080             println!("MONO_ITEM {}", item);
1081         }
1082     }
1083
1084     (Arc::new(mono_items), Arc::new(codegen_units))
1085 }
1086
1087 impl CrateInfo {
1088     pub fn new(tcx: TyCtxt) -> CrateInfo {
1089         let mut info = CrateInfo {
1090             panic_runtime: None,
1091             compiler_builtins: None,
1092             profiler_runtime: None,
1093             sanitizer_runtime: None,
1094             is_no_builtins: Default::default(),
1095             native_libraries: Default::default(),
1096             used_libraries: tcx.native_libraries(LOCAL_CRATE),
1097             link_args: tcx.link_args(LOCAL_CRATE),
1098             crate_name: Default::default(),
1099             used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1100             used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1101             used_crate_source: Default::default(),
1102             wasm_imports: Default::default(),
1103             lang_item_to_crate: Default::default(),
1104             missing_lang_items: Default::default(),
1105         };
1106         let lang_items = tcx.lang_items();
1107
1108         let load_wasm_items = tcx.sess.crate_types.borrow()
1109             .iter()
1110             .any(|c| *c != config::CrateType::Rlib) &&
1111             tcx.sess.opts.target_triple.triple() == "wasm32-unknown-unknown";
1112
1113         if load_wasm_items {
1114             info.load_wasm_imports(tcx, LOCAL_CRATE);
1115         }
1116
1117         let crates = tcx.crates();
1118
1119         let n_crates = crates.len();
1120         info.native_libraries.reserve(n_crates);
1121         info.crate_name.reserve(n_crates);
1122         info.used_crate_source.reserve(n_crates);
1123         info.missing_lang_items.reserve(n_crates);
1124
1125         for &cnum in crates.iter() {
1126             info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1127             info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1128             info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1129             if tcx.is_panic_runtime(cnum) {
1130                 info.panic_runtime = Some(cnum);
1131             }
1132             if tcx.is_compiler_builtins(cnum) {
1133                 info.compiler_builtins = Some(cnum);
1134             }
1135             if tcx.is_profiler_runtime(cnum) {
1136                 info.profiler_runtime = Some(cnum);
1137             }
1138             if tcx.is_sanitizer_runtime(cnum) {
1139                 info.sanitizer_runtime = Some(cnum);
1140             }
1141             if tcx.is_no_builtins(cnum) {
1142                 info.is_no_builtins.insert(cnum);
1143             }
1144             if load_wasm_items {
1145                 info.load_wasm_imports(tcx, cnum);
1146             }
1147             let missing = tcx.missing_lang_items(cnum);
1148             for &item in missing.iter() {
1149                 if let Ok(id) = lang_items.require(item) {
1150                     info.lang_item_to_crate.insert(item, id.krate);
1151                 }
1152             }
1153
1154             // No need to look for lang items that are whitelisted and don't
1155             // actually need to exist.
1156             let missing = missing.iter()
1157                 .cloned()
1158                 .filter(|&l| !weak_lang_items::whitelisted(tcx, l))
1159                 .collect();
1160             info.missing_lang_items.insert(cnum, missing);
1161         }
1162
1163         return info
1164     }
1165
1166     fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
1167         self.wasm_imports.extend(tcx.wasm_import_module_map(cnum).iter().map(|(&id, module)| {
1168             let instance = Instance::mono(tcx, id);
1169             let import_name = tcx.symbol_name(instance);
1170
1171             (import_name.to_string(), module.clone())
1172         }));
1173     }
1174 }
1175
1176 fn is_codegened_item(tcx: TyCtxt, id: DefId) -> bool {
1177     let (all_mono_items, _) =
1178         tcx.collect_and_partition_mono_items(LOCAL_CRATE);
1179     all_mono_items.contains(&id)
1180 }
1181
1182 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1183                                   cgu_name: InternedString)
1184                                   -> Stats {
1185     let start_time = Instant::now();
1186
1187     let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
1188     let ((stats, module), _) = tcx.dep_graph.with_task(dep_node,
1189                                                        tcx,
1190                                                        cgu_name,
1191                                                        module_codegen);
1192     let time_to_codegen = start_time.elapsed();
1193
1194     // We assume that the cost to run LLVM on a CGU is proportional to
1195     // the time we needed for codegenning it.
1196     let cost = time_to_codegen.as_secs() * 1_000_000_000 +
1197                time_to_codegen.subsec_nanos() as u64;
1198
1199     write::submit_codegened_module_to_llvm(tcx,
1200                                            module,
1201                                            cost);
1202     return stats;
1203
1204     fn module_codegen<'a, 'tcx>(
1205         tcx: TyCtxt<'a, 'tcx, 'tcx>,
1206         cgu_name: InternedString)
1207         -> (Stats, ModuleCodegen)
1208     {
1209         let cgu = tcx.codegen_unit(cgu_name);
1210
1211         // Instantiate monomorphizations without filling out definitions yet...
1212         let llvm_module = ModuleLlvm::new(tcx.sess, &cgu_name.as_str());
1213         let stats = {
1214             let cx = CodegenCx::new(tcx, cgu, &llvm_module);
1215             let mono_items = cx.codegen_unit
1216                                .items_in_deterministic_order(cx.tcx);
1217             for &(mono_item, (linkage, visibility)) in &mono_items {
1218                 mono_item.predefine(&cx, linkage, visibility);
1219             }
1220
1221             // ... and now that we have everything pre-defined, fill out those definitions.
1222             for &(mono_item, _) in &mono_items {
1223                 mono_item.define(&cx);
1224             }
1225
1226             // If this codegen unit contains the main function, also create the
1227             // wrapper here
1228             maybe_create_entry_wrapper(&cx);
1229
1230             // Run replace-all-uses-with for statics that need it
1231             for &(old_g, new_g) in cx.statics_to_rauw.borrow().iter() {
1232                 unsafe {
1233                     let bitcast = llvm::LLVMConstPointerCast(new_g, val_ty(old_g));
1234                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1235                     llvm::LLVMDeleteGlobal(old_g);
1236                 }
1237             }
1238
1239             // Create the llvm.used variable
1240             // This variable has type [N x i8*] and is stored in the llvm.metadata section
1241             if !cx.used_statics.borrow().is_empty() {
1242                 let name = const_cstr!("llvm.used");
1243                 let section = const_cstr!("llvm.metadata");
1244                 let array = C_array(Type::i8(&cx).ptr_to(), &*cx.used_statics.borrow());
1245
1246                 unsafe {
1247                     let g = llvm::LLVMAddGlobal(cx.llmod,
1248                                                 val_ty(array),
1249                                                 name.as_ptr());
1250                     llvm::LLVMSetInitializer(g, array);
1251                     llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1252                     llvm::LLVMSetSection(g, section.as_ptr());
1253                 }
1254             }
1255
1256             // Finalize debuginfo
1257             if cx.sess().opts.debuginfo != DebugInfo::None {
1258                 debuginfo::finalize(&cx);
1259             }
1260
1261             cx.stats.into_inner()
1262         };
1263
1264         (stats, ModuleCodegen {
1265             name: cgu_name.to_string(),
1266             module_llvm: llvm_module,
1267             kind: ModuleKind::Regular,
1268         })
1269     }
1270 }
1271
1272 pub fn provide(providers: &mut Providers) {
1273     providers.collect_and_partition_mono_items =
1274         collect_and_partition_mono_items;
1275
1276     providers.is_codegened_item = is_codegened_item;
1277
1278     providers.codegen_unit = |tcx, name| {
1279         let (_, all) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
1280         all.iter()
1281             .find(|cgu| *cgu.name() == name)
1282             .cloned()
1283             .unwrap_or_else(|| panic!("failed to find cgu with name {:?}", name))
1284     };
1285
1286     provide_extern(providers);
1287 }
1288
1289 pub fn provide_extern(providers: &mut Providers) {
1290     providers.dllimport_foreign_items = |tcx, krate| {
1291         let module_map = tcx.foreign_modules(krate);
1292         let module_map = module_map.iter()
1293             .map(|lib| (lib.def_id, lib))
1294             .collect::<FxHashMap<_, _>>();
1295
1296         let dllimports = tcx.native_libraries(krate)
1297             .iter()
1298             .filter(|lib| {
1299                 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
1300                     return false
1301                 }
1302                 let cfg = match lib.cfg {
1303                     Some(ref cfg) => cfg,
1304                     None => return true,
1305                 };
1306                 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
1307             })
1308             .filter_map(|lib| lib.foreign_module)
1309             .map(|id| &module_map[&id])
1310             .flat_map(|module| module.foreign_items.iter().cloned())
1311             .collect();
1312         Lrc::new(dllimports)
1313     };
1314
1315     providers.is_dllimport_foreign_item = |tcx, def_id| {
1316         tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
1317     };
1318 }
1319
1320 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1321     match linkage {
1322         Linkage::External => llvm::Linkage::ExternalLinkage,
1323         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1324         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1325         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1326         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1327         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1328         Linkage::Appending => llvm::Linkage::AppendingLinkage,
1329         Linkage::Internal => llvm::Linkage::InternalLinkage,
1330         Linkage::Private => llvm::Linkage::PrivateLinkage,
1331         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1332         Linkage::Common => llvm::Linkage::CommonLinkage,
1333     }
1334 }
1335
1336 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1337     match linkage {
1338         Visibility::Default => llvm::Visibility::Default,
1339         Visibility::Hidden => llvm::Visibility::Hidden,
1340         Visibility::Protected => llvm::Visibility::Protected,
1341     }
1342 }
1343
1344 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1345 //            the HashStable trait. Normally DepGraph::with_task() calls are
1346 //            hidden behind queries, but CGU creation is a special case in two
1347 //            ways: (1) it's not a query and (2) CGU are output nodes, so their
1348 //            Fingerprints are not actually needed. It remains to be clarified
1349 //            how exactly this case will be handled in the red/green system but
1350 //            for now we content ourselves with providing a no-op HashStable
1351 //            implementation for CGUs.
1352 mod temp_stable_hash_impls {
1353     use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1354                                                HashStable};
1355     use ModuleCodegen;
1356
1357     impl<HCX> HashStable<HCX> for ModuleCodegen {
1358         fn hash_stable<W: StableHasherResult>(&self,
1359                                               _: &mut HCX,
1360                                               _: &mut StableHasher<W>) {
1361             // do nothing
1362         }
1363     }
1364 }