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