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