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