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