]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/base.rs
Normalize EntryFnType variants to standard style
[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::ModuleSource;
28 use super::ModuleCodegen;
29 use super::ModuleKind;
30
31 use abi;
32 use back::link;
33 use back::write::{self, OngoingCodegen};
34 use llvm::{self, TypeKind, get_param};
35 use metadata;
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};
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::dep_graph::{DepNode, DepConstructor};
45 use rustc::middle::cstore::{self, LinkMeta, LinkagePreference};
46 use rustc::middle::exported_symbols;
47 use rustc::util::common::{time, print_time_passes_entry};
48 use rustc::util::profiling::ProfileCategory;
49 use rustc::session::config::{self, NoDebugInfo, EntryFnType};
50 use rustc::session::Session;
51 use rustc_incremental;
52 use allocator;
53 use mir::place::PlaceRef;
54 use attributes;
55 use builder::{Builder, MemFlags};
56 use callee;
57 use common::{C_bool, C_bytes_in_context, C_i32, C_usize};
58 use rustc_mir::monomorphize::collector::{self, MonoItemCollectionMode};
59 use rustc_mir::monomorphize::item::DefPathBasedNames;
60 use common::{self, C_struct_in_context, C_array, val_ty};
61 use consts;
62 use context::CodegenCx;
63 use debuginfo;
64 use declare;
65 use meth;
66 use mir;
67 use monomorphize::Instance;
68 use monomorphize::partitioning::{self, PartitioningStrategy, CodegenUnit, CodegenUnitExt};
69 use rustc_codegen_utils::symbol_names_test;
70 use time_graph;
71 use mono_item::{MonoItem, BaseMonoItemExt, MonoItemExt};
72 use type_::Type;
73 use type_of::LayoutLlvmExt;
74 use rustc::util::nodemap::{FxHashMap, FxHashSet, DefIdSet};
75 use CrateInfo;
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::TyFloat(_) => {
170             let cmp = bin_op_to_fcmp_predicate(op);
171             return bx.sext(bx.fcmp(cmp, lhs, rhs), ret_ty);
172         },
173         ty::TyUint(_) => false,
174         ty::TyInt(_) => 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::TyArray(_, len), &ty::TySlice(_)) => {
201             C_usize(cx, len.unwrap_usize(cx.tcx))
202         }
203         (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
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::TyDynamic(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::TyRef(_, a, _),
231          &ty::TyRef(_, b, _)) |
232         (&ty::TyRef(_, a, _),
233          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
234         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
235          &ty::TyRawPtr(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::TyAdt(def_a, _), &ty::TyAdt(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::TyAdt(def_a, _), &ty::TyAdt(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::TyRef(..), &ty::TyRef(..)) |
303         (&ty::TyRef(..), &ty::TyRawPtr(..)) |
304         (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
305             coerce_ptr()
306         }
307         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
308             coerce_ptr()
309         }
310
311         (&ty::TyAdt(def_a, _), &ty::TyAdt(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 shifting by negative
367             // values becomes not 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 fn_ty = instance.ty(cx.tcx);
495     let sig = common::ty_fn_sig(cx, fn_ty);
496     let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
497
498     let lldecl = match cx.instances.borrow().get(&instance) {
499         Some(&val) => val,
500         None => bug!("Instance `{:?}` not already declared", instance)
501     };
502
503     cx.stats.borrow_mut().n_closures += 1;
504
505     // The `uwtable` attribute according to LLVM is:
506     //
507     //     This attribute indicates that the ABI being targeted requires that an
508     //     unwind table entry be produced for this function even if we can show
509     //     that no exceptions passes by it. This is normally the case for the
510     //     ELF x86-64 abi, but it can be disabled for some compilation units.
511     //
512     // Typically when we're compiling with `-C panic=abort` (which implies this
513     // `no_landing_pads` check) we don't need `uwtable` because we can't
514     // generate any exceptions! On Windows, however, exceptions include other
515     // events such as illegal instructions, segfaults, etc. This means that on
516     // Windows we end up still needing the `uwtable` attribute even if the `-C
517     // panic=abort` flag is passed.
518     //
519     // You can also find more info on why Windows is whitelisted here in:
520     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
521     if !cx.sess().no_landing_pads() ||
522        cx.sess().target.target.options.requires_uwtable {
523         attributes::emit_uwtable(lldecl, true);
524     }
525
526     let mir = cx.tcx.instance_mir(instance.def);
527     mir::codegen_mir(cx, lldecl, &mir, instance, sig);
528 }
529
530 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
531     let sect = match attrs.link_section {
532         Some(name) => name,
533         None => return,
534     };
535     unsafe {
536         let buf = CString::new(sect.as_str().as_bytes()).unwrap();
537         llvm::LLVMSetSection(llval, buf.as_ptr());
538     }
539 }
540
541 /// Create the `main` function which will initialize the rust runtime and call
542 /// users main function.
543 fn maybe_create_entry_wrapper(cx: &CodegenCx) {
544     let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
545         Some((id, span, _)) => {
546             (cx.tcx.hir.local_def_id(id), span)
547         }
548         None => return,
549     };
550
551     let instance = Instance::mono(cx.tcx, main_def_id);
552
553     if !cx.codegen_unit.contains_item(&MonoItem::Fn(instance)) {
554         // We want to create the wrapper in the same codegen unit as Rust's main
555         // function.
556         return;
557     }
558
559     let main_llfn = callee::get_fn(cx, instance);
560
561     let et = cx.sess().entry_fn.get().map(|e| e.2);
562     match et {
563         Some(EntryFnType::Main) => create_entry_fn(cx, span, main_llfn, main_def_id, true),
564         Some(EntryFnType::Start) => create_entry_fn(cx, span, main_llfn, main_def_id, false),
565         None => {}    // Do nothing.
566     }
567
568     fn create_entry_fn(
569         cx: &CodegenCx<'ll, '_>,
570         sp: Span,
571         rust_main: &'ll Value,
572         rust_main_def_id: DefId,
573         use_start_lang_item: bool,
574     ) {
575         let llfty = Type::func(&[Type::c_int(cx), Type::i8p(cx).ptr_to()], Type::c_int(cx));
576
577         let main_ret_ty = cx.tcx.fn_sig(rust_main_def_id).output();
578         // Given that `main()` has no arguments,
579         // then its return type cannot have
580         // late-bound regions, since late-bound
581         // regions must appear in the argument
582         // listing.
583         let main_ret_ty = cx.tcx.erase_regions(
584             &main_ret_ty.no_late_bound_regions().unwrap(),
585         );
586
587         if declare::get_defined_value(cx, "main").is_some() {
588             // FIXME: We should be smart and show a better diagnostic here.
589             cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
590                       .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
591                       .emit();
592             cx.sess().abort_if_errors();
593             bug!();
594         }
595         let llfn = declare::declare_cfn(cx, "main", llfty);
596
597         // `main` should respect same config for frame pointer elimination as rest of code
598         attributes::set_frame_pointer_elimination(cx, llfn);
599
600         let bx = Builder::new_block(cx, llfn, "top");
601
602         debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(&bx);
603
604         // Params from native main() used as args for rust start function
605         let param_argc = get_param(llfn, 0);
606         let param_argv = get_param(llfn, 1);
607         let arg_argc = bx.intcast(param_argc, cx.isize_ty, true);
608         let arg_argv = param_argv;
609
610         let (start_fn, args) = if use_start_lang_item {
611             let start_def_id = cx.tcx.require_lang_item(StartFnLangItem);
612             let start_fn = callee::resolve_and_get_fn(
613                 cx,
614                 start_def_id,
615                 cx.tcx.intern_substs(&[main_ret_ty.into()]),
616             );
617             (start_fn, vec![bx.pointercast(rust_main, Type::i8p(cx).ptr_to()),
618                             arg_argc, arg_argv])
619         } else {
620             debug!("using user-defined start fn");
621             (rust_main, vec![arg_argc, arg_argv])
622         };
623
624         let result = bx.call(start_fn, &args, None);
625         bx.ret(bx.intcast(result, Type::c_int(cx), true));
626     }
627 }
628
629 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
630                             llvm_module: &ModuleLlvm,
631                             link_meta: &LinkMeta)
632                             -> EncodedMetadata {
633     use std::io::Write;
634     use flate2::Compression;
635     use flate2::write::DeflateEncoder;
636
637     let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
638
639     #[derive(PartialEq, Eq, PartialOrd, Ord)]
640     enum MetadataKind {
641         None,
642         Uncompressed,
643         Compressed
644     }
645
646     let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
647         match *ty {
648             config::CrateType::Executable |
649             config::CrateType::Staticlib |
650             config::CrateType::Cdylib => MetadataKind::None,
651
652             config::CrateType::Rlib => MetadataKind::Uncompressed,
653
654             config::CrateType::Dylib |
655             config::CrateType::ProcMacro => MetadataKind::Compressed,
656         }
657     }).max().unwrap_or(MetadataKind::None);
658
659     if kind == MetadataKind::None {
660         return EncodedMetadata::new();
661     }
662
663     let metadata = tcx.encode_metadata(link_meta);
664     if kind == MetadataKind::Uncompressed {
665         return metadata;
666     }
667
668     assert!(kind == MetadataKind::Compressed);
669     let mut compressed = tcx.metadata_encoding_version();
670     DeflateEncoder::new(&mut compressed, Compression::fast())
671         .write_all(&metadata.raw_data).unwrap();
672
673     let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
674     let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
675     let name = exported_symbols::metadata_symbol_name(tcx);
676     let buf = CString::new(name).unwrap();
677     let llglobal = unsafe {
678         llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst), buf.as_ptr())
679     };
680     unsafe {
681         llvm::LLVMSetInitializer(llglobal, llconst);
682         let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
683         let name = CString::new(section_name).unwrap();
684         llvm::LLVMSetSection(llglobal, name.as_ptr());
685
686         // Also generate a .section directive to force no
687         // flags, at least for ELF outputs, so that the
688         // metadata doesn't get loaded into memory.
689         let directive = format!(".section {}", section_name);
690         let directive = CString::new(directive).unwrap();
691         llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
692     }
693     return metadata;
694 }
695
696 pub struct ValueIter<'ll> {
697     cur: Option<&'ll Value>,
698     step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
699 }
700
701 impl Iterator for ValueIter<'ll> {
702     type Item = &'ll Value;
703
704     fn next(&mut self) -> Option<&'ll Value> {
705         let old = self.cur;
706         if let Some(old) = old {
707             self.cur = unsafe { (self.step)(old) };
708         }
709         old
710     }
711 }
712
713 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
714     unsafe {
715         ValueIter {
716             cur: llvm::LLVMGetFirstGlobal(llmod),
717             step: llvm::LLVMGetNextGlobal,
718         }
719     }
720 }
721
722 pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
723                              rx: mpsc::Receiver<Box<dyn Any + Send>>)
724                              -> OngoingCodegen {
725
726     check_for_rustc_errors_attr(tcx);
727
728     if let Some(true) = tcx.sess.opts.debugging_opts.thinlto {
729         if unsafe { !llvm::LLVMRustThinLTOAvailable() } {
730             tcx.sess.fatal("this compiler's LLVM does not support ThinLTO");
731         }
732     }
733
734     if (tcx.sess.opts.debugging_opts.pgo_gen.is_some() ||
735         !tcx.sess.opts.debugging_opts.pgo_use.is_empty()) &&
736         unsafe { !llvm::LLVMRustPGOAvailable() }
737     {
738         tcx.sess.fatal("this compiler's LLVM does not support PGO");
739     }
740
741     let crate_hash = tcx.crate_hash(LOCAL_CRATE);
742     let link_meta = link::build_link_meta(crate_hash);
743
744     // Codegen the metadata.
745     tcx.sess.profiler(|p| p.start_activity(ProfileCategory::Codegen));
746     let llmod_id = "metadata";
747     let metadata_llvm_module = ModuleLlvm::new(tcx.sess, llmod_id);
748     let metadata = time(tcx.sess, "write metadata", || {
749         write_metadata(tcx, &metadata_llvm_module, &link_meta)
750     });
751     tcx.sess.profiler(|p| p.end_activity(ProfileCategory::Codegen));
752
753     let metadata_module = ModuleCodegen {
754         name: link::METADATA_MODULE_NAME.to_string(),
755         llmod_id: llmod_id.to_string(),
756         source: ModuleSource::Codegened(metadata_llvm_module),
757         kind: ModuleKind::Metadata,
758     };
759
760     let time_graph = if tcx.sess.opts.debugging_opts.codegen_time_graph {
761         Some(time_graph::TimeGraph::new())
762     } else {
763         None
764     };
765
766     // Skip crate items and just output metadata in -Z no-codegen mode.
767     if tcx.sess.opts.debugging_opts.no_codegen ||
768        !tcx.sess.opts.output_types.should_codegen() {
769         let ongoing_codegen = write::start_async_codegen(
770             tcx,
771             time_graph.clone(),
772             link_meta,
773             metadata,
774             rx,
775             1);
776
777         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
778         ongoing_codegen.codegen_finished(tcx);
779
780         assert_and_save_dep_graph(tcx);
781
782         ongoing_codegen.check_for_errors(tcx.sess);
783
784         return ongoing_codegen;
785     }
786
787     // Run the monomorphization collector and partition the collected items into
788     // codegen units.
789     let codegen_units =
790         tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
791     let codegen_units = (*codegen_units).clone();
792
793     // Force all codegen_unit queries so they are already either red or green
794     // when compile_codegen_unit accesses them. We are not able to re-execute
795     // the codegen_unit query from just the DepNode, so an unknown color would
796     // lead to having to re-execute compile_codegen_unit, possibly
797     // unnecessarily.
798     if tcx.dep_graph.is_fully_enabled() {
799         for cgu in &codegen_units {
800             tcx.codegen_unit(cgu.name().clone());
801         }
802     }
803
804     let ongoing_codegen = write::start_async_codegen(
805         tcx,
806         time_graph.clone(),
807         link_meta,
808         metadata,
809         rx,
810         codegen_units.len());
811
812     // Codegen an allocator shim, if any
813     let allocator_module = if let Some(kind) = *tcx.sess.allocator_kind.get() {
814         unsafe {
815             let llmod_id = "allocator";
816             let modules = ModuleLlvm::new(tcx.sess, llmod_id);
817             time(tcx.sess, "write allocator module", || {
818                 allocator::codegen(tcx, &modules, kind)
819             });
820
821             Some(ModuleCodegen {
822                 name: link::ALLOCATOR_MODULE_NAME.to_string(),
823                 llmod_id: llmod_id.to_string(),
824                 source: ModuleSource::Codegened(modules),
825                 kind: ModuleKind::Allocator,
826             })
827         }
828     } else {
829         None
830     };
831
832     if let Some(allocator_module) = allocator_module {
833         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
834     }
835
836     ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
837
838     // We sort the codegen units by size. This way we can schedule work for LLVM
839     // a bit more efficiently.
840     let codegen_units = {
841         let mut codegen_units = codegen_units;
842         codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
843         codegen_units
844     };
845
846     let mut total_codegen_time = Duration::new(0, 0);
847     let mut all_stats = Stats::default();
848
849     for cgu in codegen_units.into_iter() {
850         ongoing_codegen.wait_for_signal_to_codegen_item();
851         ongoing_codegen.check_for_errors(tcx.sess);
852
853         // First, if incremental compilation is enabled, we try to re-use the
854         // codegen unit from the cache.
855         if tcx.dep_graph.is_fully_enabled() {
856             let cgu_id = cgu.work_product_id();
857
858             // Check whether there is a previous work-product we can
859             // re-use.  Not only must the file exist, and the inputs not
860             // be dirty, but the hash of the symbols we will generate must
861             // be the same.
862             if let Some(buf) = tcx.dep_graph.previous_work_product(&cgu_id) {
863                 let dep_node = &DepNode::new(tcx,
864                     DepConstructor::CompileCodegenUnit(cgu.name().clone()));
865
866                 // We try to mark the DepNode::CompileCodegenUnit green. If we
867                 // succeed it means that none of the dependencies has changed
868                 // and we can safely re-use.
869                 if let Some(dep_node_index) = tcx.dep_graph.try_mark_green(tcx, dep_node) {
870                     // Append ".rs" to LLVM module identifier.
871                     //
872                     // LLVM code generator emits a ".file filename" directive
873                     // for ELF backends. Value of the "filename" is set as the
874                     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
875                     // crashes if the module identifier is same as other symbols
876                     // such as a function name in the module.
877                     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
878                     let llmod_id = format!("{}.rs", cgu.name());
879
880                     let module = ModuleCodegen {
881                         name: cgu.name().to_string(),
882                         source: ModuleSource::Preexisting(buf),
883                         kind: ModuleKind::Regular,
884                         llmod_id,
885                     };
886                     tcx.dep_graph.mark_loaded_from_cache(dep_node_index, true);
887                     write::submit_codegened_module_to_llvm(tcx, module, 0);
888                     // Continue to next cgu, this one is done.
889                     continue
890                 }
891             } else {
892                 // This can happen if files were  deleted from the cache
893                 // directory for some reason. We just re-compile then.
894             }
895         }
896
897         let _timing_guard = time_graph.as_ref().map(|time_graph| {
898             time_graph.start(write::CODEGEN_WORKER_TIMELINE,
899                              write::CODEGEN_WORK_PACKAGE_KIND,
900                              &format!("codegen {}", cgu.name()))
901         });
902         let start_time = Instant::now();
903         all_stats.extend(tcx.compile_codegen_unit(*cgu.name()));
904         total_codegen_time += start_time.elapsed();
905         ongoing_codegen.check_for_errors(tcx.sess);
906     }
907
908     ongoing_codegen.codegen_finished(tcx);
909
910     // Since the main thread is sometimes blocked during codegen, we keep track
911     // -Ztime-passes output manually.
912     print_time_passes_entry(tcx.sess.time_passes(),
913                             "codegen to LLVM IR",
914                             total_codegen_time);
915
916     if tcx.sess.opts.incremental.is_some() {
917         ::rustc_incremental::assert_module_sources::assert_module_sources(tcx);
918     }
919
920     symbol_names_test::report_symbol_names(tcx);
921
922     if tcx.sess.codegen_stats() {
923         println!("--- codegen stats ---");
924         println!("n_glues_created: {}", all_stats.n_glues_created);
925         println!("n_null_glues: {}", all_stats.n_null_glues);
926         println!("n_real_glues: {}", all_stats.n_real_glues);
927
928         println!("n_fns: {}", all_stats.n_fns);
929         println!("n_inlines: {}", all_stats.n_inlines);
930         println!("n_closures: {}", all_stats.n_closures);
931         println!("fn stats:");
932         all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
933         for &(ref name, insns) in all_stats.fn_stats.iter() {
934             println!("{} insns, {}", insns, *name);
935         }
936     }
937
938     if tcx.sess.count_llvm_insns() {
939         for (k, v) in all_stats.llvm_insns.iter() {
940             println!("{:7} {}", *v, *k);
941         }
942     }
943
944     ongoing_codegen.check_for_errors(tcx.sess);
945
946     assert_and_save_dep_graph(tcx);
947     ongoing_codegen
948 }
949
950 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
951     time(tcx.sess,
952          "assert dep graph",
953          || rustc_incremental::assert_dep_graph(tcx));
954
955     time(tcx.sess,
956          "serialize dep graph",
957          || rustc_incremental::save_dep_graph(tcx));
958 }
959
960 fn collect_and_partition_mono_items<'a, 'tcx>(
961     tcx: TyCtxt<'a, 'tcx, 'tcx>,
962     cnum: CrateNum,
963 ) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
964 {
965     assert_eq!(cnum, LOCAL_CRATE);
966
967     let collection_mode = match tcx.sess.opts.debugging_opts.print_mono_items {
968         Some(ref s) => {
969             let mode_string = s.to_lowercase();
970             let mode_string = mode_string.trim();
971             if mode_string == "eager" {
972                 MonoItemCollectionMode::Eager
973             } else {
974                 if mode_string != "lazy" {
975                     let message = format!("Unknown codegen-item collection mode '{}'. \
976                                            Falling back to 'lazy' mode.",
977                                            mode_string);
978                     tcx.sess.warn(&message);
979                 }
980
981                 MonoItemCollectionMode::Lazy
982             }
983         }
984         None => {
985             if tcx.sess.opts.cg.link_dead_code {
986                 MonoItemCollectionMode::Eager
987             } else {
988                 MonoItemCollectionMode::Lazy
989             }
990         }
991     };
992
993     let (items, inlining_map) =
994         time(tcx.sess, "monomorphization collection", || {
995             collector::collect_crate_mono_items(tcx, collection_mode)
996     });
997
998     tcx.sess.abort_if_errors();
999
1000     ::rustc_mir::monomorphize::assert_symbols_are_distinct(tcx, items.iter());
1001
1002     let strategy = if tcx.sess.opts.incremental.is_some() {
1003         PartitioningStrategy::PerModule
1004     } else {
1005         PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
1006     };
1007
1008     let codegen_units = time(tcx.sess, "codegen unit partitioning", || {
1009         partitioning::partition(tcx,
1010                                 items.iter().cloned(),
1011                                 strategy,
1012                                 &inlining_map)
1013             .into_iter()
1014             .map(Arc::new)
1015             .collect::<Vec<_>>()
1016     });
1017
1018     let mono_items: DefIdSet = items.iter().filter_map(|mono_item| {
1019         match *mono_item {
1020             MonoItem::Fn(ref instance) => Some(instance.def_id()),
1021             MonoItem::Static(def_id) => Some(def_id),
1022             _ => None,
1023         }
1024     }).collect();
1025
1026     if tcx.sess.opts.debugging_opts.print_mono_items.is_some() {
1027         let mut item_to_cgus = FxHashMap();
1028
1029         for cgu in &codegen_units {
1030             for (&mono_item, &linkage) in cgu.items() {
1031                 item_to_cgus.entry(mono_item)
1032                             .or_insert(Vec::new())
1033                             .push((cgu.name().clone(), linkage));
1034             }
1035         }
1036
1037         let mut item_keys: Vec<_> = items
1038             .iter()
1039             .map(|i| {
1040                 let mut output = i.to_string(tcx);
1041                 output.push_str(" @@");
1042                 let mut empty = Vec::new();
1043                 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1044                 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1045                 cgus.dedup();
1046                 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1047                     output.push_str(" ");
1048                     output.push_str(&cgu_name.as_str());
1049
1050                     let linkage_abbrev = match linkage {
1051                         Linkage::External => "External",
1052                         Linkage::AvailableExternally => "Available",
1053                         Linkage::LinkOnceAny => "OnceAny",
1054                         Linkage::LinkOnceODR => "OnceODR",
1055                         Linkage::WeakAny => "WeakAny",
1056                         Linkage::WeakODR => "WeakODR",
1057                         Linkage::Appending => "Appending",
1058                         Linkage::Internal => "Internal",
1059                         Linkage::Private => "Private",
1060                         Linkage::ExternalWeak => "ExternalWeak",
1061                         Linkage::Common => "Common",
1062                     };
1063
1064                     output.push_str("[");
1065                     output.push_str(linkage_abbrev);
1066                     output.push_str("]");
1067                 }
1068                 output
1069             })
1070             .collect();
1071
1072         item_keys.sort();
1073
1074         for item in item_keys {
1075             println!("MONO_ITEM {}", item);
1076         }
1077     }
1078
1079     (Arc::new(mono_items), Arc::new(codegen_units))
1080 }
1081
1082 impl CrateInfo {
1083     pub fn new(tcx: TyCtxt) -> CrateInfo {
1084         let mut info = CrateInfo {
1085             panic_runtime: None,
1086             compiler_builtins: None,
1087             profiler_runtime: None,
1088             sanitizer_runtime: None,
1089             is_no_builtins: FxHashSet(),
1090             native_libraries: FxHashMap(),
1091             used_libraries: tcx.native_libraries(LOCAL_CRATE),
1092             link_args: tcx.link_args(LOCAL_CRATE),
1093             crate_name: FxHashMap(),
1094             used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1095             used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1096             used_crate_source: FxHashMap(),
1097             wasm_imports: FxHashMap(),
1098             lang_item_to_crate: FxHashMap(),
1099             missing_lang_items: FxHashMap(),
1100         };
1101         let lang_items = tcx.lang_items();
1102
1103         let load_wasm_items = tcx.sess.crate_types.borrow()
1104             .iter()
1105             .any(|c| *c != config::CrateType::Rlib) &&
1106             tcx.sess.opts.target_triple.triple() == "wasm32-unknown-unknown";
1107
1108         if load_wasm_items {
1109             info.load_wasm_imports(tcx, LOCAL_CRATE);
1110         }
1111
1112         for &cnum in tcx.crates().iter() {
1113             info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1114             info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1115             info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1116             if tcx.is_panic_runtime(cnum) {
1117                 info.panic_runtime = Some(cnum);
1118             }
1119             if tcx.is_compiler_builtins(cnum) {
1120                 info.compiler_builtins = Some(cnum);
1121             }
1122             if tcx.is_profiler_runtime(cnum) {
1123                 info.profiler_runtime = Some(cnum);
1124             }
1125             if tcx.is_sanitizer_runtime(cnum) {
1126                 info.sanitizer_runtime = Some(cnum);
1127             }
1128             if tcx.is_no_builtins(cnum) {
1129                 info.is_no_builtins.insert(cnum);
1130             }
1131             if load_wasm_items {
1132                 info.load_wasm_imports(tcx, cnum);
1133             }
1134             let missing = tcx.missing_lang_items(cnum);
1135             for &item in missing.iter() {
1136                 if let Ok(id) = lang_items.require(item) {
1137                     info.lang_item_to_crate.insert(item, id.krate);
1138                 }
1139             }
1140
1141             // No need to look for lang items that are whitelisted and don't
1142             // actually need to exist.
1143             let missing = missing.iter()
1144                 .cloned()
1145                 .filter(|&l| !weak_lang_items::whitelisted(tcx, l))
1146                 .collect();
1147             info.missing_lang_items.insert(cnum, missing);
1148         }
1149
1150         return info
1151     }
1152
1153     fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
1154         for (&id, module) in tcx.wasm_import_module_map(cnum).iter() {
1155             let instance = Instance::mono(tcx, id);
1156             let import_name = tcx.symbol_name(instance);
1157             self.wasm_imports.insert(import_name.to_string(), module.clone());
1158         }
1159     }
1160 }
1161
1162 fn is_codegened_item(tcx: TyCtxt, id: DefId) -> bool {
1163     let (all_mono_items, _) =
1164         tcx.collect_and_partition_mono_items(LOCAL_CRATE);
1165     all_mono_items.contains(&id)
1166 }
1167
1168 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1169                                   cgu: InternedString) -> Stats {
1170     let cgu = tcx.codegen_unit(cgu);
1171
1172     let start_time = Instant::now();
1173     let (stats, module) = module_codegen(tcx, cgu);
1174     let time_to_codegen = start_time.elapsed();
1175
1176     // We assume that the cost to run LLVM on a CGU is proportional to
1177     // the time we needed for codegenning it.
1178     let cost = time_to_codegen.as_secs() * 1_000_000_000 +
1179                time_to_codegen.subsec_nanos() as u64;
1180
1181     write::submit_codegened_module_to_llvm(tcx,
1182                                             module,
1183                                             cost);
1184     return stats;
1185
1186     fn module_codegen<'a, 'tcx>(
1187         tcx: TyCtxt<'a, 'tcx, 'tcx>,
1188         cgu: Arc<CodegenUnit<'tcx>>)
1189         -> (Stats, ModuleCodegen)
1190     {
1191         let cgu_name = cgu.name().to_string();
1192
1193         // Append ".rs" to LLVM module identifier.
1194         //
1195         // LLVM code generator emits a ".file filename" directive
1196         // for ELF backends. Value of the "filename" is set as the
1197         // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
1198         // crashes if the module identifier is same as other symbols
1199         // such as a function name in the module.
1200         // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
1201         let llmod_id = format!("{}-{}.rs",
1202                                cgu.name(),
1203                                tcx.crate_disambiguator(LOCAL_CRATE)
1204                                    .to_fingerprint().to_hex());
1205
1206         // Instantiate monomorphizations without filling out definitions yet...
1207         let llvm_module = ModuleLlvm::new(tcx.sess, &llmod_id);
1208         let stats = {
1209             let cx = CodegenCx::new(tcx, cgu, &llvm_module);
1210             let mono_items = cx.codegen_unit
1211                                  .items_in_deterministic_order(cx.tcx);
1212             for &(mono_item, (linkage, visibility)) in &mono_items {
1213                 mono_item.predefine(&cx, linkage, visibility);
1214             }
1215
1216             // ... and now that we have everything pre-defined, fill out those definitions.
1217             for &(mono_item, _) in &mono_items {
1218                 mono_item.define(&cx);
1219             }
1220
1221             // If this codegen unit contains the main function, also create the
1222             // wrapper here
1223             maybe_create_entry_wrapper(&cx);
1224
1225             // Run replace-all-uses-with for statics that need it
1226             for &(old_g, new_g) in cx.statics_to_rauw.borrow().iter() {
1227                 unsafe {
1228                     let bitcast = llvm::LLVMConstPointerCast(new_g, val_ty(old_g));
1229                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1230                     llvm::LLVMDeleteGlobal(old_g);
1231                 }
1232             }
1233
1234             // Create the llvm.used variable
1235             // This variable has type [N x i8*] and is stored in the llvm.metadata section
1236             if !cx.used_statics.borrow().is_empty() {
1237                 let name = CString::new("llvm.used").unwrap();
1238                 let section = CString::new("llvm.metadata").unwrap();
1239                 let array = C_array(Type::i8(&cx).ptr_to(), &*cx.used_statics.borrow());
1240
1241                 unsafe {
1242                     let g = llvm::LLVMAddGlobal(cx.llmod,
1243                                                 val_ty(array),
1244                                                 name.as_ptr());
1245                     llvm::LLVMSetInitializer(g, array);
1246                     llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1247                     llvm::LLVMSetSection(g, section.as_ptr());
1248                 }
1249             }
1250
1251             // Finalize debuginfo
1252             if cx.sess().opts.debuginfo != NoDebugInfo {
1253                 debuginfo::finalize(&cx);
1254             }
1255
1256             cx.stats.into_inner()
1257         };
1258
1259         (stats, ModuleCodegen {
1260             name: cgu_name,
1261             source: ModuleSource::Codegened(llvm_module),
1262             kind: ModuleKind::Regular,
1263             llmod_id,
1264         })
1265     }
1266 }
1267
1268 pub fn provide(providers: &mut Providers) {
1269     providers.collect_and_partition_mono_items =
1270         collect_and_partition_mono_items;
1271
1272     providers.is_codegened_item = is_codegened_item;
1273
1274     providers.codegen_unit = |tcx, name| {
1275         let (_, all) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
1276         all.iter()
1277             .find(|cgu| *cgu.name() == name)
1278             .cloned()
1279             .unwrap_or_else(|| panic!("failed to find cgu with name {:?}", name))
1280     };
1281     providers.compile_codegen_unit = compile_codegen_unit;
1282
1283     provide_extern(providers);
1284 }
1285
1286 pub fn provide_extern(providers: &mut Providers) {
1287     providers.dllimport_foreign_items = |tcx, krate| {
1288         let module_map = tcx.foreign_modules(krate);
1289         let module_map = module_map.iter()
1290             .map(|lib| (lib.def_id, lib))
1291             .collect::<FxHashMap<_, _>>();
1292
1293         let dllimports = tcx.native_libraries(krate)
1294             .iter()
1295             .filter(|lib| {
1296                 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
1297                     return false
1298                 }
1299                 let cfg = match lib.cfg {
1300                     Some(ref cfg) => cfg,
1301                     None => return true,
1302                 };
1303                 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
1304             })
1305             .filter_map(|lib| lib.foreign_module)
1306             .map(|id| &module_map[&id])
1307             .flat_map(|module| module.foreign_items.iter().cloned())
1308             .collect();
1309         Lrc::new(dllimports)
1310     };
1311
1312     providers.is_dllimport_foreign_item = |tcx, def_id| {
1313         tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
1314     };
1315 }
1316
1317 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1318     match linkage {
1319         Linkage::External => llvm::Linkage::ExternalLinkage,
1320         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1321         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1322         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1323         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1324         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1325         Linkage::Appending => llvm::Linkage::AppendingLinkage,
1326         Linkage::Internal => llvm::Linkage::InternalLinkage,
1327         Linkage::Private => llvm::Linkage::PrivateLinkage,
1328         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1329         Linkage::Common => llvm::Linkage::CommonLinkage,
1330     }
1331 }
1332
1333 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1334     match linkage {
1335         Visibility::Default => llvm::Visibility::Default,
1336         Visibility::Hidden => llvm::Visibility::Hidden,
1337         Visibility::Protected => llvm::Visibility::Protected,
1338     }
1339 }
1340
1341 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1342 //            the HashStable trait. Normally DepGraph::with_task() calls are
1343 //            hidden behind queries, but CGU creation is a special case in two
1344 //            ways: (1) it's not a query and (2) CGU are output nodes, so their
1345 //            Fingerprints are not actually needed. It remains to be clarified
1346 //            how exactly this case will be handled in the red/green system but
1347 //            for now we content ourselves with providing a no-op HashStable
1348 //            implementation for CGUs.
1349 mod temp_stable_hash_impls {
1350     use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1351                                                HashStable};
1352     use ModuleCodegen;
1353
1354     impl<HCX> HashStable<HCX> for ModuleCodegen {
1355         fn hash_stable<W: StableHasherResult>(&self,
1356                                               _: &mut HCX,
1357                                               _: &mut StableHasher<W>) {
1358             // do nothing
1359         }
1360     }
1361 }