]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/base.rs
async-llvm(17): Create MSVC __imp_ symbols immediately for each module.
[rust.git] / src / librustc_trans / base.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Translate the completed AST to the LLVM IR.
12 //!
13 //! Some functions here, such as trans_block and trans_expr, return a value --
14 //! the result of the translation to LLVM -- while others, such as trans_fn
15 //! and trans_item, are called only for the side effect of adding a
16 //! particular definition to the LLVM IR output we're producing.
17 //!
18 //! Hopefully useful general knowledge about trans:
19 //!
20 //!   * There's no way to find out the Ty type of a ValueRef.  Doing so
21 //!     would be "trying to get the eggs out of an omelette" (credit:
22 //!     pcwalton).  You can, instead, find out its TypeRef by calling val_ty,
23 //!     but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
24 //!     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
25
26 use super::ModuleLlvm;
27 use super::ModuleSource;
28 use super::ModuleTranslation;
29 use super::ModuleKind;
30
31 use assert_module_sources;
32 use back::link;
33 use back::linker::LinkerInfo;
34 use back::symbol_export::{self, ExportedSymbols};
35 use back::write::{self, OngoingCrateTranslation};
36 use llvm::{ContextRef, Linkage, ModuleRef, ValueRef, Vector, get_param};
37 use llvm;
38 use metadata;
39 use rustc::hir::def_id::LOCAL_CRATE;
40 use rustc::middle::lang_items::StartFnLangItem;
41 use rustc::middle::cstore::EncodedMetadata;
42 use rustc::ty::{self, Ty, TyCtxt};
43 use rustc::dep_graph::AssertDepGraphSafe;
44 use rustc::middle::cstore::LinkMeta;
45 use rustc::hir::map as hir_map;
46 use rustc::util::common::time;
47 use rustc::session::config::{self, NoDebugInfo, OutputFilenames, OutputType};
48 use rustc::session::Session;
49 use rustc_incremental::{self, IncrementalHashesMap};
50 use abi;
51 use allocator;
52 use mir::lvalue::LvalueRef;
53 use attributes;
54 use builder::Builder;
55 use 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, C_array};
59 use common::CrateContext;
60 use common::{type_is_zero_size, val_ty};
61 use common;
62 use consts;
63 use context::{self, LocalCrateContext, SharedCrateContext, Stats};
64 use debuginfo;
65 use declare;
66 use machine;
67 use meth;
68 use mir;
69 use monomorphize::{self, Instance};
70 use partitioning::{self, PartitioningStrategy, CodegenUnit};
71 use symbol_names_test;
72 use trans_item::{TransItem, DefPathBasedNames};
73 use type_::Type;
74 use type_of;
75 use value::Value;
76 use rustc::util::nodemap::{NodeSet, FxHashMap, FxHashSet};
77
78 use libc::c_uint;
79 use std::ffi::{CStr, CString};
80 use std::str;
81 use std::sync::Arc;
82 use std::i32;
83 use syntax_pos::Span;
84 use syntax::attr;
85 use rustc::hir;
86 use syntax::ast;
87
88 use mir::lvalue::Alignment;
89
90 pub struct StatRecorder<'a, 'tcx: 'a> {
91     ccx: &'a CrateContext<'a, 'tcx>,
92     name: Option<String>,
93     istart: usize,
94 }
95
96 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
97     pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
98         let istart = ccx.stats().n_llvm_insns.get();
99         StatRecorder {
100             ccx: ccx,
101             name: Some(name),
102             istart: istart,
103         }
104     }
105 }
106
107 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
108     fn drop(&mut self) {
109         if self.ccx.sess().trans_stats() {
110             let iend = self.ccx.stats().n_llvm_insns.get();
111             self.ccx.stats().fn_stats.borrow_mut()
112                 .push((self.name.take().unwrap(), iend - self.istart));
113             self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
114             // Reset LLVM insn count to avoid compound costs.
115             self.ccx.stats().n_llvm_insns.set(self.istart);
116         }
117     }
118 }
119
120 pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
121     bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
122 }
123
124 pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
125     bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
126 }
127
128 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
129                                 signed: bool)
130                                 -> llvm::IntPredicate {
131     match op {
132         hir::BiEq => llvm::IntEQ,
133         hir::BiNe => llvm::IntNE,
134         hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
135         hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
136         hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
137         hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
138         op => {
139             bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
140                   found {:?}",
141                  op)
142         }
143     }
144 }
145
146 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
147     match op {
148         hir::BiEq => llvm::RealOEQ,
149         hir::BiNe => llvm::RealUNE,
150         hir::BiLt => llvm::RealOLT,
151         hir::BiLe => llvm::RealOLE,
152         hir::BiGt => llvm::RealOGT,
153         hir::BiGe => llvm::RealOGE,
154         op => {
155             bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
156                   found {:?}",
157                  op);
158         }
159     }
160 }
161
162 pub fn compare_simd_types<'a, 'tcx>(
163     bcx: &Builder<'a, 'tcx>,
164     lhs: ValueRef,
165     rhs: ValueRef,
166     t: Ty<'tcx>,
167     ret_ty: Type,
168     op: hir::BinOp_
169 ) -> ValueRef {
170     let signed = match t.sty {
171         ty::TyFloat(_) => {
172             let cmp = bin_op_to_fcmp_predicate(op);
173             return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
174         },
175         ty::TyUint(_) => false,
176         ty::TyInt(_) => true,
177         _ => bug!("compare_simd_types: invalid SIMD type"),
178     };
179
180     let cmp = bin_op_to_icmp_predicate(op, signed);
181     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
182     // to get the correctly sized type. This will compile to a single instruction
183     // once the IR is converted to assembly if the SIMD instruction is supported
184     // by the target architecture.
185     bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
186 }
187
188 /// Retrieve the information we are losing (making dynamic) in an unsizing
189 /// adjustment.
190 ///
191 /// The `old_info` argument is a bit funny. It is intended for use
192 /// in an upcast, where the new vtable for an object will be drived
193 /// from the old one.
194 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
195                                 source: Ty<'tcx>,
196                                 target: Ty<'tcx>,
197                                 old_info: Option<ValueRef>)
198                                 -> ValueRef {
199     let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
200     match (&source.sty, &target.sty) {
201         (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
202         (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
203             // For now, upcasts are limited to changes in marker
204             // traits, and hence never actually require an actual
205             // change to the vtable.
206             old_info.expect("unsized_info: missing old info for trait upcast")
207         }
208         (_, &ty::TyDynamic(ref data, ..)) => {
209             consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
210                             Type::vtable_ptr(ccx))
211         }
212         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
213                                      source,
214                                      target),
215     }
216 }
217
218 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
219 pub fn unsize_thin_ptr<'a, 'tcx>(
220     bcx: &Builder<'a, 'tcx>,
221     src: ValueRef,
222     src_ty: Ty<'tcx>,
223     dst_ty: Ty<'tcx>
224 ) -> (ValueRef, ValueRef) {
225     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
226     match (&src_ty.sty, &dst_ty.sty) {
227         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
228          &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
229         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
230          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
231         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
232          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
233             assert!(bcx.ccx.shared().type_is_sized(a));
234             let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
235             (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
236         }
237         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
238             let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
239             assert!(bcx.ccx.shared().type_is_sized(a));
240             let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
241             (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
242         }
243         _ => bug!("unsize_thin_ptr: called on bad types"),
244     }
245 }
246
247 /// Coerce `src`, which is a reference to a value of type `src_ty`,
248 /// to a value of type `dst_ty` and store the result in `dst`
249 pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
250                                      src: &LvalueRef<'tcx>,
251                                      dst: &LvalueRef<'tcx>) {
252     let src_ty = src.ty.to_ty(bcx.tcx());
253     let dst_ty = dst.ty.to_ty(bcx.tcx());
254     let coerce_ptr = || {
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.llval, src.alignment, 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.llval, src.alignment, src_ty);
266             unsize_thin_ptr(bcx, base, src_ty, dst_ty)
267         };
268         store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
269     };
270     match (&src_ty.sty, &dst_ty.sty) {
271         (&ty::TyRef(..), &ty::TyRef(..)) |
272         (&ty::TyRef(..), &ty::TyRawPtr(..)) |
273         (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
274             coerce_ptr()
275         }
276         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
277             coerce_ptr()
278         }
279
280         (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
281             assert_eq!(def_a, def_b);
282
283             let src_fields = def_a.variants[0].fields.iter().map(|f| {
284                 monomorphize::field_ty(bcx.tcx(), substs_a, f)
285             });
286             let dst_fields = def_b.variants[0].fields.iter().map(|f| {
287                 monomorphize::field_ty(bcx.tcx(), substs_b, f)
288             });
289
290             let iter = src_fields.zip(dst_fields).enumerate();
291             for (i, (src_fty, dst_fty)) in iter {
292                 if type_is_zero_size(bcx.ccx, dst_fty) {
293                     continue;
294                 }
295
296                 let (src_f, src_f_align) = src.trans_field_ptr(bcx, i);
297                 let (dst_f, dst_f_align) = dst.trans_field_ptr(bcx, i);
298                 if src_fty == dst_fty {
299                     memcpy_ty(bcx, dst_f, src_f, src_fty, None);
300                 } else {
301                     coerce_unsized_into(
302                         bcx,
303                         &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
304                         &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
305                     );
306                 }
307             }
308         }
309         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
310                   src_ty,
311                   dst_ty),
312     }
313 }
314
315 pub fn cast_shift_expr_rhs(
316     cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
317 ) -> ValueRef {
318     cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
319 }
320
321 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
322     cast_shift_rhs(op,
323                    lhs,
324                    rhs,
325                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
326                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
327 }
328
329 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
330                         lhs: ValueRef,
331                         rhs: ValueRef,
332                         trunc: F,
333                         zext: G)
334                         -> ValueRef
335     where F: FnOnce(ValueRef, Type) -> ValueRef,
336           G: FnOnce(ValueRef, Type) -> ValueRef
337 {
338     // Shifts may have any size int on the rhs
339     if op.is_shift() {
340         let mut rhs_llty = val_ty(rhs);
341         let mut lhs_llty = val_ty(lhs);
342         if rhs_llty.kind() == Vector {
343             rhs_llty = rhs_llty.element_type()
344         }
345         if lhs_llty.kind() == Vector {
346             lhs_llty = lhs_llty.element_type()
347         }
348         let rhs_sz = rhs_llty.int_width();
349         let lhs_sz = lhs_llty.int_width();
350         if lhs_sz < rhs_sz {
351             trunc(rhs, lhs_llty)
352         } else if lhs_sz > rhs_sz {
353             // FIXME (#1877: If shifting by negative
354             // values becomes not undefined then this is wrong.
355             zext(rhs, lhs_llty)
356         } else {
357             rhs
358         }
359     } else {
360         rhs
361     }
362 }
363
364 /// Returns whether this session's target will use SEH-based unwinding.
365 ///
366 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
367 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
368 /// 64-bit MinGW) instead of "full SEH".
369 pub fn wants_msvc_seh(sess: &Session) -> bool {
370     sess.target.target.options.is_like_msvc
371 }
372
373 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
374     let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
375     b.call(assume_intrinsic, &[val], None);
376 }
377
378 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
379 /// differs from the type used for SSA values. Also handles various special cases where the type
380 /// gives us better information about what we are loading.
381 pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,
382                          alignment: Alignment, t: Ty<'tcx>) -> ValueRef {
383     let ccx = b.ccx;
384     if type_is_zero_size(ccx, t) {
385         return C_undef(type_of::type_of(ccx, t));
386     }
387
388     unsafe {
389         let global = llvm::LLVMIsAGlobalVariable(ptr);
390         if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
391             let val = llvm::LLVMGetInitializer(global);
392             if !val.is_null() {
393                 if t.is_bool() {
394                     return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
395                 }
396                 return val;
397             }
398         }
399     }
400
401     if t.is_bool() {
402         b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
403                 Type::i1(ccx))
404     } else if t.is_char() {
405         // a char is a Unicode codepoint, and so takes values from 0
406         // to 0x10FFFF inclusive only.
407         b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False, alignment.to_align())
408     } else if (t.is_region_ptr() || t.is_box() || t.is_fn())
409         && !common::type_is_fat_ptr(ccx, t)
410     {
411         b.load_nonnull(ptr, alignment.to_align())
412     } else {
413         b.load(ptr, alignment.to_align())
414     }
415 }
416
417 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
418 /// differs from the type used for SSA values.
419 pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,
420                           dst_align: Alignment, t: Ty<'tcx>) {
421     debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
422
423     if common::type_is_fat_ptr(cx.ccx, t) {
424         let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
425         let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
426         store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);
427     } else {
428         cx.store(from_immediate(cx, v), dst, dst_align.to_align());
429     }
430 }
431
432 pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
433                                data: ValueRef,
434                                extra: ValueRef,
435                                dst: ValueRef,
436                                dst_align: Alignment,
437                                _ty: Ty<'tcx>) {
438     // FIXME: emit metadata
439     cx.store(data, get_dataptr(cx, dst), dst_align.to_align());
440     cx.store(extra, get_meta(cx, dst), dst_align.to_align());
441 }
442
443 pub fn load_fat_ptr<'a, 'tcx>(
444     b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx>
445 ) -> (ValueRef, ValueRef) {
446     let ptr = get_dataptr(b, src);
447     let ptr = if t.is_region_ptr() || t.is_box() {
448         b.load_nonnull(ptr, alignment.to_align())
449     } else {
450         b.load(ptr, alignment.to_align())
451     };
452
453     let meta = get_meta(b, src);
454     let meta_ty = val_ty(meta);
455     // If the 'meta' field is a pointer, it's a vtable, so use load_nonnull
456     // instead
457     let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
458         b.load_nonnull(meta, None)
459     } else {
460         b.load(meta, None)
461     };
462
463     (ptr, meta)
464 }
465
466 pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
467     if val_ty(val) == Type::i1(bcx.ccx) {
468         bcx.zext(val, Type::i8(bcx.ccx))
469     } else {
470         val
471     }
472 }
473
474 pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
475     if ty.is_bool() {
476         bcx.trunc(val, Type::i1(bcx.ccx))
477     } else {
478         val
479     }
480 }
481
482 pub enum Lifetime { Start, End }
483
484 impl Lifetime {
485     // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
486     // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
487     // and the intrinsic for `lt` and passes them to `emit`, which is in
488     // charge of generating code to call the passed intrinsic on whatever
489     // block of generated code is targetted for the intrinsic.
490     //
491     // If LLVM lifetime intrinsic support is disabled (i.e.  optimizations
492     // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
493     pub fn call(self, b: &Builder, ptr: ValueRef) {
494         if b.ccx.sess().opts.optimize == config::OptLevel::No {
495             return;
496         }
497
498         let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
499         if size == 0 {
500             return;
501         }
502
503         let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
504             Lifetime::Start => "llvm.lifetime.start",
505             Lifetime::End => "llvm.lifetime.end"
506         });
507
508         let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
509         b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
510     }
511 }
512
513 pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
514                                dst: ValueRef,
515                                src: ValueRef,
516                                n_bytes: ValueRef,
517                                align: u32) {
518     let ccx = b.ccx;
519     let ptr_width = &ccx.sess().target.target.target_pointer_width;
520     let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
521     let memcpy = ccx.get_intrinsic(&key);
522     let src_ptr = b.pointercast(src, Type::i8p(ccx));
523     let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
524     let size = b.intcast(n_bytes, ccx.int_type(), false);
525     let align = C_i32(ccx, align as i32);
526     let volatile = C_bool(ccx, false);
527     b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
528 }
529
530 pub fn memcpy_ty<'a, 'tcx>(
531     bcx: &Builder<'a, 'tcx>,
532     dst: ValueRef,
533     src: ValueRef,
534     t: Ty<'tcx>,
535     align: Option<u32>,
536 ) {
537     let ccx = bcx.ccx;
538
539     let size = ccx.size_of(t);
540     if size == 0 {
541         return;
542     }
543
544     let align = align.unwrap_or_else(|| ccx.align_of(t));
545     call_memcpy(bcx, dst, src, C_uint(ccx, size), align);
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 trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
562     let _s = if ccx.sess().trans_stats() {
563         let mut instance_name = String::new();
564         DefPathBasedNames::new(ccx.tcx(), true, true)
565             .push_def_path(instance.def_id(), &mut instance_name);
566         Some(StatRecorder::new(ccx, instance_name))
567     } else {
568         None
569     };
570
571     // this is an info! to allow collecting monomorphization statistics
572     // and to allow finding the last function before LLVM aborts from
573     // release builds.
574     info!("trans_instance({})", instance);
575
576     let fn_ty = common::instance_ty(ccx.shared(), &instance);
577     let sig = common::ty_fn_sig(ccx, fn_ty);
578     let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
579
580     let lldecl = match ccx.instances().borrow().get(&instance) {
581         Some(&val) => val,
582         None => bug!("Instance `{:?}` not already declared", instance)
583     };
584
585     ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
586
587     // The `uwtable` attribute according to LLVM is:
588     //
589     //     This attribute indicates that the ABI being targeted requires that an
590     //     unwind table entry be produced for this function even if we can show
591     //     that no exceptions passes by it. This is normally the case for the
592     //     ELF x86-64 abi, but it can be disabled for some compilation units.
593     //
594     // Typically when we're compiling with `-C panic=abort` (which implies this
595     // `no_landing_pads` check) we don't need `uwtable` because we can't
596     // generate any exceptions! On Windows, however, exceptions include other
597     // events such as illegal instructions, segfaults, etc. This means that on
598     // Windows we end up still needing the `uwtable` attribute even if the `-C
599     // panic=abort` flag is passed.
600     //
601     // You can also find more info on why Windows is whitelisted here in:
602     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
603     if !ccx.sess().no_landing_pads() ||
604        ccx.sess().target.target.options.is_like_windows {
605         attributes::emit_uwtable(lldecl, true);
606     }
607
608     let mir = ccx.tcx().instance_mir(instance.def);
609     mir::trans_mir(ccx, lldecl, &mir, instance, sig);
610 }
611
612 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
613     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
614     // applicable to variable declarations and may not really make sense for
615     // Rust code in the first place but whitelist them anyway and trust that
616     // the user knows what s/he's doing. Who knows, unanticipated use cases
617     // may pop up in the future.
618     //
619     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
620     // and don't have to be, LLVM treats them as no-ops.
621     match name {
622         "appending" => Some(llvm::Linkage::AppendingLinkage),
623         "available_externally" => Some(llvm::Linkage::AvailableExternallyLinkage),
624         "common" => Some(llvm::Linkage::CommonLinkage),
625         "extern_weak" => Some(llvm::Linkage::ExternalWeakLinkage),
626         "external" => Some(llvm::Linkage::ExternalLinkage),
627         "internal" => Some(llvm::Linkage::InternalLinkage),
628         "linkonce" => Some(llvm::Linkage::LinkOnceAnyLinkage),
629         "linkonce_odr" => Some(llvm::Linkage::LinkOnceODRLinkage),
630         "private" => Some(llvm::Linkage::PrivateLinkage),
631         "weak" => Some(llvm::Linkage::WeakAnyLinkage),
632         "weak_odr" => Some(llvm::Linkage::WeakODRLinkage),
633         _ => None,
634     }
635 }
636
637 pub fn set_link_section(ccx: &CrateContext,
638                         llval: ValueRef,
639                         attrs: &[ast::Attribute]) {
640     if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
641         if contains_null(&sect.as_str()) {
642             ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", &sect));
643         }
644         unsafe {
645             let buf = CString::new(sect.as_str().as_bytes()).unwrap();
646             llvm::LLVMSetSection(llval, buf.as_ptr());
647         }
648     }
649 }
650
651 /// Create the `main` function which will initialise the rust runtime and call
652 /// users main function.
653 pub fn maybe_create_entry_wrapper(ccx: &CrateContext) {
654     let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
655         Some((id, span)) => {
656             (ccx.tcx().hir.local_def_id(id), span)
657         }
658         None => return,
659     };
660
661     // check for the #[rustc_error] annotation, which forces an
662     // error in trans. This is used to write compile-fail tests
663     // that actually test that compilation succeeds without
664     // reporting an error.
665     if ccx.tcx().has_attr(main_def_id, "rustc_error") {
666         ccx.tcx().sess.span_fatal(span, "compilation successful");
667     }
668
669     let instance = Instance::mono(ccx.tcx(), main_def_id);
670
671     if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
672         // We want to create the wrapper in the same codegen unit as Rust's main
673         // function.
674         return;
675     }
676
677     let main_llfn = callee::get_fn(ccx, instance);
678
679     let et = ccx.sess().entry_type.get().unwrap();
680     match et {
681         config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
682         config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
683         config::EntryNone => {}    // Do nothing.
684     }
685
686     fn create_entry_fn(ccx: &CrateContext,
687                        sp: Span,
688                        rust_main: ValueRef,
689                        use_start_lang_item: bool) {
690         let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
691
692         if declare::get_defined_value(ccx, "main").is_some() {
693             // FIXME: We should be smart and show a better diagnostic here.
694             ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
695                       .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
696                       .emit();
697             ccx.sess().abort_if_errors();
698             bug!();
699         }
700         let llfn = declare::declare_cfn(ccx, "main", llfty);
701
702         // `main` should respect same config for frame pointer elimination as rest of code
703         attributes::set_frame_pointer_elimination(ccx, llfn);
704
705         let bld = Builder::new_block(ccx, llfn, "top");
706
707         debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
708
709         let (start_fn, args) = if use_start_lang_item {
710             let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
711             let start_instance = Instance::mono(ccx.tcx(), start_def_id);
712             let start_fn = callee::get_fn(ccx, start_instance);
713             (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()), get_param(llfn, 0),
714                 get_param(llfn, 1)])
715         } else {
716             debug!("using user-defined start fn");
717             (rust_main, vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)])
718         };
719
720         let result = bld.call(start_fn, &args, None);
721         bld.ret(result);
722     }
723 }
724
725 fn contains_null(s: &str) -> bool {
726     s.bytes().any(|b| b == 0)
727 }
728
729 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
730                             link_meta: &LinkMeta,
731                             exported_symbols: &NodeSet)
732                             -> (ContextRef, ModuleRef, EncodedMetadata) {
733     use std::io::Write;
734     use flate2::Compression;
735     use flate2::write::DeflateEncoder;
736
737     let (metadata_llcx, metadata_llmod) = unsafe {
738         context::create_context_and_module(tcx.sess, "metadata")
739     };
740
741     #[derive(PartialEq, Eq, PartialOrd, Ord)]
742     enum MetadataKind {
743         None,
744         Uncompressed,
745         Compressed
746     }
747
748     let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
749         match *ty {
750             config::CrateTypeExecutable |
751             config::CrateTypeStaticlib |
752             config::CrateTypeCdylib => MetadataKind::None,
753
754             config::CrateTypeRlib => MetadataKind::Uncompressed,
755
756             config::CrateTypeDylib |
757             config::CrateTypeProcMacro => MetadataKind::Compressed,
758         }
759     }).max().unwrap();
760
761     if kind == MetadataKind::None {
762         return (metadata_llcx, metadata_llmod, EncodedMetadata::new());
763     }
764
765     let cstore = &tcx.sess.cstore;
766     let metadata = cstore.encode_metadata(tcx,
767                                           &link_meta,
768                                           exported_symbols);
769     if kind == MetadataKind::Uncompressed {
770         return (metadata_llcx, metadata_llmod, metadata);
771     }
772
773     assert!(kind == MetadataKind::Compressed);
774     let mut compressed = cstore.metadata_encoding_version().to_vec();
775     DeflateEncoder::new(&mut compressed, Compression::Fast)
776         .write_all(&metadata.raw_data).unwrap();
777
778     let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
779     let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
780     let name = symbol_export::metadata_symbol_name(tcx);
781     let buf = CString::new(name).unwrap();
782     let llglobal = unsafe {
783         llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
784     };
785     unsafe {
786         llvm::LLVMSetInitializer(llglobal, llconst);
787         let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
788         let name = CString::new(section_name).unwrap();
789         llvm::LLVMSetSection(llglobal, name.as_ptr());
790
791         // Also generate a .section directive to force no
792         // flags, at least for ELF outputs, so that the
793         // metadata doesn't get loaded into memory.
794         let directive = format!(".section {}", section_name);
795         let directive = CString::new(directive).unwrap();
796         llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
797     }
798     return (metadata_llcx, metadata_llmod, metadata);
799 }
800
801 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
802 // This is required to satisfy `dllimport` references to static data in .rlibs
803 // when using MSVC linker.  We do this only for data, as linker can fix up
804 // code references on its own.
805 // See #26591, #27438
806 fn create_imps(sess: &Session,
807                llvm_module: &ModuleLlvm) {
808     // The x86 ABI seems to require that leading underscores are added to symbol
809     // names, so we need an extra underscore on 32-bit. There's also a leading
810     // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
811     // underscores added in front).
812     let prefix = if sess.target.target.target_pointer_width == "32" {
813         "\x01__imp__"
814     } else {
815         "\x01__imp_"
816     };
817     unsafe {
818         let exported: Vec<_> = iter_globals(llvm_module.llmod)
819                                    .filter(|&val| {
820                                        llvm::LLVMRustGetLinkage(val) ==
821                                        llvm::Linkage::ExternalLinkage &&
822                                        llvm::LLVMIsDeclaration(val) == 0
823                                    })
824                                    .collect();
825
826         let i8p_ty = Type::i8p_llcx(llvm_module.llcx);
827         for val in exported {
828             let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
829             let mut imp_name = prefix.as_bytes().to_vec();
830             imp_name.extend(name.to_bytes());
831             let imp_name = CString::new(imp_name).unwrap();
832             let imp = llvm::LLVMAddGlobal(llvm_module.llmod,
833                                           i8p_ty.to_ref(),
834                                           imp_name.as_ptr() as *const _);
835             let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
836             llvm::LLVMSetInitializer(imp, init);
837             llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
838         }
839     }
840 }
841
842 struct ValueIter {
843     cur: ValueRef,
844     step: unsafe extern "C" fn(ValueRef) -> ValueRef,
845 }
846
847 impl Iterator for ValueIter {
848     type Item = ValueRef;
849
850     fn next(&mut self) -> Option<ValueRef> {
851         let old = self.cur;
852         if !old.is_null() {
853             self.cur = unsafe { (self.step)(old) };
854             Some(old)
855         } else {
856             None
857         }
858     }
859 }
860
861 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
862     unsafe {
863         ValueIter {
864             cur: llvm::LLVMGetFirstGlobal(llmod),
865             step: llvm::LLVMGetNextGlobal,
866         }
867     }
868 }
869
870 /// The context provided lists a set of reachable ids as calculated by
871 /// middle::reachable, but this contains far more ids and symbols than we're
872 /// actually exposing from the object file. This function will filter the set in
873 /// the context to the set of ids which correspond to symbols that are exposed
874 /// from the object file being generated.
875 ///
876 /// This list is later used by linkers to determine the set of symbols needed to
877 /// be exposed from a dynamic library and it's also encoded into the metadata.
878 pub fn find_exported_symbols(tcx: TyCtxt, reachable: &NodeSet) -> NodeSet {
879     reachable.iter().cloned().filter(|&id| {
880         // Next, we want to ignore some FFI functions that are not exposed from
881         // this crate. Reachable FFI functions can be lumped into two
882         // categories:
883         //
884         // 1. Those that are included statically via a static library
885         // 2. Those included otherwise (e.g. dynamically or via a framework)
886         //
887         // Although our LLVM module is not literally emitting code for the
888         // statically included symbols, it's an export of our library which
889         // needs to be passed on to the linker and encoded in the metadata.
890         //
891         // As a result, if this id is an FFI item (foreign item) then we only
892         // let it through if it's included statically.
893         match tcx.hir.get(id) {
894             hir_map::NodeForeignItem(..) => {
895                 let def_id = tcx.hir.local_def_id(id);
896                 tcx.sess.cstore.is_statically_included_foreign_item(def_id)
897             }
898
899             // Only consider nodes that actually have exported symbols.
900             hir_map::NodeItem(&hir::Item {
901                 node: hir::ItemStatic(..), .. }) |
902             hir_map::NodeItem(&hir::Item {
903                 node: hir::ItemFn(..), .. }) |
904             hir_map::NodeImplItem(&hir::ImplItem {
905                 node: hir::ImplItemKind::Method(..), .. }) => {
906                 let def_id = tcx.hir.local_def_id(id);
907                 let generics = tcx.generics_of(def_id);
908                 let attributes = tcx.get_attrs(def_id);
909                 (generics.parent_types == 0 && generics.types.is_empty()) &&
910                 // Functions marked with #[inline] are only ever translated
911                 // with "internal" linkage and are never exported.
912                 !attr::requests_inline(&attributes)
913             }
914
915             _ => false
916         }
917     }).collect()
918 }
919
920 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
921                              analysis: ty::CrateAnalysis,
922                              incremental_hashes_map: &IncrementalHashesMap,
923                              output_filenames: &OutputFilenames)
924                              -> OngoingCrateTranslation {
925     // Be careful with this krate: obviously it gives access to the
926     // entire contents of the krate. So if you push any subtasks of
927     // `TransCrate`, you need to be careful to register "reads" of the
928     // particular items that will be processed.
929     let krate = tcx.hir.krate();
930
931     let ty::CrateAnalysis { reachable, .. } = analysis;
932
933     let check_overflow = tcx.sess.overflow_checks();
934
935     let link_meta = link::build_link_meta(incremental_hashes_map);
936
937     let exported_symbol_node_ids = find_exported_symbols(tcx, &reachable);
938     let shared_ccx = SharedCrateContext::new(tcx,
939                                              check_overflow,
940                                              output_filenames);
941     // Translate the metadata.
942     let (metadata_llcx, metadata_llmod, metadata) =
943         time(tcx.sess.time_passes(), "write metadata", || {
944             write_metadata(tcx, &link_meta, &exported_symbol_node_ids)
945         });
946
947     let metadata_module = ModuleTranslation {
948         name: link::METADATA_MODULE_NAME.to_string(),
949         symbol_name_hash: 0, // we always rebuild metadata, at least for now
950         source: ModuleSource::Translated(ModuleLlvm {
951             llcx: metadata_llcx,
952             llmod: metadata_llmod,
953         }),
954         kind: ModuleKind::Metadata,
955     };
956
957     let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
958
959     // Skip crate items and just output metadata in -Z no-trans mode.
960     if tcx.sess.opts.debugging_opts.no_trans ||
961        !tcx.sess.opts.output_types.should_trans() {
962         let empty_exported_symbols = ExportedSymbols::empty();
963         let linker_info = LinkerInfo::new(&shared_ccx, &empty_exported_symbols);
964         let ongoing_translation = write::run_passes(
965             tcx.sess,
966             output_filenames,
967             tcx.crate_name(LOCAL_CRATE),
968             link_meta,
969             metadata,
970             Arc::new(empty_exported_symbols),
971             no_builtins,
972             None,
973             linker_info,
974             false);
975
976         ongoing_translation.submit_translated_module_to_llvm(tcx.sess, metadata_module);
977         ongoing_translation.signal_translation_done();
978
979         return ongoing_translation;
980     }
981
982     let exported_symbols = Arc::new(ExportedSymbols::compute(tcx,
983                                                              &exported_symbol_node_ids));
984
985     // Run the translation item collector and partition the collected items into
986     // codegen units.
987     let (translation_items, codegen_units) =
988         collect_and_partition_translation_items(&shared_ccx, &exported_symbols);
989
990     assert!(codegen_units.len() <= 1 || !tcx.sess.lto());
991
992     let translation_items = Arc::new(translation_items);
993
994     let mut all_stats = Stats::default();
995     let modules: Vec<ModuleTranslation> = codegen_units
996         .into_iter()
997         .map(|cgu| {
998             let dep_node = cgu.work_product_dep_node();
999             let ((stats, module), _) =
1000                 tcx.dep_graph.with_task(dep_node,
1001                                         AssertDepGraphSafe(&shared_ccx),
1002                                         AssertDepGraphSafe((cgu,
1003                                                             translation_items.clone(),
1004                                                             exported_symbols.clone())),
1005                                         module_translation);
1006             all_stats.extend(stats);
1007             module
1008         })
1009         .collect();
1010
1011     fn module_translation<'a, 'tcx>(
1012         scx: AssertDepGraphSafe<&SharedCrateContext<'a, 'tcx>>,
1013         args: AssertDepGraphSafe<(CodegenUnit<'tcx>,
1014                                   Arc<FxHashSet<TransItem<'tcx>>>,
1015                                   Arc<ExportedSymbols>)>)
1016         -> (Stats, ModuleTranslation)
1017     {
1018         // FIXME(#40304): We ought to be using the id as a key and some queries, I think.
1019         let AssertDepGraphSafe(scx) = scx;
1020         let AssertDepGraphSafe((cgu, crate_trans_items, exported_symbols)) = args;
1021
1022         let cgu_name = String::from(cgu.name());
1023         let cgu_id = cgu.work_product_id();
1024         let symbol_name_hash = cgu.compute_symbol_name_hash(scx, &exported_symbols);
1025
1026         // Check whether there is a previous work-product we can
1027         // re-use.  Not only must the file exist, and the inputs not
1028         // be dirty, but the hash of the symbols we will generate must
1029         // be the same.
1030         let previous_work_product =
1031             scx.dep_graph().previous_work_product(&cgu_id).and_then(|work_product| {
1032                 if work_product.input_hash == symbol_name_hash {
1033                     debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1034                     Some(work_product)
1035                 } else {
1036                     if scx.sess().opts.debugging_opts.incremental_info {
1037                         eprintln!("incremental: CGU `{}` invalidated because of \
1038                                    changed partitioning hash.",
1039                                    cgu.name());
1040                     }
1041                     debug!("trans_reuse_previous_work_products: \
1042                             not reusing {:?} because hash changed to {:?}",
1043                            work_product, symbol_name_hash);
1044                     None
1045                 }
1046             });
1047
1048         if let Some(buf) = previous_work_product {
1049             // Don't need to translate this module.
1050             let module = ModuleTranslation {
1051                 name: cgu_name,
1052                 symbol_name_hash,
1053                 source: ModuleSource::Preexisting(buf.clone()),
1054                 kind: ModuleKind::Regular,
1055             };
1056             return (Stats::default(), module);
1057         }
1058
1059         // Instantiate translation items without filling out definitions yet...
1060         let lcx = LocalCrateContext::new(scx, cgu, crate_trans_items, exported_symbols);
1061         let module = {
1062             let ccx = CrateContext::new(scx, &lcx);
1063             let trans_items = ccx.codegen_unit()
1064                                  .items_in_deterministic_order(ccx.tcx());
1065             for &(trans_item, (linkage, visibility)) in &trans_items {
1066                 trans_item.predefine(&ccx, linkage, visibility);
1067             }
1068
1069             // ... and now that we have everything pre-defined, fill out those definitions.
1070             for &(trans_item, _) in &trans_items {
1071                 trans_item.define(&ccx);
1072             }
1073
1074             // If this codegen unit contains the main function, also create the
1075             // wrapper here
1076             maybe_create_entry_wrapper(&ccx);
1077
1078             // Run replace-all-uses-with for statics that need it
1079             for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1080                 unsafe {
1081                     let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1082                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1083                     llvm::LLVMDeleteGlobal(old_g);
1084                 }
1085             }
1086
1087             // Create the llvm.used variable
1088             // This variable has type [N x i8*] and is stored in the llvm.metadata section
1089             if !ccx.used_statics().borrow().is_empty() {
1090                 let name = CString::new("llvm.used").unwrap();
1091                 let section = CString::new("llvm.metadata").unwrap();
1092                 let array = C_array(Type::i8(&ccx).ptr_to(), &*ccx.used_statics().borrow());
1093
1094                 unsafe {
1095                     let g = llvm::LLVMAddGlobal(ccx.llmod(),
1096                                                 val_ty(array).to_ref(),
1097                                                 name.as_ptr());
1098                     llvm::LLVMSetInitializer(g, array);
1099                     llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1100                     llvm::LLVMSetSection(g, section.as_ptr());
1101                 }
1102             }
1103
1104             // Finalize debuginfo
1105             if ccx.sess().opts.debuginfo != NoDebugInfo {
1106                 debuginfo::finalize(&ccx);
1107             }
1108
1109             let llvm_module = ModuleLlvm {
1110                 llcx: ccx.llcx(),
1111                 llmod: ccx.llmod(),
1112             };
1113
1114             // In LTO mode we inject the allocator shim into the existing
1115             // module.
1116             if ccx.sess().lto() {
1117                 if let Some(kind) = ccx.sess().allocator_kind.get() {
1118                     time(ccx.sess().time_passes(), "write allocator module", || {
1119                         unsafe {
1120                             allocator::trans(ccx.tcx(), &llvm_module, kind);
1121                         }
1122                     });
1123                 }
1124             }
1125
1126             // Adjust exported symbols for MSVC dllimport
1127             if ccx.sess().target.target.options.is_like_msvc &&
1128                ccx.sess().crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1129                 create_imps(ccx.sess(), &llvm_module);
1130             }
1131
1132             ModuleTranslation {
1133                 name: cgu_name,
1134                 symbol_name_hash,
1135                 source: ModuleSource::Translated(llvm_module),
1136                 kind: ModuleKind::Regular,
1137             }
1138         };
1139
1140         (lcx.into_stats(), module)
1141     }
1142
1143     assert_module_sources::assert_module_sources(tcx, &modules);
1144
1145     symbol_names_test::report_symbol_names(tcx);
1146
1147     if shared_ccx.sess().trans_stats() {
1148         println!("--- trans stats ---");
1149         println!("n_glues_created: {}", all_stats.n_glues_created.get());
1150         println!("n_null_glues: {}", all_stats.n_null_glues.get());
1151         println!("n_real_glues: {}", all_stats.n_real_glues.get());
1152
1153         println!("n_fns: {}", all_stats.n_fns.get());
1154         println!("n_inlines: {}", all_stats.n_inlines.get());
1155         println!("n_closures: {}", all_stats.n_closures.get());
1156         println!("fn stats:");
1157         all_stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1158             insns_b.cmp(&insns_a)
1159         });
1160         for tuple in all_stats.fn_stats.borrow().iter() {
1161             match *tuple {
1162                 (ref name, insns) => {
1163                     println!("{} insns, {}", insns, *name);
1164                 }
1165             }
1166         }
1167     }
1168
1169     if shared_ccx.sess().count_llvm_insns() {
1170         for (k, v) in all_stats.llvm_insns.borrow().iter() {
1171             println!("{:7} {}", *v, *k);
1172         }
1173     }
1174
1175     let sess = shared_ccx.sess();
1176
1177     // Translate an allocator shim, if any
1178     //
1179     // If LTO is enabled and we've got some previous LLVM module we translated
1180     // above, then we can just translate directly into that LLVM module. If not,
1181     // however, we need to create a separate module and trans into that. Note
1182     // that the separate translation is critical for the standard library where
1183     // the rlib's object file doesn't have allocator functions but the dylib
1184     // links in an object file that has allocator functions. When we're
1185     // compiling a final LTO artifact, though, there's no need to worry about
1186     // this as we're not working with this dual "rlib/dylib" functionality.
1187     let allocator_module = if tcx.sess.lto() {
1188         None
1189     } else if let Some(kind) = tcx.sess.allocator_kind.get() {
1190         unsafe {
1191             let (llcx, llmod) =
1192                 context::create_context_and_module(tcx.sess, "allocator");
1193             let modules = ModuleLlvm {
1194                 llmod: llmod,
1195                 llcx: llcx,
1196             };
1197             time(tcx.sess.time_passes(), "write allocator module", || {
1198                 allocator::trans(tcx, &modules, kind)
1199             });
1200
1201             Some(ModuleTranslation {
1202                 name: link::ALLOCATOR_MODULE_NAME.to_string(),
1203                 symbol_name_hash: 0, // we always rebuild allocator shims
1204                 source: ModuleSource::Translated(modules),
1205                 kind: ModuleKind::Allocator,
1206             })
1207         }
1208     } else {
1209         None
1210     };
1211
1212     let linker_info = LinkerInfo::new(&shared_ccx, &exported_symbols);
1213
1214     let subsystem = attr::first_attr_value_str_by_name(&krate.attrs,
1215                                                        "windows_subsystem");
1216     let windows_subsystem = subsystem.map(|subsystem| {
1217         if subsystem != "windows" && subsystem != "console" {
1218             tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
1219                                      `windows` and `console` are allowed",
1220                                     subsystem));
1221         }
1222         subsystem.to_string()
1223     });
1224
1225     let outputs = output_filenames;
1226
1227     let no_integrated_as = sess.opts.cg.no_integrated_as ||
1228         (sess.target.target.options.no_integrated_as &&
1229          (outputs.outputs.contains_key(&OutputType::Object) ||
1230           outputs.outputs.contains_key(&OutputType::Exe)));
1231
1232     time(sess.time_passes(),
1233          "assert dep graph",
1234          || rustc_incremental::assert_dep_graph(tcx));
1235
1236     time(sess.time_passes(),
1237          "serialize dep graph",
1238          || rustc_incremental::save_dep_graph(tcx,
1239                                               incremental_hashes_map,
1240                                               &metadata.hashes,
1241                                               link_meta.crate_hash));
1242     // ---
1243     let ongoing_translation = write::run_passes(
1244         sess,
1245         outputs,
1246         tcx.crate_name(LOCAL_CRATE),
1247         link_meta,
1248         metadata,
1249         exported_symbols,
1250         no_builtins,
1251         windows_subsystem,
1252         linker_info,
1253         no_integrated_as);
1254
1255     ongoing_translation.submit_translated_module_to_llvm(sess, metadata_module);
1256
1257     for mtrans in modules {
1258         ongoing_translation.submit_translated_module_to_llvm(sess, mtrans);
1259     }
1260
1261     if let Some(allocator_module) = allocator_module {
1262         ongoing_translation.submit_translated_module_to_llvm(sess, allocator_module);
1263     }
1264
1265     ongoing_translation.signal_translation_done();
1266
1267     ongoing_translation
1268 }
1269
1270 #[inline(never)] // give this a place in the profiler
1271 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
1272     where I: Iterator<Item=&'a TransItem<'tcx>>
1273 {
1274     let mut symbols: Vec<_> = trans_items.map(|trans_item| {
1275         (trans_item, trans_item.symbol_name(tcx))
1276     }).collect();
1277
1278     (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
1279         sym1.cmp(sym2)
1280     });
1281
1282     for pair in (&symbols[..]).windows(2) {
1283         let sym1 = &pair[0].1;
1284         let sym2 = &pair[1].1;
1285
1286         if *sym1 == *sym2 {
1287             let trans_item1 = pair[0].0;
1288             let trans_item2 = pair[1].0;
1289
1290             let span1 = trans_item1.local_span(tcx);
1291             let span2 = trans_item2.local_span(tcx);
1292
1293             // Deterministically select one of the spans for error reporting
1294             let span = match (span1, span2) {
1295                 (Some(span1), Some(span2)) => {
1296                     Some(if span1.lo.0 > span2.lo.0 {
1297                         span1
1298                     } else {
1299                         span2
1300                     })
1301                 }
1302                 (Some(span), None) |
1303                 (None, Some(span)) => Some(span),
1304                 _ => None
1305             };
1306
1307             let error_message = format!("symbol `{}` is already defined", sym1);
1308
1309             if let Some(span) = span {
1310                 tcx.sess.span_fatal(span, &error_message)
1311             } else {
1312                 tcx.sess.fatal(&error_message)
1313             }
1314         }
1315     }
1316 }
1317
1318 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
1319                                                      exported_symbols: &ExportedSymbols)
1320                                                      -> (FxHashSet<TransItem<'tcx>>,
1321                                                          Vec<CodegenUnit<'tcx>>) {
1322     let time_passes = scx.sess().time_passes();
1323
1324     let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
1325         Some(ref s) => {
1326             let mode_string = s.to_lowercase();
1327             let mode_string = mode_string.trim();
1328             if mode_string == "eager" {
1329                 TransItemCollectionMode::Eager
1330             } else {
1331                 if mode_string != "lazy" {
1332                     let message = format!("Unknown codegen-item collection mode '{}'. \
1333                                            Falling back to 'lazy' mode.",
1334                                            mode_string);
1335                     scx.sess().warn(&message);
1336                 }
1337
1338                 TransItemCollectionMode::Lazy
1339             }
1340         }
1341         None => TransItemCollectionMode::Lazy
1342     };
1343
1344     let (items, inlining_map) =
1345         time(time_passes, "translation item collection", || {
1346             collector::collect_crate_translation_items(&scx,
1347                                                        exported_symbols,
1348                                                        collection_mode)
1349     });
1350
1351     assert_symbols_are_distinct(scx.tcx(), items.iter());
1352
1353     let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1354         PartitioningStrategy::PerModule
1355     } else {
1356         PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1357     };
1358
1359     let codegen_units = time(time_passes, "codegen unit partitioning", || {
1360         partitioning::partition(scx,
1361                                 items.iter().cloned(),
1362                                 strategy,
1363                                 &inlining_map,
1364                                 exported_symbols)
1365     });
1366
1367     assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1368             scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1369
1370     let translation_items: FxHashSet<TransItem<'tcx>> = items.iter().cloned().collect();
1371
1372     if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
1373         let mut item_to_cgus = FxHashMap();
1374
1375         for cgu in &codegen_units {
1376             for (&trans_item, &linkage) in cgu.items() {
1377                 item_to_cgus.entry(trans_item)
1378                             .or_insert(Vec::new())
1379                             .push((cgu.name().clone(), linkage));
1380             }
1381         }
1382
1383         let mut item_keys: Vec<_> = items
1384             .iter()
1385             .map(|i| {
1386                 let mut output = i.to_string(scx.tcx());
1387                 output.push_str(" @@");
1388                 let mut empty = Vec::new();
1389                 let mut cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1390                 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1391                 cgus.dedup();
1392                 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1393                     output.push_str(" ");
1394                     output.push_str(&cgu_name);
1395
1396                     let linkage_abbrev = match linkage {
1397                         llvm::Linkage::ExternalLinkage => "External",
1398                         llvm::Linkage::AvailableExternallyLinkage => "Available",
1399                         llvm::Linkage::LinkOnceAnyLinkage => "OnceAny",
1400                         llvm::Linkage::LinkOnceODRLinkage => "OnceODR",
1401                         llvm::Linkage::WeakAnyLinkage => "WeakAny",
1402                         llvm::Linkage::WeakODRLinkage => "WeakODR",
1403                         llvm::Linkage::AppendingLinkage => "Appending",
1404                         llvm::Linkage::InternalLinkage => "Internal",
1405                         llvm::Linkage::PrivateLinkage => "Private",
1406                         llvm::Linkage::ExternalWeakLinkage => "ExternalWeak",
1407                         llvm::Linkage::CommonLinkage => "Common",
1408                     };
1409
1410                     output.push_str("[");
1411                     output.push_str(linkage_abbrev);
1412                     output.push_str("]");
1413                 }
1414                 output
1415             })
1416             .collect();
1417
1418         item_keys.sort();
1419
1420         for item in item_keys {
1421             println!("TRANS_ITEM {}", item);
1422         }
1423     }
1424
1425     (translation_items, codegen_units)
1426 }