]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/base.rs
Fix test
[rust.git] / src / librustc_trans / 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 //! Translate the completed AST to the LLVM IR.
12 //!
13 //! Some functions here, such as trans_block and trans_expr, return a value --
14 //! the result of the translation to LLVM -- while others, such as trans_fn
15 //! and trans_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 trans:
19 //!
20 //!   * There's no way to find out the Ty type of a ValueRef.  Doing so
21 //!     would be "trying to get the eggs out of an omelette" (credit:
22 //!     pcwalton).  You can, instead, find out its TypeRef by calling val_ty,
23 //!     but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
24 //!     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
25
26 use super::ModuleLlvm;
27 use super::ModuleSource;
28 use super::ModuleTranslation;
29 use super::ModuleKind;
30
31 use abi;
32 use back::link;
33 use back::write::{self, OngoingCrateTranslation, create_target_machine};
34 use llvm::{ContextRef, ModuleRef, ValueRef, Vector, get_param};
35 use llvm;
36 use metadata;
37 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
38 use rustc::middle::lang_items::StartFnLangItem;
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::maps::Providers;
44 use rustc::dep_graph::{DepNode, DepConstructor};
45 use rustc::ty::subst::Kind;
46 use rustc::middle::cstore::{self, LinkMeta, LinkagePreference};
47 use rustc::middle::exported_symbols;
48 use rustc::util::common::{time, print_time_passes_entry};
49 use rustc::session::config::{self, NoDebugInfo};
50 use rustc::session::Session;
51 use rustc_incremental;
52 use allocator;
53 use mir::place::PlaceRef;
54 use attributes;
55 use builder::Builder;
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 common::{self, C_struct_in_context, C_array, val_ty};
60 use consts;
61 use context::{self, 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_trans_utils::symbol_names_test;
69 use time_graph;
70 use trans_item::{MonoItem, BaseMonoItemExt, MonoItemExt, DefPathBasedNames};
71 use type_::Type;
72 use type_of::LayoutLlvmExt;
73 use rustc::util::nodemap::{FxHashMap, FxHashSet, DefIdSet};
74 use CrateInfo;
75 use rustc_data_structures::sync::Lrc;
76
77 use std::any::Any;
78 use std::collections::BTreeMap;
79 use std::ffi::CString;
80 use std::str;
81 use std::sync::Arc;
82 use std::time::{Instant, Duration};
83 use std::{i32, usize};
84 use std::iter;
85 use std::sync::mpsc;
86 use syntax_pos::Span;
87 use syntax_pos::symbol::InternedString;
88 use syntax::attr;
89 use rustc::hir;
90 use syntax::ast;
91
92 use mir::operand::OperandValue;
93
94 pub use rustc_trans_utils::check_for_rustc_errors_attr;
95
96 pub struct StatRecorder<'a, 'tcx: 'a> {
97     cx: &'a CodegenCx<'a, 'tcx>,
98     name: Option<String>,
99     istart: usize,
100 }
101
102 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
103     pub fn new(cx: &'a CodegenCx<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
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<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
114     fn drop(&mut self) {
115         if self.cx.sess().trans_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::BinOp_,
127                                 signed: bool)
128                                 -> llvm::IntPredicate {
129     match op {
130         hir::BiEq => llvm::IntEQ,
131         hir::BiNe => llvm::IntNE,
132         hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
133         hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
134         hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
135         hir::BiGe => 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::BinOp_) -> llvm::RealPredicate {
145     match op {
146         hir::BiEq => llvm::RealOEQ,
147         hir::BiNe => llvm::RealUNE,
148         hir::BiLt => llvm::RealOLT,
149         hir::BiLe => llvm::RealOLE,
150         hir::BiGt => llvm::RealOGT,
151         hir::BiGe => 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<'a, 'tcx>(
161     bx: &Builder<'a, 'tcx>,
162     lhs: ValueRef,
163     rhs: ValueRef,
164     t: Ty<'tcx>,
165     ret_ty: Type,
166     op: hir::BinOp_
167 ) -> ValueRef {
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<'cx, 'tcx>(cx: &CodegenCx<'cx, 'tcx>,
193                                 source: Ty<'tcx>,
194                                 target: Ty<'tcx>,
195                                 old_info: Option<ValueRef>)
196                                 -> ValueRef {
197     let (source, target) = cx.tcx.struct_lockstep_tails(source, target);
198     match (&source.sty, &target.sty) {
199         (&ty::TyArray(_, len), &ty::TySlice(_)) => {
200             C_usize(cx, len.val.unwrap_u64())
201         }
202         (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
203             // For now, upcasts are limited to changes in marker
204             // traits, and hence never actually require an actual
205             // change to the vtable.
206             old_info.expect("unsized_info: missing old info for trait upcast")
207         }
208         (_, &ty::TyDynamic(ref data, ..)) => {
209             let vtable_ptr = cx.layout_of(cx.tcx.mk_mut_ptr(target))
210                 .field(cx, abi::FAT_PTR_EXTRA);
211             consts::ptrcast(meth::get_vtable(cx, source, data.principal()),
212                             vtable_ptr.llvm_type(cx))
213         }
214         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
215                                      source,
216                                      target),
217     }
218 }
219
220 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
221 pub fn unsize_thin_ptr<'a, 'tcx>(
222     bx: &Builder<'a, 'tcx>,
223     src: ValueRef,
224     src_ty: Ty<'tcx>,
225     dst_ty: Ty<'tcx>
226 ) -> (ValueRef, ValueRef) {
227     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
228     match (&src_ty.sty, &dst_ty.sty) {
229         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
230          &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
231         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
232          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
233         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
234          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
235             assert!(bx.cx.type_is_sized(a));
236             let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
237             (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
238         }
239         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
240             let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
241             assert!(bx.cx.type_is_sized(a));
242             let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
243             (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
244         }
245         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
246             assert_eq!(def_a, def_b);
247
248             let src_layout = bx.cx.layout_of(src_ty);
249             let dst_layout = bx.cx.layout_of(dst_ty);
250             let mut result = None;
251             for i in 0..src_layout.fields.count() {
252                 let src_f = src_layout.field(bx.cx, i);
253                 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
254                 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
255                 if src_f.is_zst() {
256                     continue;
257                 }
258                 assert_eq!(src_layout.size, src_f.size);
259
260                 let dst_f = dst_layout.field(bx.cx, i);
261                 assert_ne!(src_f.ty, dst_f.ty);
262                 assert_eq!(result, None);
263                 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
264             }
265             let (lldata, llextra) = result.unwrap();
266             // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
267             (bx.bitcast(lldata, dst_layout.scalar_pair_element_llvm_type(bx.cx, 0)),
268              bx.bitcast(llextra, dst_layout.scalar_pair_element_llvm_type(bx.cx, 1)))
269         }
270         _ => bug!("unsize_thin_ptr: called on bad types"),
271     }
272 }
273
274 /// Coerce `src`, which is a reference to a value of type `src_ty`,
275 /// to a value of type `dst_ty` and store the result in `dst`
276 pub fn coerce_unsized_into<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
277                                      src: PlaceRef<'tcx>,
278                                      dst: PlaceRef<'tcx>) {
279     let src_ty = src.layout.ty;
280     let dst_ty = dst.layout.ty;
281     let coerce_ptr = || {
282         let (base, info) = match src.load(bx).val {
283             OperandValue::Pair(base, info) => {
284                 // fat-ptr to fat-ptr unsize preserves the vtable
285                 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
286                 // So we need to pointercast the base to ensure
287                 // the types match up.
288                 let thin_ptr = dst.layout.field(bx.cx, abi::FAT_PTR_ADDR);
289                 (bx.pointercast(base, thin_ptr.llvm_type(bx.cx)), info)
290             }
291             OperandValue::Immediate(base) => {
292                 unsize_thin_ptr(bx, base, src_ty, dst_ty)
293             }
294             OperandValue::Ref(..) => bug!()
295         };
296         OperandValue::Pair(base, info).store(bx, dst);
297     };
298     match (&src_ty.sty, &dst_ty.sty) {
299         (&ty::TyRef(..), &ty::TyRef(..)) |
300         (&ty::TyRef(..), &ty::TyRawPtr(..)) |
301         (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
302             coerce_ptr()
303         }
304         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
305             coerce_ptr()
306         }
307
308         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
309             assert_eq!(def_a, def_b);
310
311             for i in 0..def_a.variants[0].fields.len() {
312                 let src_f = src.project_field(bx, i);
313                 let dst_f = dst.project_field(bx, i);
314
315                 if dst_f.layout.is_zst() {
316                     continue;
317                 }
318
319                 if src_f.layout.ty == dst_f.layout.ty {
320                     memcpy_ty(bx, dst_f.llval, src_f.llval, src_f.layout,
321                         src_f.align.min(dst_f.align));
322                 } else {
323                     coerce_unsized_into(bx, src_f, dst_f);
324                 }
325             }
326         }
327         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
328                   src_ty,
329                   dst_ty),
330     }
331 }
332
333 pub fn cast_shift_expr_rhs(
334     cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
335 ) -> ValueRef {
336     cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
337 }
338
339 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
340                         lhs: ValueRef,
341                         rhs: ValueRef,
342                         trunc: F,
343                         zext: G)
344                         -> ValueRef
345     where F: FnOnce(ValueRef, Type) -> ValueRef,
346           G: FnOnce(ValueRef, Type) -> ValueRef
347 {
348     // Shifts may have any size int on the rhs
349     if op.is_shift() {
350         let mut rhs_llty = val_ty(rhs);
351         let mut lhs_llty = val_ty(lhs);
352         if rhs_llty.kind() == Vector {
353             rhs_llty = rhs_llty.element_type()
354         }
355         if lhs_llty.kind() == Vector {
356             lhs_llty = lhs_llty.element_type()
357         }
358         let rhs_sz = rhs_llty.int_width();
359         let lhs_sz = lhs_llty.int_width();
360         if lhs_sz < rhs_sz {
361             trunc(rhs, lhs_llty)
362         } else if lhs_sz > rhs_sz {
363             // FIXME (#1877: If shifting by negative
364             // values becomes not undefined then this is wrong.
365             zext(rhs, lhs_llty)
366         } else {
367             rhs
368         }
369     } else {
370         rhs
371     }
372 }
373
374 /// Returns whether this session's target will use SEH-based unwinding.
375 ///
376 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
377 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
378 /// 64-bit MinGW) instead of "full SEH".
379 pub fn wants_msvc_seh(sess: &Session) -> bool {
380     sess.target.target.options.is_like_msvc
381 }
382
383 pub fn call_assume<'a, 'tcx>(bx: &Builder<'a, 'tcx>, val: ValueRef) {
384     let assume_intrinsic = bx.cx.get_intrinsic("llvm.assume");
385     bx.call(assume_intrinsic, &[val], None);
386 }
387
388 pub fn from_immediate(bx: &Builder, val: ValueRef) -> ValueRef {
389     if val_ty(val) == Type::i1(bx.cx) {
390         bx.zext(val, Type::i8(bx.cx))
391     } else {
392         val
393     }
394 }
395
396 pub fn to_immediate(bx: &Builder, val: ValueRef, layout: layout::TyLayout) -> ValueRef {
397     if let layout::Abi::Scalar(ref scalar) = layout.abi {
398         if scalar.is_bool() {
399             return bx.trunc(val, Type::i1(bx.cx));
400         }
401     }
402     val
403 }
404
405 pub fn call_memcpy(bx: &Builder,
406                    dst: ValueRef,
407                    src: ValueRef,
408                    n_bytes: ValueRef,
409                    align: Align) {
410     let cx = bx.cx;
411     let ptr_width = &cx.sess().target.target.target_pointer_width;
412     let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
413     let memcpy = cx.get_intrinsic(&key);
414     let src_ptr = bx.pointercast(src, Type::i8p(cx));
415     let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
416     let size = bx.intcast(n_bytes, cx.isize_ty, false);
417     let align = C_i32(cx, align.abi() as i32);
418     let volatile = C_bool(cx, false);
419     bx.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
420 }
421
422 pub fn memcpy_ty<'a, 'tcx>(
423     bx: &Builder<'a, 'tcx>,
424     dst: ValueRef,
425     src: ValueRef,
426     layout: TyLayout<'tcx>,
427     align: Align,
428 ) {
429     let size = layout.size.bytes();
430     if size == 0 {
431         return;
432     }
433
434     call_memcpy(bx, dst, src, C_usize(bx.cx, size), align);
435 }
436
437 pub fn call_memset<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
438                              ptr: ValueRef,
439                              fill_byte: ValueRef,
440                              size: ValueRef,
441                              align: ValueRef,
442                              volatile: bool) -> ValueRef {
443     let ptr_width = &bx.cx.sess().target.target.target_pointer_width;
444     let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
445     let llintrinsicfn = bx.cx.get_intrinsic(&intrinsic_key);
446     let volatile = C_bool(bx.cx, volatile);
447     bx.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
448 }
449
450 pub fn trans_instance<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, instance: Instance<'tcx>) {
451     let _s = if cx.sess().trans_stats() {
452         let mut instance_name = String::new();
453         DefPathBasedNames::new(cx.tcx, true, true)
454             .push_def_path(instance.def_id(), &mut instance_name);
455         Some(StatRecorder::new(cx, instance_name))
456     } else {
457         None
458     };
459
460     // this is an info! to allow collecting monomorphization statistics
461     // and to allow finding the last function before LLVM aborts from
462     // release builds.
463     info!("trans_instance({})", instance);
464
465     let fn_ty = instance.ty(cx.tcx);
466     let sig = common::ty_fn_sig(cx, fn_ty);
467     let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
468
469     let lldecl = match cx.instances.borrow().get(&instance) {
470         Some(&val) => val,
471         None => bug!("Instance `{:?}` not already declared", instance)
472     };
473
474     cx.stats.borrow_mut().n_closures += 1;
475
476     // The `uwtable` attribute according to LLVM is:
477     //
478     //     This attribute indicates that the ABI being targeted requires that an
479     //     unwind table entry be produced for this function even if we can show
480     //     that no exceptions passes by it. This is normally the case for the
481     //     ELF x86-64 abi, but it can be disabled for some compilation units.
482     //
483     // Typically when we're compiling with `-C panic=abort` (which implies this
484     // `no_landing_pads` check) we don't need `uwtable` because we can't
485     // generate any exceptions! On Windows, however, exceptions include other
486     // events such as illegal instructions, segfaults, etc. This means that on
487     // Windows we end up still needing the `uwtable` attribute even if the `-C
488     // panic=abort` flag is passed.
489     //
490     // You can also find more info on why Windows is whitelisted here in:
491     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
492     if !cx.sess().no_landing_pads() ||
493        cx.sess().target.target.options.is_like_windows {
494         attributes::emit_uwtable(lldecl, true);
495     }
496
497     let mir = cx.tcx.instance_mir(instance.def);
498     mir::trans_mir(cx, lldecl, &mir, instance, sig);
499 }
500
501 pub fn set_link_section(cx: &CodegenCx,
502                         llval: ValueRef,
503                         attrs: &[ast::Attribute]) {
504     if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
505         if contains_null(&sect.as_str()) {
506             cx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", &sect));
507         }
508         unsafe {
509             let buf = CString::new(sect.as_str().as_bytes()).unwrap();
510             llvm::LLVMSetSection(llval, buf.as_ptr());
511         }
512     }
513 }
514
515 /// Create the `main` function which will initialize the rust runtime and call
516 /// users main function.
517 fn maybe_create_entry_wrapper(cx: &CodegenCx) {
518     let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
519         Some((id, span)) => {
520             (cx.tcx.hir.local_def_id(id), span)
521         }
522         None => return,
523     };
524
525     let instance = Instance::mono(cx.tcx, main_def_id);
526
527     if !cx.codegen_unit.contains_item(&MonoItem::Fn(instance)) {
528         // We want to create the wrapper in the same codegen unit as Rust's main
529         // function.
530         return;
531     }
532
533     let main_llfn = callee::get_fn(cx, instance);
534
535     let et = cx.sess().entry_type.get().unwrap();
536     match et {
537         config::EntryMain => create_entry_fn(cx, span, main_llfn, main_def_id, true),
538         config::EntryStart => create_entry_fn(cx, span, main_llfn, main_def_id, false),
539         config::EntryNone => {}    // Do nothing.
540     }
541
542     fn create_entry_fn<'cx>(cx: &'cx CodegenCx,
543                        sp: Span,
544                        rust_main: ValueRef,
545                        rust_main_def_id: DefId,
546                        use_start_lang_item: bool) {
547         let llfty = Type::func(&[Type::c_int(cx), Type::i8p(cx).ptr_to()], &Type::c_int(cx));
548
549         let main_ret_ty = cx.tcx.fn_sig(rust_main_def_id).output();
550         // Given that `main()` has no arguments,
551         // then its return type cannot have
552         // late-bound regions, since late-bound
553         // regions must appear in the argument
554         // listing.
555         let main_ret_ty = main_ret_ty.no_late_bound_regions().unwrap();
556
557         if declare::get_defined_value(cx, "main").is_some() {
558             // FIXME: We should be smart and show a better diagnostic here.
559             cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
560                       .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
561                       .emit();
562             cx.sess().abort_if_errors();
563             bug!();
564         }
565         let llfn = declare::declare_cfn(cx, "main", llfty);
566
567         // `main` should respect same config for frame pointer elimination as rest of code
568         attributes::set_frame_pointer_elimination(cx, llfn);
569
570         let bx = Builder::new_block(cx, llfn, "top");
571
572         debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(&bx);
573
574         // Params from native main() used as args for rust start function
575         let param_argc = get_param(llfn, 0);
576         let param_argv = get_param(llfn, 1);
577         let arg_argc = bx.intcast(param_argc, cx.isize_ty, true);
578         let arg_argv = param_argv;
579
580         let (start_fn, args) = if use_start_lang_item {
581             let start_def_id = cx.tcx.require_lang_item(StartFnLangItem);
582             let start_fn = callee::resolve_and_get_fn(cx, start_def_id, cx.tcx.mk_substs(
583                 iter::once(Kind::from(main_ret_ty))));
584             (start_fn, vec![bx.pointercast(rust_main, Type::i8p(cx).ptr_to()),
585                             arg_argc, arg_argv])
586         } else {
587             debug!("using user-defined start fn");
588             (rust_main, vec![arg_argc, arg_argv])
589         };
590
591         let result = bx.call(start_fn, &args, None);
592         bx.ret(bx.intcast(result, Type::c_int(cx), true));
593     }
594 }
595
596 fn contains_null(s: &str) -> bool {
597     s.bytes().any(|b| b == 0)
598 }
599
600 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
601                             llmod_id: &str,
602                             link_meta: &LinkMeta)
603                             -> (ContextRef, ModuleRef, EncodedMetadata) {
604     use std::io::Write;
605     use flate2::Compression;
606     use flate2::write::DeflateEncoder;
607
608     let (metadata_llcx, metadata_llmod) = unsafe {
609         context::create_context_and_module(tcx.sess, llmod_id)
610     };
611
612     #[derive(PartialEq, Eq, PartialOrd, Ord)]
613     enum MetadataKind {
614         None,
615         Uncompressed,
616         Compressed
617     }
618
619     let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
620         match *ty {
621             config::CrateTypeExecutable |
622             config::CrateTypeStaticlib |
623             config::CrateTypeCdylib => MetadataKind::None,
624
625             config::CrateTypeRlib => MetadataKind::Uncompressed,
626
627             config::CrateTypeDylib |
628             config::CrateTypeProcMacro => MetadataKind::Compressed,
629         }
630     }).max().unwrap();
631
632     if kind == MetadataKind::None {
633         return (metadata_llcx,
634                 metadata_llmod,
635                 EncodedMetadata::new());
636     }
637
638     let metadata = tcx.encode_metadata(link_meta);
639     if kind == MetadataKind::Uncompressed {
640         return (metadata_llcx, metadata_llmod, metadata);
641     }
642
643     assert!(kind == MetadataKind::Compressed);
644     let mut compressed = tcx.metadata_encoding_version();
645     DeflateEncoder::new(&mut compressed, Compression::fast())
646         .write_all(&metadata.raw_data).unwrap();
647
648     let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
649     let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
650     let name = exported_symbols::metadata_symbol_name(tcx);
651     let buf = CString::new(name).unwrap();
652     let llglobal = unsafe {
653         llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
654     };
655     unsafe {
656         llvm::LLVMSetInitializer(llglobal, llconst);
657         let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
658         let name = CString::new(section_name).unwrap();
659         llvm::LLVMSetSection(llglobal, name.as_ptr());
660
661         // Also generate a .section directive to force no
662         // flags, at least for ELF outputs, so that the
663         // metadata doesn't get loaded into memory.
664         let directive = format!(".section {}", section_name);
665         let directive = CString::new(directive).unwrap();
666         llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
667     }
668     return (metadata_llcx, metadata_llmod, metadata);
669 }
670
671 pub struct ValueIter {
672     cur: ValueRef,
673     step: unsafe extern "C" fn(ValueRef) -> ValueRef,
674 }
675
676 impl Iterator for ValueIter {
677     type Item = ValueRef;
678
679     fn next(&mut self) -> Option<ValueRef> {
680         let old = self.cur;
681         if !old.is_null() {
682             self.cur = unsafe { (self.step)(old) };
683             Some(old)
684         } else {
685             None
686         }
687     }
688 }
689
690 pub fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
691     unsafe {
692         ValueIter {
693             cur: llvm::LLVMGetFirstGlobal(llmod),
694             step: llvm::LLVMGetNextGlobal,
695         }
696     }
697 }
698
699 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
700                              rx: mpsc::Receiver<Box<Any + Send>>)
701                              -> OngoingCrateTranslation {
702
703     check_for_rustc_errors_attr(tcx);
704
705     if let Some(true) = tcx.sess.opts.debugging_opts.thinlto {
706         if unsafe { !llvm::LLVMRustThinLTOAvailable() } {
707             tcx.sess.fatal("this compiler's LLVM does not support ThinLTO");
708         }
709     }
710
711     let crate_hash = tcx.crate_hash(LOCAL_CRATE);
712     let link_meta = link::build_link_meta(crate_hash);
713
714     // Translate the metadata.
715     let llmod_id = "metadata";
716     let (metadata_llcx, metadata_llmod, metadata) =
717         time(tcx.sess, "write metadata", || {
718             write_metadata(tcx, llmod_id, &link_meta)
719         });
720
721     let metadata_module = ModuleTranslation {
722         name: link::METADATA_MODULE_NAME.to_string(),
723         llmod_id: llmod_id.to_string(),
724         source: ModuleSource::Translated(ModuleLlvm {
725             llcx: metadata_llcx,
726             llmod: metadata_llmod,
727             tm: create_target_machine(tcx.sess),
728         }),
729         kind: ModuleKind::Metadata,
730     };
731
732     let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
733         Some(time_graph::TimeGraph::new())
734     } else {
735         None
736     };
737
738     // Skip crate items and just output metadata in -Z no-trans mode.
739     if tcx.sess.opts.debugging_opts.no_trans ||
740        !tcx.sess.opts.output_types.should_trans() {
741         let ongoing_translation = write::start_async_translation(
742             tcx,
743             time_graph.clone(),
744             link_meta,
745             metadata,
746             rx,
747             1);
748
749         ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
750         ongoing_translation.translation_finished(tcx);
751
752         assert_and_save_dep_graph(tcx);
753
754         ongoing_translation.check_for_errors(tcx.sess);
755
756         return ongoing_translation;
757     }
758
759     // Run the translation item collector and partition the collected items into
760     // codegen units.
761     let codegen_units =
762         tcx.collect_and_partition_translation_items(LOCAL_CRATE).1;
763     let codegen_units = (*codegen_units).clone();
764
765     // Force all codegen_unit queries so they are already either red or green
766     // when compile_codegen_unit accesses them. We are not able to re-execute
767     // the codegen_unit query from just the DepNode, so an unknown color would
768     // lead to having to re-execute compile_codegen_unit, possibly
769     // unnecessarily.
770     if tcx.dep_graph.is_fully_enabled() {
771         for cgu in &codegen_units {
772             tcx.codegen_unit(cgu.name().clone());
773         }
774     }
775
776     let ongoing_translation = write::start_async_translation(
777         tcx,
778         time_graph.clone(),
779         link_meta,
780         metadata,
781         rx,
782         codegen_units.len());
783
784     // Translate an allocator shim, if any
785     let allocator_module = if let Some(kind) = tcx.sess.allocator_kind.get() {
786         unsafe {
787             let llmod_id = "allocator";
788             let (llcx, llmod) =
789                 context::create_context_and_module(tcx.sess, llmod_id);
790             let modules = ModuleLlvm {
791                 llmod,
792                 llcx,
793                 tm: create_target_machine(tcx.sess),
794             };
795             time(tcx.sess, "write allocator module", || {
796                 allocator::trans(tcx, &modules, kind)
797             });
798
799             Some(ModuleTranslation {
800                 name: link::ALLOCATOR_MODULE_NAME.to_string(),
801                 llmod_id: llmod_id.to_string(),
802                 source: ModuleSource::Translated(modules),
803                 kind: ModuleKind::Allocator,
804             })
805         }
806     } else {
807         None
808     };
809
810     if let Some(allocator_module) = allocator_module {
811         ongoing_translation.submit_pre_translated_module_to_llvm(tcx, allocator_module);
812     }
813
814     ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
815
816     // We sort the codegen units by size. This way we can schedule work for LLVM
817     // a bit more efficiently.
818     let codegen_units = {
819         let mut codegen_units = codegen_units;
820         codegen_units.sort_by_key(|cgu| usize::MAX - cgu.size_estimate());
821         codegen_units
822     };
823
824     let mut total_trans_time = Duration::new(0, 0);
825     let mut all_stats = Stats::default();
826
827     for cgu in codegen_units.into_iter() {
828         ongoing_translation.wait_for_signal_to_translate_item();
829         ongoing_translation.check_for_errors(tcx.sess);
830
831         // First, if incremental compilation is enabled, we try to re-use the
832         // codegen unit from the cache.
833         if tcx.dep_graph.is_fully_enabled() {
834             let cgu_id = cgu.work_product_id();
835
836             // Check whether there is a previous work-product we can
837             // re-use.  Not only must the file exist, and the inputs not
838             // be dirty, but the hash of the symbols we will generate must
839             // be the same.
840             if let Some(buf) = tcx.dep_graph.previous_work_product(&cgu_id) {
841                 let dep_node = &DepNode::new(tcx,
842                     DepConstructor::CompileCodegenUnit(cgu.name().clone()));
843
844                 // We try to mark the DepNode::CompileCodegenUnit green. If we
845                 // succeed it means that none of the dependencies has changed
846                 // and we can safely re-use.
847                 if let Some(dep_node_index) = tcx.dep_graph.try_mark_green(tcx, dep_node) {
848                     // Append ".rs" to LLVM module identifier.
849                     //
850                     // LLVM code generator emits a ".file filename" directive
851                     // for ELF backends. Value of the "filename" is set as the
852                     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
853                     // crashes if the module identifier is same as other symbols
854                     // such as a function name in the module.
855                     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
856                     let llmod_id = format!("{}.rs", cgu.name());
857
858                     let module = ModuleTranslation {
859                         name: cgu.name().to_string(),
860                         source: ModuleSource::Preexisting(buf),
861                         kind: ModuleKind::Regular,
862                         llmod_id,
863                     };
864                     tcx.dep_graph.mark_loaded_from_cache(dep_node_index, true);
865                     write::submit_translated_module_to_llvm(tcx, module, 0);
866                     // Continue to next cgu, this one is done.
867                     continue
868                 }
869             } else {
870                 // This can happen if files were  deleted from the cache
871                 // directory for some reason. We just re-compile then.
872             }
873         }
874
875         let _timing_guard = time_graph.as_ref().map(|time_graph| {
876             time_graph.start(write::TRANS_WORKER_TIMELINE,
877                              write::TRANS_WORK_PACKAGE_KIND,
878                              &format!("codegen {}", cgu.name()))
879         });
880         let start_time = Instant::now();
881         all_stats.extend(tcx.compile_codegen_unit(*cgu.name()));
882         total_trans_time += start_time.elapsed();
883         ongoing_translation.check_for_errors(tcx.sess);
884     }
885
886     ongoing_translation.translation_finished(tcx);
887
888     // Since the main thread is sometimes blocked during trans, we keep track
889     // -Ztime-passes output manually.
890     print_time_passes_entry(tcx.sess.time_passes(),
891                             "translate to LLVM IR",
892                             total_trans_time);
893
894     if tcx.sess.opts.incremental.is_some() {
895         ::rustc_incremental::assert_module_sources::assert_module_sources(tcx);
896     }
897
898     symbol_names_test::report_symbol_names(tcx);
899
900     if tcx.sess.trans_stats() {
901         println!("--- trans stats ---");
902         println!("n_glues_created: {}", all_stats.n_glues_created);
903         println!("n_null_glues: {}", all_stats.n_null_glues);
904         println!("n_real_glues: {}", all_stats.n_real_glues);
905
906         println!("n_fns: {}", all_stats.n_fns);
907         println!("n_inlines: {}", all_stats.n_inlines);
908         println!("n_closures: {}", all_stats.n_closures);
909         println!("fn stats:");
910         all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
911         for &(ref name, insns) in all_stats.fn_stats.iter() {
912             println!("{} insns, {}", insns, *name);
913         }
914     }
915
916     if tcx.sess.count_llvm_insns() {
917         for (k, v) in all_stats.llvm_insns.iter() {
918             println!("{:7} {}", *v, *k);
919         }
920     }
921
922     ongoing_translation.check_for_errors(tcx.sess);
923
924     assert_and_save_dep_graph(tcx);
925     ongoing_translation
926 }
927
928 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
929     time(tcx.sess,
930          "assert dep graph",
931          || rustc_incremental::assert_dep_graph(tcx));
932
933     time(tcx.sess,
934          "serialize dep graph",
935          || rustc_incremental::save_dep_graph(tcx));
936 }
937
938 fn collect_and_partition_translation_items<'a, 'tcx>(
939     tcx: TyCtxt<'a, 'tcx, 'tcx>,
940     cnum: CrateNum,
941 ) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
942 {
943     assert_eq!(cnum, LOCAL_CRATE);
944
945     let collection_mode = match tcx.sess.opts.debugging_opts.print_trans_items {
946         Some(ref s) => {
947             let mode_string = s.to_lowercase();
948             let mode_string = mode_string.trim();
949             if mode_string == "eager" {
950                 MonoItemCollectionMode::Eager
951             } else {
952                 if mode_string != "lazy" {
953                     let message = format!("Unknown codegen-item collection mode '{}'. \
954                                            Falling back to 'lazy' mode.",
955                                            mode_string);
956                     tcx.sess.warn(&message);
957                 }
958
959                 MonoItemCollectionMode::Lazy
960             }
961         }
962         None => {
963             if tcx.sess.opts.cg.link_dead_code {
964                 MonoItemCollectionMode::Eager
965             } else {
966                 MonoItemCollectionMode::Lazy
967             }
968         }
969     };
970
971     let (items, inlining_map) =
972         time(tcx.sess, "translation item collection", || {
973             collector::collect_crate_mono_items(tcx, collection_mode)
974     });
975
976     tcx.sess.abort_if_errors();
977
978     ::rustc_mir::monomorphize::assert_symbols_are_distinct(tcx, items.iter());
979
980     let strategy = if tcx.sess.opts.incremental.is_some() {
981         PartitioningStrategy::PerModule
982     } else {
983         PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
984     };
985
986     let codegen_units = time(tcx.sess, "codegen unit partitioning", || {
987         partitioning::partition(tcx,
988                                 items.iter().cloned(),
989                                 strategy,
990                                 &inlining_map)
991             .into_iter()
992             .map(Arc::new)
993             .collect::<Vec<_>>()
994     });
995
996     let translation_items: DefIdSet = items.iter().filter_map(|trans_item| {
997         match *trans_item {
998             MonoItem::Fn(ref instance) => Some(instance.def_id()),
999             MonoItem::Static(def_id) => Some(def_id),
1000             _ => None,
1001         }
1002     }).collect();
1003
1004     if tcx.sess.opts.debugging_opts.print_trans_items.is_some() {
1005         let mut item_to_cgus = FxHashMap();
1006
1007         for cgu in &codegen_units {
1008             for (&trans_item, &linkage) in cgu.items() {
1009                 item_to_cgus.entry(trans_item)
1010                             .or_insert(Vec::new())
1011                             .push((cgu.name().clone(), linkage));
1012             }
1013         }
1014
1015         let mut item_keys: Vec<_> = items
1016             .iter()
1017             .map(|i| {
1018                 let mut output = i.to_string(tcx);
1019                 output.push_str(" @@");
1020                 let mut empty = Vec::new();
1021                 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1022                 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1023                 cgus.dedup();
1024                 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1025                     output.push_str(" ");
1026                     output.push_str(&cgu_name);
1027
1028                     let linkage_abbrev = match linkage {
1029                         Linkage::External => "External",
1030                         Linkage::AvailableExternally => "Available",
1031                         Linkage::LinkOnceAny => "OnceAny",
1032                         Linkage::LinkOnceODR => "OnceODR",
1033                         Linkage::WeakAny => "WeakAny",
1034                         Linkage::WeakODR => "WeakODR",
1035                         Linkage::Appending => "Appending",
1036                         Linkage::Internal => "Internal",
1037                         Linkage::Private => "Private",
1038                         Linkage::ExternalWeak => "ExternalWeak",
1039                         Linkage::Common => "Common",
1040                     };
1041
1042                     output.push_str("[");
1043                     output.push_str(linkage_abbrev);
1044                     output.push_str("]");
1045                 }
1046                 output
1047             })
1048             .collect();
1049
1050         item_keys.sort();
1051
1052         for item in item_keys {
1053             println!("TRANS_ITEM {}", item);
1054         }
1055     }
1056
1057     (Arc::new(translation_items), Arc::new(codegen_units))
1058 }
1059
1060 impl CrateInfo {
1061     pub fn new(tcx: TyCtxt) -> CrateInfo {
1062         let mut info = CrateInfo {
1063             panic_runtime: None,
1064             compiler_builtins: None,
1065             profiler_runtime: None,
1066             sanitizer_runtime: None,
1067             is_no_builtins: FxHashSet(),
1068             native_libraries: FxHashMap(),
1069             used_libraries: tcx.native_libraries(LOCAL_CRATE),
1070             link_args: tcx.link_args(LOCAL_CRATE),
1071             crate_name: FxHashMap(),
1072             used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1073             used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1074             used_crate_source: FxHashMap(),
1075             wasm_custom_sections: BTreeMap::new(),
1076             wasm_imports: FxHashMap(),
1077         };
1078
1079         let load_wasm_items = tcx.sess.crate_types.borrow()
1080             .iter()
1081             .any(|c| *c != config::CrateTypeRlib) &&
1082             tcx.sess.opts.target_triple == "wasm32-unknown-unknown";
1083
1084         if load_wasm_items {
1085             info!("attempting to load all wasm sections");
1086             for &id in tcx.wasm_custom_sections(LOCAL_CRATE).iter() {
1087                 let (name, contents) = fetch_wasm_section(tcx, id);
1088                 info.wasm_custom_sections.entry(name)
1089                     .or_insert(Vec::new())
1090                     .extend(contents);
1091             }
1092             info.load_wasm_imports(tcx, LOCAL_CRATE);
1093         }
1094
1095         for &cnum in tcx.crates().iter() {
1096             info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1097             info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1098             info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1099             if tcx.is_panic_runtime(cnum) {
1100                 info.panic_runtime = Some(cnum);
1101             }
1102             if tcx.is_compiler_builtins(cnum) {
1103                 info.compiler_builtins = Some(cnum);
1104             }
1105             if tcx.is_profiler_runtime(cnum) {
1106                 info.profiler_runtime = Some(cnum);
1107             }
1108             if tcx.is_sanitizer_runtime(cnum) {
1109                 info.sanitizer_runtime = Some(cnum);
1110             }
1111             if tcx.is_no_builtins(cnum) {
1112                 info.is_no_builtins.insert(cnum);
1113             }
1114             if load_wasm_items {
1115                 for &id in tcx.wasm_custom_sections(cnum).iter() {
1116                     let (name, contents) = fetch_wasm_section(tcx, id);
1117                     info.wasm_custom_sections.entry(name)
1118                         .or_insert(Vec::new())
1119                         .extend(contents);
1120                 }
1121                 info.load_wasm_imports(tcx, cnum);
1122             }
1123         }
1124
1125         return info
1126     }
1127
1128     fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
1129         for (&id, module) in tcx.wasm_import_module_map(cnum).iter() {
1130             let instance = Instance::mono(tcx, id);
1131             let import_name = tcx.symbol_name(instance);
1132             self.wasm_imports.insert(import_name.to_string(), module.clone());
1133         }
1134     }
1135 }
1136
1137 fn is_translated_item(tcx: TyCtxt, id: DefId) -> bool {
1138     let (all_trans_items, _) =
1139         tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1140     all_trans_items.contains(&id)
1141 }
1142
1143 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1144                                   cgu: InternedString) -> Stats {
1145     let cgu = tcx.codegen_unit(cgu);
1146
1147     let start_time = Instant::now();
1148     let (stats, module) = module_translation(tcx, cgu);
1149     let time_to_translate = start_time.elapsed();
1150
1151     // We assume that the cost to run LLVM on a CGU is proportional to
1152     // the time we needed for translating it.
1153     let cost = time_to_translate.as_secs() * 1_000_000_000 +
1154                time_to_translate.subsec_nanos() as u64;
1155
1156     write::submit_translated_module_to_llvm(tcx,
1157                                             module,
1158                                             cost);
1159     return stats;
1160
1161     fn module_translation<'a, 'tcx>(
1162         tcx: TyCtxt<'a, 'tcx, 'tcx>,
1163         cgu: Arc<CodegenUnit<'tcx>>)
1164         -> (Stats, ModuleTranslation)
1165     {
1166         let cgu_name = cgu.name().to_string();
1167
1168         // Append ".rs" to LLVM module identifier.
1169         //
1170         // LLVM code generator emits a ".file filename" directive
1171         // for ELF backends. Value of the "filename" is set as the
1172         // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
1173         // crashes if the module identifier is same as other symbols
1174         // such as a function name in the module.
1175         // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
1176         let llmod_id = format!("{}-{}.rs",
1177                                cgu.name(),
1178                                tcx.crate_disambiguator(LOCAL_CRATE)
1179                                    .to_fingerprint().to_hex());
1180
1181         // Instantiate translation items without filling out definitions yet...
1182         let cx = CodegenCx::new(tcx, cgu, &llmod_id);
1183         let module = {
1184             let trans_items = cx.codegen_unit
1185                                  .items_in_deterministic_order(cx.tcx);
1186             for &(trans_item, (linkage, visibility)) in &trans_items {
1187                 trans_item.predefine(&cx, linkage, visibility);
1188             }
1189
1190             // ... and now that we have everything pre-defined, fill out those definitions.
1191             for &(trans_item, _) in &trans_items {
1192                 trans_item.define(&cx);
1193             }
1194
1195             // If this codegen unit contains the main function, also create the
1196             // wrapper here
1197             maybe_create_entry_wrapper(&cx);
1198
1199             // Run replace-all-uses-with for statics that need it
1200             for &(old_g, new_g) in cx.statics_to_rauw.borrow().iter() {
1201                 unsafe {
1202                     let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1203                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1204                     llvm::LLVMDeleteGlobal(old_g);
1205                 }
1206             }
1207
1208             // Create the llvm.used variable
1209             // This variable has type [N x i8*] and is stored in the llvm.metadata section
1210             if !cx.used_statics.borrow().is_empty() {
1211                 let name = CString::new("llvm.used").unwrap();
1212                 let section = CString::new("llvm.metadata").unwrap();
1213                 let array = C_array(Type::i8(&cx).ptr_to(), &*cx.used_statics.borrow());
1214
1215                 unsafe {
1216                     let g = llvm::LLVMAddGlobal(cx.llmod,
1217                                                 val_ty(array).to_ref(),
1218                                                 name.as_ptr());
1219                     llvm::LLVMSetInitializer(g, array);
1220                     llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1221                     llvm::LLVMSetSection(g, section.as_ptr());
1222                 }
1223             }
1224
1225             // Finalize debuginfo
1226             if cx.sess().opts.debuginfo != NoDebugInfo {
1227                 debuginfo::finalize(&cx);
1228             }
1229
1230             let llvm_module = ModuleLlvm {
1231                 llcx: cx.llcx,
1232                 llmod: cx.llmod,
1233                 tm: create_target_machine(cx.sess()),
1234             };
1235
1236             ModuleTranslation {
1237                 name: cgu_name,
1238                 source: ModuleSource::Translated(llvm_module),
1239                 kind: ModuleKind::Regular,
1240                 llmod_id,
1241             }
1242         };
1243
1244         (cx.into_stats(), module)
1245     }
1246 }
1247
1248 pub fn provide(providers: &mut Providers) {
1249     providers.collect_and_partition_translation_items =
1250         collect_and_partition_translation_items;
1251
1252     providers.is_translated_item = is_translated_item;
1253
1254     providers.codegen_unit = |tcx, name| {
1255         let (_, all) = tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1256         all.iter()
1257             .find(|cgu| *cgu.name() == name)
1258             .cloned()
1259             .expect(&format!("failed to find cgu with name {:?}", name))
1260     };
1261     providers.compile_codegen_unit = compile_codegen_unit;
1262
1263     provide_extern(providers);
1264 }
1265
1266 pub fn provide_extern(providers: &mut Providers) {
1267     providers.dllimport_foreign_items = |tcx, krate| {
1268         let module_map = tcx.foreign_modules(krate);
1269         let module_map = module_map.iter()
1270             .map(|lib| (lib.def_id, lib))
1271             .collect::<FxHashMap<_, _>>();
1272
1273         let dllimports = tcx.native_libraries(krate)
1274             .iter()
1275             .filter(|lib| {
1276                 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
1277                     return false
1278                 }
1279                 let cfg = match lib.cfg {
1280                     Some(ref cfg) => cfg,
1281                     None => return true,
1282                 };
1283                 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
1284             })
1285             .filter_map(|lib| lib.foreign_module)
1286             .map(|id| &module_map[&id])
1287             .flat_map(|module| module.foreign_items.iter().cloned())
1288             .collect();
1289         Lrc::new(dllimports)
1290     };
1291
1292     providers.is_dllimport_foreign_item = |tcx, def_id| {
1293         tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
1294     };
1295 }
1296
1297 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1298     match linkage {
1299         Linkage::External => llvm::Linkage::ExternalLinkage,
1300         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1301         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1302         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1303         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1304         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1305         Linkage::Appending => llvm::Linkage::AppendingLinkage,
1306         Linkage::Internal => llvm::Linkage::InternalLinkage,
1307         Linkage::Private => llvm::Linkage::PrivateLinkage,
1308         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1309         Linkage::Common => llvm::Linkage::CommonLinkage,
1310     }
1311 }
1312
1313 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1314     match linkage {
1315         Visibility::Default => llvm::Visibility::Default,
1316         Visibility::Hidden => llvm::Visibility::Hidden,
1317         Visibility::Protected => llvm::Visibility::Protected,
1318     }
1319 }
1320
1321 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1322 //            the HashStable trait. Normally DepGraph::with_task() calls are
1323 //            hidden behind queries, but CGU creation is a special case in two
1324 //            ways: (1) it's not a query and (2) CGU are output nodes, so their
1325 //            Fingerprints are not actually needed. It remains to be clarified
1326 //            how exactly this case will be handled in the red/green system but
1327 //            for now we content ourselves with providing a no-op HashStable
1328 //            implementation for CGUs.
1329 mod temp_stable_hash_impls {
1330     use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1331                                                HashStable};
1332     use ModuleTranslation;
1333
1334     impl<HCX> HashStable<HCX> for ModuleTranslation {
1335         fn hash_stable<W: StableHasherResult>(&self,
1336                                               _: &mut HCX,
1337                                               _: &mut StableHasher<W>) {
1338             // do nothing
1339         }
1340     }
1341 }
1342
1343 fn fetch_wasm_section(tcx: TyCtxt, id: DefId) -> (String, Vec<u8>) {
1344     use rustc::mir::interpret::{GlobalId, Value, PrimVal};
1345     use rustc::middle::const_val::ConstVal;
1346
1347     info!("loading wasm section {:?}", id);
1348
1349     let section = tcx.get_attrs(id)
1350         .iter()
1351         .find(|a| a.check_name("wasm_custom_section"))
1352         .expect("missing #[wasm_custom_section] attribute")
1353         .value_str()
1354         .expect("malformed #[wasm_custom_section] attribute");
1355
1356     let instance = ty::Instance::mono(tcx, id);
1357     let cid = GlobalId {
1358         instance,
1359         promoted: None
1360     };
1361     let param_env = ty::ParamEnv::reveal_all();
1362     let val = tcx.const_eval(param_env.and(cid)).unwrap();
1363
1364     let val = match val.val {
1365         ConstVal::Value(val) => val,
1366         ConstVal::Unevaluated(..) => bug!("should be evaluated"),
1367     };
1368     let val = match val {
1369         Value::ByRef(ptr, _align) => ptr.into_inner_primval(),
1370         ref v => bug!("should be ByRef, was {:?}", v),
1371     };
1372     let mem = match val {
1373         PrimVal::Ptr(mem) => mem,
1374         ref v => bug!("should be Ptr, was {:?}", v),
1375     };
1376     assert_eq!(mem.offset, 0);
1377     let alloc = tcx
1378         .interpret_interner
1379         .get_alloc(mem.alloc_id)
1380         .expect("miri allocation never successfully created");
1381     (section.to_string(), alloc.bytes.clone())
1382 }