]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/base.rs
Rollup merge of #40056 - keeperofdakeys:contributing, r=alexcrichton
[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::CrateTranslation;
27 use super::ModuleLlvm;
28 use super::ModuleSource;
29 use super::ModuleTranslation;
30
31 use assert_module_sources;
32 use back::link;
33 use back::linker::LinkerInfo;
34 use back::symbol_export::{self, ExportedSymbols};
35 use llvm::{Linkage, ValueRef, Vector, get_param};
36 use llvm;
37 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
38 use middle::lang_items::StartFnLangItem;
39 use rustc::ty::subst::Substs;
40 use rustc::mir::tcx::LvalueTy;
41 use rustc::traits;
42 use rustc::ty::{self, Ty, TyCtxt};
43 use rustc::ty::adjustment::CustomCoerceUnsized;
44 use rustc::dep_graph::{DepNode, WorkProduct};
45 use rustc::hir::map as hir_map;
46 use rustc::util::common::time;
47 use session::config::{self, NoDebugInfo};
48 use rustc_incremental::IncrementalHashesMap;
49 use session::{self, DataTypeKind, Session};
50 use abi::{self, FnType};
51 use mir::lvalue::LvalueRef;
52 use adt;
53 use attributes;
54 use builder::Builder;
55 use callee::{Callee};
56 use common::{C_bool, C_bytes_in_context, C_i32, C_uint};
57 use collector::{self, TransItemCollectionMode};
58 use common::{C_struct_in_context, C_u64, C_undef};
59 use common::CrateContext;
60 use common::{fulfill_obligation};
61 use common::{type_is_zero_size, val_ty};
62 use common;
63 use consts;
64 use context::{SharedCrateContext, CrateContextList};
65 use debuginfo;
66 use declare;
67 use machine;
68 use machine::{llalign_of_min, llsize_of};
69 use meth;
70 use mir;
71 use monomorphize::{self, Instance};
72 use partitioning::{self, PartitioningStrategy, CodegenUnit};
73 use symbol_map::SymbolMap;
74 use symbol_names_test;
75 use trans_item::{TransItem, DefPathBasedNames};
76 use type_::Type;
77 use type_of;
78 use value::Value;
79 use Disr;
80 use util::nodemap::{NodeSet, FxHashMap, FxHashSet};
81
82 use libc::c_uint;
83 use std::ffi::{CStr, CString};
84 use std::rc::Rc;
85 use std::str;
86 use std::i32;
87 use syntax_pos::{Span, DUMMY_SP};
88 use syntax::attr;
89 use rustc::hir;
90 use rustc::ty::layout::{self, Layout};
91 use syntax::ast;
92
93 use mir::lvalue::Alignment;
94
95 pub struct StatRecorder<'a, 'tcx: 'a> {
96     ccx: &'a CrateContext<'a, 'tcx>,
97     name: Option<String>,
98     istart: usize,
99 }
100
101 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
102     pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
103         let istart = ccx.stats().n_llvm_insns.get();
104         StatRecorder {
105             ccx: ccx,
106             name: Some(name),
107             istart: istart,
108         }
109     }
110 }
111
112 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
113     fn drop(&mut self) {
114         if self.ccx.sess().trans_stats() {
115             let iend = self.ccx.stats().n_llvm_insns.get();
116             self.ccx.stats().fn_stats.borrow_mut()
117                 .push((self.name.take().unwrap(), iend - self.istart));
118             self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
119             // Reset LLVM insn count to avoid compound costs.
120             self.ccx.stats().n_llvm_insns.set(self.istart);
121         }
122     }
123 }
124
125 pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
126     bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
127 }
128
129 pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
130     bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
131 }
132
133 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
134                                 signed: bool)
135                                 -> llvm::IntPredicate {
136     match op {
137         hir::BiEq => llvm::IntEQ,
138         hir::BiNe => llvm::IntNE,
139         hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
140         hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
141         hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
142         hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
143         op => {
144             bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
145                   found {:?}",
146                  op)
147         }
148     }
149 }
150
151 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
152     match op {
153         hir::BiEq => llvm::RealOEQ,
154         hir::BiNe => llvm::RealUNE,
155         hir::BiLt => llvm::RealOLT,
156         hir::BiLe => llvm::RealOLE,
157         hir::BiGt => llvm::RealOGT,
158         hir::BiGe => llvm::RealOGE,
159         op => {
160             bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
161                   found {:?}",
162                  op);
163         }
164     }
165 }
166
167 pub fn compare_simd_types<'a, 'tcx>(
168     bcx: &Builder<'a, 'tcx>,
169     lhs: ValueRef,
170     rhs: ValueRef,
171     t: Ty<'tcx>,
172     ret_ty: Type,
173     op: hir::BinOp_
174 ) -> ValueRef {
175     let signed = match t.sty {
176         ty::TyFloat(_) => {
177             let cmp = bin_op_to_fcmp_predicate(op);
178             return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
179         },
180         ty::TyUint(_) => false,
181         ty::TyInt(_) => true,
182         _ => bug!("compare_simd_types: invalid SIMD type"),
183     };
184
185     let cmp = bin_op_to_icmp_predicate(op, signed);
186     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
187     // to get the correctly sized type. This will compile to a single instruction
188     // once the IR is converted to assembly if the SIMD instruction is supported
189     // by the target architecture.
190     bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
191 }
192
193 /// Retrieve the information we are losing (making dynamic) in an unsizing
194 /// adjustment.
195 ///
196 /// The `old_info` argument is a bit funny. It is intended for use
197 /// in an upcast, where the new vtable for an object will be drived
198 /// from the old one.
199 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
200                                 source: Ty<'tcx>,
201                                 target: Ty<'tcx>,
202                                 old_info: Option<ValueRef>)
203                                 -> ValueRef {
204     let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
205     match (&source.sty, &target.sty) {
206         (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
207         (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
208             // For now, upcasts are limited to changes in marker
209             // traits, and hence never actually require an actual
210             // change to the vtable.
211             old_info.expect("unsized_info: missing old info for trait upcast")
212         }
213         (_, &ty::TyDynamic(ref data, ..)) => {
214             consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
215                             Type::vtable_ptr(ccx))
216         }
217         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
218                                      source,
219                                      target),
220     }
221 }
222
223 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
224 pub fn unsize_thin_ptr<'a, 'tcx>(
225     bcx: &Builder<'a, 'tcx>,
226     src: ValueRef,
227     src_ty: Ty<'tcx>,
228     dst_ty: Ty<'tcx>
229 ) -> (ValueRef, ValueRef) {
230     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
231     match (&src_ty.sty, &dst_ty.sty) {
232         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
233          &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
234         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
235          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
236         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
237          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
238             assert!(bcx.ccx.shared().type_is_sized(a));
239             let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
240             (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
241         }
242         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
243             let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
244             assert!(bcx.ccx.shared().type_is_sized(a));
245             let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
246             (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
247         }
248         _ => bug!("unsize_thin_ptr: called on bad types"),
249     }
250 }
251
252 /// Coerce `src`, which is a reference to a value of type `src_ty`,
253 /// to a value of type `dst_ty` and store the result in `dst`
254 pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
255                                      src: &LvalueRef<'tcx>,
256                                      dst: &LvalueRef<'tcx>) {
257     let src_ty = src.ty.to_ty(bcx.tcx());
258     let dst_ty = dst.ty.to_ty(bcx.tcx());
259     let coerce_ptr = || {
260         let (base, info) = if common::type_is_fat_ptr(bcx.ccx, src_ty) {
261             // fat-ptr to fat-ptr unsize preserves the vtable
262             // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
263             // So we need to pointercast the base to ensure
264             // the types match up.
265             let (base, info) = load_fat_ptr(bcx, src.llval, src.alignment, src_ty);
266             let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, dst_ty);
267             let base = bcx.pointercast(base, llcast_ty);
268             (base, info)
269         } else {
270             let base = load_ty(bcx, src.llval, src.alignment, src_ty);
271             unsize_thin_ptr(bcx, base, src_ty, dst_ty)
272         };
273         store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
274     };
275     match (&src_ty.sty, &dst_ty.sty) {
276         (&ty::TyRef(..), &ty::TyRef(..)) |
277         (&ty::TyRef(..), &ty::TyRawPtr(..)) |
278         (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
279             coerce_ptr()
280         }
281         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
282             coerce_ptr()
283         }
284
285         (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
286             assert_eq!(def_a, def_b);
287
288             let src_fields = def_a.variants[0].fields.iter().map(|f| {
289                 monomorphize::field_ty(bcx.tcx(), substs_a, f)
290             });
291             let dst_fields = def_b.variants[0].fields.iter().map(|f| {
292                 monomorphize::field_ty(bcx.tcx(), substs_b, f)
293             });
294
295             let iter = src_fields.zip(dst_fields).enumerate();
296             for (i, (src_fty, dst_fty)) in iter {
297                 if type_is_zero_size(bcx.ccx, dst_fty) {
298                     continue;
299                 }
300
301                 let (src_f, src_f_align) = src.trans_field_ptr(bcx, i);
302                 let (dst_f, dst_f_align) = dst.trans_field_ptr(bcx, i);
303                 if src_fty == dst_fty {
304                     memcpy_ty(bcx, dst_f, src_f, src_fty, None);
305                 } else {
306                     coerce_unsized_into(
307                         bcx,
308                         &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
309                         &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
310                     );
311                 }
312             }
313         }
314         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
315                   src_ty,
316                   dst_ty),
317     }
318 }
319
320 pub fn custom_coerce_unsize_info<'scx, 'tcx>(scx: &SharedCrateContext<'scx, 'tcx>,
321                                              source_ty: Ty<'tcx>,
322                                              target_ty: Ty<'tcx>)
323                                              -> CustomCoerceUnsized {
324     let trait_ref = ty::Binder(ty::TraitRef {
325         def_id: scx.tcx().lang_items.coerce_unsized_trait().unwrap(),
326         substs: scx.tcx().mk_substs_trait(source_ty, &[target_ty])
327     });
328
329     match fulfill_obligation(scx, DUMMY_SP, trait_ref) {
330         traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
331             scx.tcx().custom_coerce_unsized_kind(impl_def_id)
332         }
333         vtable => {
334             bug!("invalid CoerceUnsized vtable: {:?}", vtable);
335         }
336     }
337 }
338
339 pub fn cast_shift_expr_rhs(
340     cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
341 ) -> ValueRef {
342     cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
343 }
344
345 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
346     cast_shift_rhs(op,
347                    lhs,
348                    rhs,
349                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
350                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
351 }
352
353 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
354                         lhs: ValueRef,
355                         rhs: ValueRef,
356                         trunc: F,
357                         zext: G)
358                         -> ValueRef
359     where F: FnOnce(ValueRef, Type) -> ValueRef,
360           G: FnOnce(ValueRef, Type) -> ValueRef
361 {
362     // Shifts may have any size int on the rhs
363     if op.is_shift() {
364         let mut rhs_llty = val_ty(rhs);
365         let mut lhs_llty = val_ty(lhs);
366         if rhs_llty.kind() == Vector {
367             rhs_llty = rhs_llty.element_type()
368         }
369         if lhs_llty.kind() == Vector {
370             lhs_llty = lhs_llty.element_type()
371         }
372         let rhs_sz = rhs_llty.int_width();
373         let lhs_sz = lhs_llty.int_width();
374         if lhs_sz < rhs_sz {
375             trunc(rhs, lhs_llty)
376         } else if lhs_sz > rhs_sz {
377             // FIXME (#1877: If shifting by negative
378             // values becomes not undefined then this is wrong.
379             zext(rhs, lhs_llty)
380         } else {
381             rhs
382         }
383     } else {
384         rhs
385     }
386 }
387
388 /// Returns whether this session's target will use SEH-based unwinding.
389 ///
390 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
391 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
392 /// 64-bit MinGW) instead of "full SEH".
393 pub fn wants_msvc_seh(sess: &Session) -> bool {
394     sess.target.target.options.is_like_msvc
395 }
396
397 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
398     let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
399     b.call(assume_intrinsic, &[val], None);
400 }
401
402 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
403 /// differs from the type used for SSA values. Also handles various special cases where the type
404 /// gives us better information about what we are loading.
405 pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,
406                          alignment: Alignment, t: Ty<'tcx>) -> ValueRef {
407     let ccx = b.ccx;
408     if type_is_zero_size(ccx, t) {
409         return C_undef(type_of::type_of(ccx, t));
410     }
411
412     unsafe {
413         let global = llvm::LLVMIsAGlobalVariable(ptr);
414         if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
415             let val = llvm::LLVMGetInitializer(global);
416             if !val.is_null() {
417                 if t.is_bool() {
418                     return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
419                 }
420                 return val;
421             }
422         }
423     }
424
425     if t.is_bool() {
426         b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
427                 Type::i1(ccx))
428     } else if t.is_char() {
429         // a char is a Unicode codepoint, and so takes values from 0
430         // to 0x10FFFF inclusive only.
431         b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False, alignment.to_align())
432     } else if (t.is_region_ptr() || t.is_box()) && !common::type_is_fat_ptr(ccx, t) {
433         b.load_nonnull(ptr, alignment.to_align())
434     } else {
435         b.load(ptr, alignment.to_align())
436     }
437 }
438
439 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
440 /// differs from the type used for SSA values.
441 pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,
442                           dst_align: Alignment, t: Ty<'tcx>) {
443     debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
444
445     if common::type_is_fat_ptr(cx.ccx, t) {
446         let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
447         let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
448         store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);
449     } else {
450         cx.store(from_immediate(cx, v), dst, dst_align.to_align());
451     }
452 }
453
454 pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
455                                data: ValueRef,
456                                extra: ValueRef,
457                                dst: ValueRef,
458                                dst_align: Alignment,
459                                _ty: Ty<'tcx>) {
460     // FIXME: emit metadata
461     cx.store(data, get_dataptr(cx, dst), dst_align.to_align());
462     cx.store(extra, get_meta(cx, dst), dst_align.to_align());
463 }
464
465 pub fn load_fat_ptr<'a, 'tcx>(
466     b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx>
467 ) -> (ValueRef, ValueRef) {
468     let ptr = get_dataptr(b, src);
469     let ptr = if t.is_region_ptr() || t.is_box() {
470         b.load_nonnull(ptr, alignment.to_align())
471     } else {
472         b.load(ptr, alignment.to_align())
473     };
474
475     let meta = get_meta(b, src);
476     let meta_ty = val_ty(meta);
477     // If the 'meta' field is a pointer, it's a vtable, so use load_nonnull
478     // instead
479     let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
480         b.load_nonnull(meta, None)
481     } else {
482         b.load(meta, None)
483     };
484
485     (ptr, meta)
486 }
487
488 pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
489     if val_ty(val) == Type::i1(bcx.ccx) {
490         bcx.zext(val, Type::i8(bcx.ccx))
491     } else {
492         val
493     }
494 }
495
496 pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
497     if ty.is_bool() {
498         bcx.trunc(val, Type::i1(bcx.ccx))
499     } else {
500         val
501     }
502 }
503
504 pub enum Lifetime { Start, End }
505
506 impl Lifetime {
507     // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
508     // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
509     // and the intrinsic for `lt` and passes them to `emit`, which is in
510     // charge of generating code to call the passed intrinsic on whatever
511     // block of generated code is targetted for the intrinsic.
512     //
513     // If LLVM lifetime intrinsic support is disabled (i.e.  optimizations
514     // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
515     pub fn call(self, b: &Builder, ptr: ValueRef) {
516         if b.ccx.sess().opts.optimize == config::OptLevel::No {
517             return;
518         }
519
520         let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
521         if size == 0 {
522             return;
523         }
524
525         let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
526             Lifetime::Start => "llvm.lifetime.start",
527             Lifetime::End => "llvm.lifetime.end"
528         });
529
530         let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
531         b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
532     }
533 }
534
535 pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
536                                dst: ValueRef,
537                                src: ValueRef,
538                                n_bytes: ValueRef,
539                                align: u32) {
540     let ccx = b.ccx;
541     let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
542     let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
543     let memcpy = ccx.get_intrinsic(&key);
544     let src_ptr = b.pointercast(src, Type::i8p(ccx));
545     let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
546     let size = b.intcast(n_bytes, ccx.int_type(), false);
547     let align = C_i32(ccx, align as i32);
548     let volatile = C_bool(ccx, false);
549     b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
550 }
551
552 pub fn memcpy_ty<'a, 'tcx>(
553     bcx: &Builder<'a, 'tcx>,
554     dst: ValueRef,
555     src: ValueRef,
556     t: Ty<'tcx>,
557     align: Option<u32>,
558 ) {
559     let ccx = bcx.ccx;
560
561     if type_is_zero_size(ccx, t) {
562         return;
563     }
564
565     let llty = type_of::type_of(ccx, t);
566     let llsz = llsize_of(ccx, llty);
567     let llalign = align.unwrap_or_else(|| type_of::align_of(ccx, t));
568     call_memcpy(bcx, dst, src, llsz, llalign as u32);
569 }
570
571 pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
572                                ptr: ValueRef,
573                                fill_byte: ValueRef,
574                                size: ValueRef,
575                                align: ValueRef,
576                                volatile: bool) -> ValueRef {
577     let ptr_width = &b.ccx.sess().target.target.target_pointer_width[..];
578     let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
579     let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
580     let volatile = C_bool(b.ccx, volatile);
581     b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
582 }
583
584 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
585     let _s = if ccx.sess().trans_stats() {
586         let mut instance_name = String::new();
587         DefPathBasedNames::new(ccx.tcx(), true, true)
588             .push_def_path(instance.def, &mut instance_name);
589         Some(StatRecorder::new(ccx, instance_name))
590     } else {
591         None
592     };
593
594     // this is an info! to allow collecting monomorphization statistics
595     // and to allow finding the last function before LLVM aborts from
596     // release builds.
597     info!("trans_instance({})", instance);
598
599     let fn_ty = ccx.tcx().item_type(instance.def);
600     let fn_ty = ccx.tcx().erase_regions(&fn_ty);
601     let fn_ty = monomorphize::apply_param_substs(ccx.shared(), instance.substs, &fn_ty);
602
603     let sig = common::ty_fn_sig(ccx, fn_ty);
604     let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
605
606     let lldecl = match ccx.instances().borrow().get(&instance) {
607         Some(&val) => val,
608         None => bug!("Instance `{:?}` not already declared", instance)
609     };
610
611     ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
612
613     if !ccx.sess().no_landing_pads() {
614         attributes::emit_uwtable(lldecl, true);
615     }
616
617     let mir = ccx.tcx().item_mir(instance.def);
618     mir::trans_mir(ccx, lldecl, &mir, instance, sig);
619 }
620
621 pub fn trans_ctor_shim<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
622                                  def_id: DefId,
623                                  substs: &'tcx Substs<'tcx>,
624                                  disr: Disr,
625                                  llfn: ValueRef) {
626     attributes::inline(llfn, attributes::InlineAttr::Hint);
627     attributes::set_frame_pointer_elimination(ccx, llfn);
628
629     let ctor_ty = ccx.tcx().item_type(def_id);
630     let ctor_ty = monomorphize::apply_param_substs(ccx.shared(), substs, &ctor_ty);
631
632     let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&ctor_ty.fn_sig());
633     let fn_ty = FnType::new(ccx, sig, &[]);
634
635     let bcx = Builder::new_block(ccx, llfn, "entry-block");
636     if !fn_ty.ret.is_ignore() {
637         // But if there are no nested returns, we skip the indirection
638         // and have a single retslot
639         let dest = if fn_ty.ret.is_indirect() {
640             get_param(llfn, 0)
641         } else {
642             // We create an alloca to hold a pointer of type `ret.original_ty`
643             // which will hold the pointer to the right alloca which has the
644             // final ret value
645             bcx.alloca(fn_ty.ret.memory_ty(ccx), "sret_slot")
646         };
647         // Can return unsized value
648         let mut dest_val = LvalueRef::new_sized_ty(dest, sig.output(), Alignment::AbiAligned);
649         dest_val.ty = LvalueTy::Downcast {
650             adt_def: sig.output().ty_adt_def().unwrap(),
651             substs: substs,
652             variant_index: disr.0 as usize,
653         };
654         let mut llarg_idx = fn_ty.ret.is_indirect() as usize;
655         let mut arg_idx = 0;
656         for (i, arg_ty) in sig.inputs().iter().enumerate() {
657             let (lldestptr, _) = dest_val.trans_field_ptr(&bcx, i);
658             let arg = &fn_ty.args[arg_idx];
659             arg_idx += 1;
660             if common::type_is_fat_ptr(bcx.ccx, arg_ty) {
661                 let meta = &fn_ty.args[arg_idx];
662                 arg_idx += 1;
663                 arg.store_fn_arg(&bcx, &mut llarg_idx, get_dataptr(&bcx, lldestptr));
664                 meta.store_fn_arg(&bcx, &mut llarg_idx, get_meta(&bcx, lldestptr));
665             } else {
666                 arg.store_fn_arg(&bcx, &mut llarg_idx, lldestptr);
667             }
668         }
669         adt::trans_set_discr(&bcx, sig.output(), dest, disr);
670
671         if fn_ty.ret.is_indirect() {
672             bcx.ret_void();
673             return;
674         }
675
676         if let Some(cast_ty) = fn_ty.ret.cast {
677             bcx.ret(bcx.load(
678                 bcx.pointercast(dest, cast_ty.ptr_to()),
679                 Some(llalign_of_min(ccx, fn_ty.ret.ty))
680             ));
681         } else {
682             bcx.ret(bcx.load(dest, None))
683         }
684     } else {
685         bcx.ret_void();
686     }
687 }
688
689 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
690     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
691     // applicable to variable declarations and may not really make sense for
692     // Rust code in the first place but whitelist them anyway and trust that
693     // the user knows what s/he's doing. Who knows, unanticipated use cases
694     // may pop up in the future.
695     //
696     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
697     // and don't have to be, LLVM treats them as no-ops.
698     match name {
699         "appending" => Some(llvm::Linkage::AppendingLinkage),
700         "available_externally" => Some(llvm::Linkage::AvailableExternallyLinkage),
701         "common" => Some(llvm::Linkage::CommonLinkage),
702         "extern_weak" => Some(llvm::Linkage::ExternalWeakLinkage),
703         "external" => Some(llvm::Linkage::ExternalLinkage),
704         "internal" => Some(llvm::Linkage::InternalLinkage),
705         "linkonce" => Some(llvm::Linkage::LinkOnceAnyLinkage),
706         "linkonce_odr" => Some(llvm::Linkage::LinkOnceODRLinkage),
707         "private" => Some(llvm::Linkage::PrivateLinkage),
708         "weak" => Some(llvm::Linkage::WeakAnyLinkage),
709         "weak_odr" => Some(llvm::Linkage::WeakODRLinkage),
710         _ => None,
711     }
712 }
713
714 pub fn set_link_section(ccx: &CrateContext,
715                         llval: ValueRef,
716                         attrs: &[ast::Attribute]) {
717     if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
718         if contains_null(&sect.as_str()) {
719             ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", &sect));
720         }
721         unsafe {
722             let buf = CString::new(sect.as_str().as_bytes()).unwrap();
723             llvm::LLVMSetSection(llval, buf.as_ptr());
724         }
725     }
726 }
727
728 /// Create the `main` function which will initialise the rust runtime and call
729 /// users’ main function.
730 pub fn maybe_create_entry_wrapper(ccx: &CrateContext) {
731     let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
732         Some((id, span)) => {
733             (ccx.tcx().hir.local_def_id(id), span)
734         }
735         None => return,
736     };
737
738     // check for the #[rustc_error] annotation, which forces an
739     // error in trans. This is used to write compile-fail tests
740     // that actually test that compilation succeeds without
741     // reporting an error.
742     if ccx.tcx().has_attr(main_def_id, "rustc_error") {
743         ccx.tcx().sess.span_fatal(span, "compilation successful");
744     }
745
746     let instance = Instance::mono(ccx.shared(), main_def_id);
747
748     if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
749         // We want to create the wrapper in the same codegen unit as Rust's main
750         // function.
751         return;
752     }
753
754     let main_llfn = Callee::def(ccx, main_def_id, instance.substs).reify(ccx);
755
756     let et = ccx.sess().entry_type.get().unwrap();
757     match et {
758         config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
759         config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
760         config::EntryNone => {}    // Do nothing.
761     }
762
763     fn create_entry_fn(ccx: &CrateContext,
764                        sp: Span,
765                        rust_main: ValueRef,
766                        use_start_lang_item: bool) {
767         let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
768
769         if declare::get_defined_value(ccx, "main").is_some() {
770             // FIXME: We should be smart and show a better diagnostic here.
771             ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
772                       .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
773                       .emit();
774             ccx.sess().abort_if_errors();
775             bug!();
776         }
777         let llfn = declare::declare_cfn(ccx, "main", llfty);
778
779         // `main` should respect same config for frame pointer elimination as rest of code
780         attributes::set_frame_pointer_elimination(ccx, llfn);
781
782         let bld = Builder::new_block(ccx, llfn, "top");
783
784         debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
785
786         let (start_fn, args) = if use_start_lang_item {
787             let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
788             let empty_substs = ccx.tcx().intern_substs(&[]);
789             let start_fn = Callee::def(ccx, start_def_id, empty_substs).reify(ccx);
790             (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()), get_param(llfn, 0),
791                 get_param(llfn, 1)])
792         } else {
793             debug!("using user-defined start fn");
794             (rust_main, vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)])
795         };
796
797         let result = bld.call(start_fn, &args, None);
798         bld.ret(result);
799     }
800 }
801
802 fn contains_null(s: &str) -> bool {
803     s.bytes().any(|b| b == 0)
804 }
805
806 fn write_metadata(cx: &SharedCrateContext,
807                   exported_symbols: &NodeSet) -> Vec<u8> {
808     use flate;
809
810     #[derive(PartialEq, Eq, PartialOrd, Ord)]
811     enum MetadataKind {
812         None,
813         Uncompressed,
814         Compressed
815     }
816
817     let kind = cx.sess().crate_types.borrow().iter().map(|ty| {
818         match *ty {
819             config::CrateTypeExecutable |
820             config::CrateTypeStaticlib |
821             config::CrateTypeCdylib => MetadataKind::None,
822
823             config::CrateTypeRlib => MetadataKind::Uncompressed,
824
825             config::CrateTypeDylib |
826             config::CrateTypeProcMacro => MetadataKind::Compressed,
827         }
828     }).max().unwrap();
829
830     if kind == MetadataKind::None {
831         return Vec::new();
832     }
833
834     let cstore = &cx.tcx().sess.cstore;
835     let metadata = cstore.encode_metadata(cx.tcx(),
836                                           cx.export_map(),
837                                           cx.link_meta(),
838                                           exported_symbols);
839     if kind == MetadataKind::Uncompressed {
840         return metadata;
841     }
842
843     assert!(kind == MetadataKind::Compressed);
844     let mut compressed = cstore.metadata_encoding_version().to_vec();
845     compressed.extend_from_slice(&flate::deflate_bytes(&metadata));
846
847     let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
848     let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
849     let name = cx.metadata_symbol_name();
850     let buf = CString::new(name).unwrap();
851     let llglobal = unsafe {
852         llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf.as_ptr())
853     };
854     unsafe {
855         llvm::LLVMSetInitializer(llglobal, llconst);
856         let section_name =
857             cx.tcx().sess.cstore.metadata_section_name(&cx.sess().target.target);
858         let name = CString::new(section_name).unwrap();
859         llvm::LLVMSetSection(llglobal, name.as_ptr());
860
861         // Also generate a .section directive to force no
862         // flags, at least for ELF outputs, so that the
863         // metadata doesn't get loaded into memory.
864         let directive = format!(".section {}", section_name);
865         let directive = CString::new(directive).unwrap();
866         llvm::LLVMSetModuleInlineAsm(cx.metadata_llmod(), directive.as_ptr())
867     }
868     return metadata;
869 }
870
871 /// Find any symbols that are defined in one compilation unit, but not declared
872 /// in any other compilation unit.  Give these symbols internal linkage.
873 fn internalize_symbols<'a, 'tcx>(sess: &Session,
874                                  ccxs: &CrateContextList<'a, 'tcx>,
875                                  symbol_map: &SymbolMap<'tcx>,
876                                  exported_symbols: &ExportedSymbols) {
877     let export_threshold =
878         symbol_export::crates_export_threshold(&sess.crate_types.borrow()[..]);
879
880     let exported_symbols = exported_symbols
881         .exported_symbols(LOCAL_CRATE)
882         .iter()
883         .filter(|&&(_, export_level)| {
884             symbol_export::is_below_threshold(export_level, export_threshold)
885         })
886         .map(|&(ref name, _)| &name[..])
887         .collect::<FxHashSet<&str>>();
888
889     let scx = ccxs.shared();
890     let tcx = scx.tcx();
891
892     let incr_comp = sess.opts.debugging_opts.incremental.is_some();
893
894     // 'unsafe' because we are holding on to CStr's from the LLVM module within
895     // this block.
896     unsafe {
897         let mut referenced_somewhere = FxHashSet();
898
899         // Collect all symbols that need to stay externally visible because they
900         // are referenced via a declaration in some other codegen unit. In
901         // incremental compilation, we don't need to collect. See below for more
902         // information.
903         if !incr_comp {
904             for ccx in ccxs.iter_need_trans() {
905                 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
906                     let linkage = llvm::LLVMRustGetLinkage(val);
907                     // We only care about external declarations (not definitions)
908                     // and available_externally definitions.
909                     let is_available_externally =
910                         linkage == llvm::Linkage::AvailableExternallyLinkage;
911                     let is_decl = llvm::LLVMIsDeclaration(val) == llvm::True;
912
913                     if is_decl || is_available_externally {
914                         let symbol_name = CStr::from_ptr(llvm::LLVMGetValueName(val));
915                         referenced_somewhere.insert(symbol_name);
916                     }
917                 }
918             }
919         }
920
921         // Also collect all symbols for which we cannot adjust linkage, because
922         // it is fixed by some directive in the source code.
923         let (locally_defined_symbols, linkage_fixed_explicitly) = {
924             let mut locally_defined_symbols = FxHashSet();
925             let mut linkage_fixed_explicitly = FxHashSet();
926
927             for trans_item in scx.translation_items().borrow().iter() {
928                 let symbol_name = symbol_map.get_or_compute(scx, *trans_item);
929                 if trans_item.explicit_linkage(tcx).is_some() {
930                     linkage_fixed_explicitly.insert(symbol_name.clone());
931                 }
932                 locally_defined_symbols.insert(symbol_name);
933             }
934
935             (locally_defined_symbols, linkage_fixed_explicitly)
936         };
937
938         // Examine each external definition.  If the definition is not used in
939         // any other compilation unit, and is not reachable from other crates,
940         // then give it internal linkage.
941         for ccx in ccxs.iter_need_trans() {
942             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
943                 let linkage = llvm::LLVMRustGetLinkage(val);
944
945                 let is_externally_visible = (linkage == llvm::Linkage::ExternalLinkage) ||
946                                             (linkage == llvm::Linkage::LinkOnceODRLinkage) ||
947                                             (linkage == llvm::Linkage::WeakODRLinkage);
948
949                 if !is_externally_visible {
950                     // This symbol is not visible outside of its codegen unit,
951                     // so there is nothing to do for it.
952                     continue;
953                 }
954
955                 let name_cstr = CStr::from_ptr(llvm::LLVMGetValueName(val));
956                 let name_str = name_cstr.to_str().unwrap();
957
958                 if exported_symbols.contains(&name_str) {
959                     // This symbol is explicitly exported, so we can't
960                     // mark it as internal or hidden.
961                     continue;
962                 }
963
964                 let is_declaration = llvm::LLVMIsDeclaration(val) == llvm::True;
965
966                 if is_declaration {
967                     if locally_defined_symbols.contains(name_str) {
968                         // Only mark declarations from the current crate as hidden.
969                         // Otherwise we would mark things as hidden that are
970                         // imported from other crates or native libraries.
971                         llvm::LLVMRustSetVisibility(val, llvm::Visibility::Hidden);
972                     }
973                 } else {
974                     let has_fixed_linkage = linkage_fixed_explicitly.contains(name_str);
975
976                     if !has_fixed_linkage {
977                         // In incremental compilation mode, we can't be sure that
978                         // we saw all references because we don't know what's in
979                         // cached compilation units, so we always assume that the
980                         // given item has been referenced.
981                         if incr_comp || referenced_somewhere.contains(&name_cstr) {
982                             llvm::LLVMRustSetVisibility(val, llvm::Visibility::Hidden);
983                         } else {
984                             llvm::LLVMRustSetLinkage(val, llvm::Linkage::InternalLinkage);
985                         }
986
987                         llvm::LLVMSetDLLStorageClass(val, llvm::DLLStorageClass::Default);
988                         llvm::UnsetComdat(val);
989                     }
990                 }
991             }
992         }
993     }
994 }
995
996 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
997 // This is required to satisfy `dllimport` references to static data in .rlibs
998 // when using MSVC linker.  We do this only for data, as linker can fix up
999 // code references on its own.
1000 // See #26591, #27438
1001 fn create_imps(cx: &CrateContextList) {
1002     // The x86 ABI seems to require that leading underscores are added to symbol
1003     // names, so we need an extra underscore on 32-bit. There's also a leading
1004     // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
1005     // underscores added in front).
1006     let prefix = if cx.shared().sess().target.target.target_pointer_width == "32" {
1007         "\x01__imp__"
1008     } else {
1009         "\x01__imp_"
1010     };
1011     unsafe {
1012         for ccx in cx.iter_need_trans() {
1013             let exported: Vec<_> = iter_globals(ccx.llmod())
1014                                        .filter(|&val| {
1015                                            llvm::LLVMRustGetLinkage(val) ==
1016                                            llvm::Linkage::ExternalLinkage &&
1017                                            llvm::LLVMIsDeclaration(val) == 0
1018                                        })
1019                                        .collect();
1020
1021             let i8p_ty = Type::i8p(&ccx);
1022             for val in exported {
1023                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
1024                 let mut imp_name = prefix.as_bytes().to_vec();
1025                 imp_name.extend(name.to_bytes());
1026                 let imp_name = CString::new(imp_name).unwrap();
1027                 let imp = llvm::LLVMAddGlobal(ccx.llmod(),
1028                                               i8p_ty.to_ref(),
1029                                               imp_name.as_ptr() as *const _);
1030                 let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
1031                 llvm::LLVMSetInitializer(imp, init);
1032                 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
1033             }
1034         }
1035     }
1036 }
1037
1038 struct ValueIter {
1039     cur: ValueRef,
1040     step: unsafe extern "C" fn(ValueRef) -> ValueRef,
1041 }
1042
1043 impl Iterator for ValueIter {
1044     type Item = ValueRef;
1045
1046     fn next(&mut self) -> Option<ValueRef> {
1047         let old = self.cur;
1048         if !old.is_null() {
1049             self.cur = unsafe { (self.step)(old) };
1050             Some(old)
1051         } else {
1052             None
1053         }
1054     }
1055 }
1056
1057 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
1058     unsafe {
1059         ValueIter {
1060             cur: llvm::LLVMGetFirstGlobal(llmod),
1061             step: llvm::LLVMGetNextGlobal,
1062         }
1063     }
1064 }
1065
1066 fn iter_functions(llmod: llvm::ModuleRef) -> ValueIter {
1067     unsafe {
1068         ValueIter {
1069             cur: llvm::LLVMGetFirstFunction(llmod),
1070             step: llvm::LLVMGetNextFunction,
1071         }
1072     }
1073 }
1074
1075 /// The context provided lists a set of reachable ids as calculated by
1076 /// middle::reachable, but this contains far more ids and symbols than we're
1077 /// actually exposing from the object file. This function will filter the set in
1078 /// the context to the set of ids which correspond to symbols that are exposed
1079 /// from the object file being generated.
1080 ///
1081 /// This list is later used by linkers to determine the set of symbols needed to
1082 /// be exposed from a dynamic library and it's also encoded into the metadata.
1083 pub fn find_exported_symbols(tcx: TyCtxt, reachable: NodeSet) -> NodeSet {
1084     reachable.into_iter().filter(|&id| {
1085         // Next, we want to ignore some FFI functions that are not exposed from
1086         // this crate. Reachable FFI functions can be lumped into two
1087         // categories:
1088         //
1089         // 1. Those that are included statically via a static library
1090         // 2. Those included otherwise (e.g. dynamically or via a framework)
1091         //
1092         // Although our LLVM module is not literally emitting code for the
1093         // statically included symbols, it's an export of our library which
1094         // needs to be passed on to the linker and encoded in the metadata.
1095         //
1096         // As a result, if this id is an FFI item (foreign item) then we only
1097         // let it through if it's included statically.
1098         match tcx.hir.get(id) {
1099             hir_map::NodeForeignItem(..) => {
1100                 let def_id = tcx.hir.local_def_id(id);
1101                 tcx.sess.cstore.is_statically_included_foreign_item(def_id)
1102             }
1103
1104             // Only consider nodes that actually have exported symbols.
1105             hir_map::NodeItem(&hir::Item {
1106                 node: hir::ItemStatic(..), .. }) |
1107             hir_map::NodeItem(&hir::Item {
1108                 node: hir::ItemFn(..), .. }) |
1109             hir_map::NodeImplItem(&hir::ImplItem {
1110                 node: hir::ImplItemKind::Method(..), .. }) => {
1111                 let def_id = tcx.hir.local_def_id(id);
1112                 let generics = tcx.item_generics(def_id);
1113                 let attributes = tcx.get_attrs(def_id);
1114                 (generics.parent_types == 0 && generics.types.is_empty()) &&
1115                 // Functions marked with #[inline] are only ever translated
1116                 // with "internal" linkage and are never exported.
1117                 !attr::requests_inline(&attributes[..])
1118             }
1119
1120             _ => false
1121         }
1122     }).collect()
1123 }
1124
1125 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1126                              analysis: ty::CrateAnalysis,
1127                              incremental_hashes_map: &IncrementalHashesMap)
1128                              -> CrateTranslation {
1129     let _task = tcx.dep_graph.in_task(DepNode::TransCrate);
1130
1131     // Be careful with this krate: obviously it gives access to the
1132     // entire contents of the krate. So if you push any subtasks of
1133     // `TransCrate`, you need to be careful to register "reads" of the
1134     // particular items that will be processed.
1135     let krate = tcx.hir.krate();
1136
1137     let ty::CrateAnalysis { export_map, reachable, name, .. } = analysis;
1138     let exported_symbols = find_exported_symbols(tcx, reachable);
1139
1140     let check_overflow = tcx.sess.overflow_checks();
1141
1142     let link_meta = link::build_link_meta(incremental_hashes_map, &name);
1143
1144     let shared_ccx = SharedCrateContext::new(tcx,
1145                                              export_map,
1146                                              link_meta.clone(),
1147                                              exported_symbols,
1148                                              check_overflow);
1149     // Translate the metadata.
1150     let metadata = time(tcx.sess.time_passes(), "write metadata", || {
1151         write_metadata(&shared_ccx, shared_ccx.exported_symbols())
1152     });
1153
1154     let metadata_module = ModuleTranslation {
1155         name: link::METADATA_MODULE_NAME.to_string(),
1156         symbol_name_hash: 0, // we always rebuild metadata, at least for now
1157         source: ModuleSource::Translated(ModuleLlvm {
1158             llcx: shared_ccx.metadata_llcx(),
1159             llmod: shared_ccx.metadata_llmod(),
1160         }),
1161     };
1162     let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
1163
1164     // Skip crate items and just output metadata in -Z no-trans mode.
1165     if tcx.sess.opts.debugging_opts.no_trans ||
1166        !tcx.sess.opts.output_types.should_trans() {
1167         let empty_exported_symbols = ExportedSymbols::empty();
1168         let linker_info = LinkerInfo::new(&shared_ccx, &empty_exported_symbols);
1169         return CrateTranslation {
1170             modules: vec![],
1171             metadata_module: metadata_module,
1172             link: link_meta,
1173             metadata: metadata,
1174             exported_symbols: empty_exported_symbols,
1175             no_builtins: no_builtins,
1176             linker_info: linker_info,
1177             windows_subsystem: None,
1178         };
1179     }
1180
1181     // Run the translation item collector and partition the collected items into
1182     // codegen units.
1183     let (codegen_units, symbol_map) = collect_and_partition_translation_items(&shared_ccx);
1184
1185     let symbol_map = Rc::new(symbol_map);
1186
1187     let previous_work_products = trans_reuse_previous_work_products(&shared_ccx,
1188                                                                     &codegen_units,
1189                                                                     &symbol_map);
1190
1191     let crate_context_list = CrateContextList::new(&shared_ccx,
1192                                                    codegen_units,
1193                                                    previous_work_products,
1194                                                    symbol_map.clone());
1195     let modules: Vec<_> = crate_context_list.iter_all()
1196         .map(|ccx| {
1197             let source = match ccx.previous_work_product() {
1198                 Some(buf) => ModuleSource::Preexisting(buf.clone()),
1199                 None => ModuleSource::Translated(ModuleLlvm {
1200                     llcx: ccx.llcx(),
1201                     llmod: ccx.llmod(),
1202                 }),
1203             };
1204
1205             ModuleTranslation {
1206                 name: String::from(ccx.codegen_unit().name()),
1207                 symbol_name_hash: ccx.codegen_unit()
1208                                      .compute_symbol_name_hash(&shared_ccx,
1209                                                                &symbol_map),
1210                 source: source,
1211             }
1212         })
1213         .collect();
1214
1215     assert_module_sources::assert_module_sources(tcx, &modules);
1216
1217     // Instantiate translation items without filling out definitions yet...
1218     for ccx in crate_context_list.iter_need_trans() {
1219         let cgu = ccx.codegen_unit();
1220         let trans_items = cgu.items_in_deterministic_order(tcx, &symbol_map);
1221
1222         tcx.dep_graph.with_task(cgu.work_product_dep_node(), || {
1223             for (trans_item, linkage) in trans_items {
1224                 trans_item.predefine(&ccx, linkage);
1225             }
1226         });
1227     }
1228
1229     // ... and now that we have everything pre-defined, fill out those definitions.
1230     for ccx in crate_context_list.iter_need_trans() {
1231         let cgu = ccx.codegen_unit();
1232         let trans_items = cgu.items_in_deterministic_order(tcx, &symbol_map);
1233         tcx.dep_graph.with_task(cgu.work_product_dep_node(), || {
1234             for (trans_item, _) in trans_items {
1235                 trans_item.define(&ccx);
1236             }
1237
1238             // If this codegen unit contains the main function, also create the
1239             // wrapper here
1240             maybe_create_entry_wrapper(&ccx);
1241
1242             // Run replace-all-uses-with for statics that need it
1243             for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1244                 unsafe {
1245                     let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1246                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1247                     llvm::LLVMDeleteGlobal(old_g);
1248                 }
1249             }
1250
1251             // Finalize debuginfo
1252             if ccx.sess().opts.debuginfo != NoDebugInfo {
1253                 debuginfo::finalize(&ccx);
1254             }
1255         });
1256     }
1257
1258     symbol_names_test::report_symbol_names(&shared_ccx);
1259
1260     if shared_ccx.sess().trans_stats() {
1261         let stats = shared_ccx.stats();
1262         println!("--- trans stats ---");
1263         println!("n_glues_created: {}", stats.n_glues_created.get());
1264         println!("n_null_glues: {}", stats.n_null_glues.get());
1265         println!("n_real_glues: {}", stats.n_real_glues.get());
1266
1267         println!("n_fns: {}", stats.n_fns.get());
1268         println!("n_inlines: {}", stats.n_inlines.get());
1269         println!("n_closures: {}", stats.n_closures.get());
1270         println!("fn stats:");
1271         stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1272             insns_b.cmp(&insns_a)
1273         });
1274         for tuple in stats.fn_stats.borrow().iter() {
1275             match *tuple {
1276                 (ref name, insns) => {
1277                     println!("{} insns, {}", insns, *name);
1278                 }
1279             }
1280         }
1281     }
1282
1283     if shared_ccx.sess().count_llvm_insns() {
1284         for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
1285             println!("{:7} {}", *v, *k);
1286         }
1287     }
1288
1289     let sess = shared_ccx.sess();
1290
1291     let exported_symbols = ExportedSymbols::compute_from(&shared_ccx,
1292                                                          &symbol_map);
1293
1294     // Now that we have all symbols that are exported from the CGUs of this
1295     // crate, we can run the `internalize_symbols` pass.
1296     time(shared_ccx.sess().time_passes(), "internalize symbols", || {
1297         internalize_symbols(sess,
1298                             &crate_context_list,
1299                             &symbol_map,
1300                             &exported_symbols);
1301     });
1302
1303     if tcx.sess.opts.debugging_opts.print_type_sizes {
1304         gather_type_sizes(tcx);
1305     }
1306
1307     if sess.target.target.options.is_like_msvc &&
1308        sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1309         create_imps(&crate_context_list);
1310     }
1311
1312     let linker_info = LinkerInfo::new(&shared_ccx, &exported_symbols);
1313
1314     let subsystem = attr::first_attr_value_str_by_name(&krate.attrs,
1315                                                        "windows_subsystem");
1316     let windows_subsystem = subsystem.map(|subsystem| {
1317         if subsystem != "windows" && subsystem != "console" {
1318             tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
1319                                      `windows` and `console` are allowed",
1320                                     subsystem));
1321         }
1322         subsystem.to_string()
1323     });
1324
1325     CrateTranslation {
1326         modules: modules,
1327         metadata_module: metadata_module,
1328         link: link_meta,
1329         metadata: metadata,
1330         exported_symbols: exported_symbols,
1331         no_builtins: no_builtins,
1332         linker_info: linker_info,
1333         windows_subsystem: windows_subsystem,
1334     }
1335 }
1336
1337 fn gather_type_sizes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
1338     let layout_cache = tcx.layout_cache.borrow();
1339     for (ty, layout) in layout_cache.iter() {
1340
1341         // (delay format until we actually need it)
1342         let record = |kind, opt_discr_size, variants| {
1343             let type_desc = format!("{:?}", ty);
1344             let overall_size = layout.size(&tcx.data_layout);
1345             let align = layout.align(&tcx.data_layout);
1346             tcx.sess.code_stats.borrow_mut().record_type_size(kind,
1347                                                               type_desc,
1348                                                               align,
1349                                                               overall_size,
1350                                                               opt_discr_size,
1351                                                               variants);
1352         };
1353
1354         let (adt_def, substs) = match ty.sty {
1355             ty::TyAdt(ref adt_def, substs) => {
1356                 debug!("print-type-size t: `{:?}` process adt", ty);
1357                 (adt_def, substs)
1358             }
1359
1360             ty::TyClosure(..) => {
1361                 debug!("print-type-size t: `{:?}` record closure", ty);
1362                 record(DataTypeKind::Closure, None, vec![]);
1363                 continue;
1364             }
1365
1366             _ => {
1367                 debug!("print-type-size t: `{:?}` skip non-nominal", ty);
1368                 continue;
1369             }
1370         };
1371
1372         let adt_kind = adt_def.adt_kind();
1373
1374         let build_field_info = |(field_name, field_ty): (ast::Name, Ty), offset: &layout::Size| {
1375             match layout_cache.get(&field_ty) {
1376                 None => bug!("no layout found for field {} type: `{:?}`", field_name, field_ty),
1377                 Some(field_layout) => {
1378                     session::FieldInfo {
1379                         name: field_name.to_string(),
1380                         offset: offset.bytes(),
1381                         size: field_layout.size(&tcx.data_layout).bytes(),
1382                         align: field_layout.align(&tcx.data_layout).abi(),
1383                     }
1384                 }
1385             }
1386         };
1387
1388         let build_primitive_info = |name: ast::Name, value: &layout::Primitive| {
1389             session::VariantInfo {
1390                 name: Some(name.to_string()),
1391                 kind: session::SizeKind::Exact,
1392                 align: value.align(&tcx.data_layout).abi(),
1393                 size: value.size(&tcx.data_layout).bytes(),
1394                 fields: vec![],
1395             }
1396         };
1397
1398         enum Fields<'a> {
1399             WithDiscrim(&'a layout::Struct),
1400             NoDiscrim(&'a layout::Struct),
1401         }
1402
1403         let build_variant_info = |n: Option<ast::Name>, flds: &[(ast::Name, Ty)], layout: Fields| {
1404             let (s, field_offsets) = match layout {
1405                 Fields::WithDiscrim(s) => (s, &s.offsets[1..]),
1406                 Fields::NoDiscrim(s) => (s, &s.offsets[0..]),
1407             };
1408             let field_info: Vec<_> = flds.iter()
1409                 .zip(field_offsets.iter())
1410                 .map(|(&field_name_ty, offset)| build_field_info(field_name_ty, offset))
1411                 .collect();
1412
1413             session::VariantInfo {
1414                 name: n.map(|n|n.to_string()),
1415                 kind: if s.sized {
1416                     session::SizeKind::Exact
1417                 } else {
1418                     session::SizeKind::Min
1419                 },
1420                 align: s.align.abi(),
1421                 size: s.min_size.bytes(),
1422                 fields: field_info,
1423             }
1424         };
1425
1426         match **layout {
1427             Layout::StructWrappedNullablePointer { nonnull: ref variant_layout,
1428                                                    nndiscr,
1429                                                    discrfield: _,
1430                                                    discrfield_source: _ } => {
1431                 debug!("print-type-size t: `{:?}` adt struct-wrapped nullable nndiscr {} is {:?}",
1432                        ty, nndiscr, variant_layout);
1433                 let variant_def = &adt_def.variants[nndiscr as usize];
1434                 let fields: Vec<_> = variant_def.fields.iter()
1435                     .map(|field_def| (field_def.name, field_def.ty(tcx, substs)))
1436                     .collect();
1437                 record(adt_kind.into(),
1438                        None,
1439                        vec![build_variant_info(Some(variant_def.name),
1440                                                &fields,
1441                                                Fields::NoDiscrim(variant_layout))]);
1442             }
1443             Layout::RawNullablePointer { nndiscr, value } => {
1444                 debug!("print-type-size t: `{:?}` adt raw nullable nndiscr {} is {:?}",
1445                        ty, nndiscr, value);
1446                 let variant_def = &adt_def.variants[nndiscr as usize];
1447                 record(adt_kind.into(), None,
1448                        vec![build_primitive_info(variant_def.name, &value)]);
1449             }
1450             Layout::Univariant { variant: ref variant_layout, non_zero: _ } => {
1451                 let variant_names = || {
1452                     adt_def.variants.iter().map(|v|format!("{}", v.name)).collect::<Vec<_>>()
1453                 };
1454                 debug!("print-type-size t: `{:?}` adt univariant {:?} variants: {:?}",
1455                        ty, variant_layout, variant_names());
1456                 assert!(adt_def.variants.len() <= 1,
1457                         "univariant with variants {:?}", variant_names());
1458                 if adt_def.variants.len() == 1 {
1459                     let variant_def = &adt_def.variants[0];
1460                     let fields: Vec<_> = variant_def.fields.iter()
1461                         .map(|field_def| (field_def.name, field_def.ty(tcx, substs)))
1462                         .collect();
1463                     record(adt_kind.into(),
1464                            None,
1465                            vec![build_variant_info(Some(variant_def.name),
1466                                                    &fields,
1467                                                    Fields::NoDiscrim(variant_layout))]);
1468                 } else {
1469                     // (This case arises for *empty* enums; so give it
1470                     // zero variants.)
1471                     record(adt_kind.into(), None, vec![]);
1472                 }
1473             }
1474
1475             Layout::General { ref variants, discr, .. } => {
1476                 debug!("print-type-size t: `{:?}` adt general variants def {} layouts {} {:?}",
1477                        ty, adt_def.variants.len(), variants.len(), variants);
1478                 let variant_infos: Vec<_> = adt_def.variants.iter()
1479                     .zip(variants.iter())
1480                     .map(|(variant_def, variant_layout)| {
1481                         let fields: Vec<_> = variant_def.fields.iter()
1482                             .map(|field_def| (field_def.name, field_def.ty(tcx, substs)))
1483                             .collect();
1484                         build_variant_info(Some(variant_def.name),
1485                                            &fields,
1486                                            Fields::WithDiscrim(variant_layout))
1487                     })
1488                     .collect();
1489                 record(adt_kind.into(), Some(discr.size()), variant_infos);
1490             }
1491
1492             Layout::UntaggedUnion { ref variants } => {
1493                 debug!("print-type-size t: `{:?}` adt union variants {:?}",
1494                        ty, variants);
1495                 // layout does not currently store info about each
1496                 // variant...
1497                 record(adt_kind.into(), None, Vec::new());
1498             }
1499
1500             Layout::CEnum { discr, .. } => {
1501                 debug!("print-type-size t: `{:?}` adt c-like enum", ty);
1502                 let variant_infos: Vec<_> = adt_def.variants.iter()
1503                     .map(|variant_def| {
1504                         build_primitive_info(variant_def.name,
1505                                              &layout::Primitive::Int(discr))
1506                     })
1507                     .collect();
1508                 record(adt_kind.into(), Some(discr.size()), variant_infos);
1509             }
1510
1511             // other cases provide little interesting (i.e. adjustable
1512             // via representation tweaks) size info beyond total size.
1513             Layout::Scalar { .. } |
1514             Layout::Vector { .. } |
1515             Layout::Array { .. } |
1516             Layout::FatPointer { .. } => {
1517                 debug!("print-type-size t: `{:?}` adt other", ty);
1518                 record(adt_kind.into(), None, Vec::new())
1519             }
1520         }
1521     }
1522 }
1523
1524 /// For each CGU, identify if we can reuse an existing object file (or
1525 /// maybe other context).
1526 fn trans_reuse_previous_work_products(scx: &SharedCrateContext,
1527                                       codegen_units: &[CodegenUnit],
1528                                       symbol_map: &SymbolMap)
1529                                       -> Vec<Option<WorkProduct>> {
1530     debug!("trans_reuse_previous_work_products()");
1531     codegen_units
1532         .iter()
1533         .map(|cgu| {
1534             let id = cgu.work_product_id();
1535
1536             let hash = cgu.compute_symbol_name_hash(scx, symbol_map);
1537
1538             debug!("trans_reuse_previous_work_products: id={:?} hash={}", id, hash);
1539
1540             if let Some(work_product) = scx.dep_graph().previous_work_product(&id) {
1541                 if work_product.input_hash == hash {
1542                     debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1543                     return Some(work_product);
1544                 } else {
1545                     if scx.sess().opts.debugging_opts.incremental_info {
1546                         println!("incremental: CGU `{}` invalidated because of \
1547                                   changed partitioning hash.",
1548                                   cgu.name());
1549                     }
1550                     debug!("trans_reuse_previous_work_products: \
1551                             not reusing {:?} because hash changed to {:?}",
1552                            work_product, hash);
1553                 }
1554             }
1555
1556             None
1557         })
1558         .collect()
1559 }
1560
1561 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>)
1562                                                      -> (Vec<CodegenUnit<'tcx>>, SymbolMap<'tcx>) {
1563     let time_passes = scx.sess().time_passes();
1564
1565     let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
1566         Some(ref s) => {
1567             let mode_string = s.to_lowercase();
1568             let mode_string = mode_string.trim();
1569             if mode_string == "eager" {
1570                 TransItemCollectionMode::Eager
1571             } else {
1572                 if mode_string != "lazy" {
1573                     let message = format!("Unknown codegen-item collection mode '{}'. \
1574                                            Falling back to 'lazy' mode.",
1575                                            mode_string);
1576                     scx.sess().warn(&message);
1577                 }
1578
1579                 TransItemCollectionMode::Lazy
1580             }
1581         }
1582         None => TransItemCollectionMode::Lazy
1583     };
1584
1585     let (items, inlining_map) =
1586         time(time_passes, "translation item collection", || {
1587             collector::collect_crate_translation_items(&scx, collection_mode)
1588     });
1589
1590     let symbol_map = SymbolMap::build(scx, items.iter().cloned());
1591
1592     let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1593         PartitioningStrategy::PerModule
1594     } else {
1595         PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1596     };
1597
1598     let codegen_units = time(time_passes, "codegen unit partitioning", || {
1599         partitioning::partition(scx,
1600                                 items.iter().cloned(),
1601                                 strategy,
1602                                 &inlining_map)
1603     });
1604
1605     assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1606             scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1607
1608     {
1609         let mut ccx_map = scx.translation_items().borrow_mut();
1610
1611         for trans_item in items.iter().cloned() {
1612             ccx_map.insert(trans_item);
1613         }
1614     }
1615
1616     if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
1617         let mut item_to_cgus = FxHashMap();
1618
1619         for cgu in &codegen_units {
1620             for (&trans_item, &linkage) in cgu.items() {
1621                 item_to_cgus.entry(trans_item)
1622                             .or_insert(Vec::new())
1623                             .push((cgu.name().clone(), linkage));
1624             }
1625         }
1626
1627         let mut item_keys: Vec<_> = items
1628             .iter()
1629             .map(|i| {
1630                 let mut output = i.to_string(scx.tcx());
1631                 output.push_str(" @@");
1632                 let mut empty = Vec::new();
1633                 let mut cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1634                 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1635                 cgus.dedup();
1636                 for &(ref cgu_name, linkage) in cgus.iter() {
1637                     output.push_str(" ");
1638                     output.push_str(&cgu_name[..]);
1639
1640                     let linkage_abbrev = match linkage {
1641                         llvm::Linkage::ExternalLinkage => "External",
1642                         llvm::Linkage::AvailableExternallyLinkage => "Available",
1643                         llvm::Linkage::LinkOnceAnyLinkage => "OnceAny",
1644                         llvm::Linkage::LinkOnceODRLinkage => "OnceODR",
1645                         llvm::Linkage::WeakAnyLinkage => "WeakAny",
1646                         llvm::Linkage::WeakODRLinkage => "WeakODR",
1647                         llvm::Linkage::AppendingLinkage => "Appending",
1648                         llvm::Linkage::InternalLinkage => "Internal",
1649                         llvm::Linkage::PrivateLinkage => "Private",
1650                         llvm::Linkage::ExternalWeakLinkage => "ExternalWeak",
1651                         llvm::Linkage::CommonLinkage => "Common",
1652                     };
1653
1654                     output.push_str("[");
1655                     output.push_str(linkage_abbrev);
1656                     output.push_str("]");
1657                 }
1658                 output
1659             })
1660             .collect();
1661
1662         item_keys.sort();
1663
1664         for item in item_keys {
1665             println!("TRANS_ITEM {}", item);
1666         }
1667     }
1668
1669     (codegen_units, symbol_map)
1670 }