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