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.
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.
11 //! Translate the completed AST to the LLVM IR.
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.
18 //! Hopefully useful general knowledge about trans:
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.
26 use super::CrateTranslation;
27 use super::ModuleLlvm;
28 use super::ModuleSource;
29 use super::ModuleTranslation;
31 use assert_module_sources;
33 use back::linker::LinkerInfo;
34 use back::symbol_export::{self, ExportedSymbols};
35 use llvm::{Linkage, ValueRef, Vector, get_param};
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};
47 use mir::lvalue::LvalueRef;
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};
58 use context::{SharedCrateContext, CrateContextList};
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};
72 use util::nodemap::{NodeSet, FxHashMap, FxHashSet};
75 use std::ffi::{CStr, CString};
82 use rustc::ty::layout::{self, Layout};
85 use mir::lvalue::Alignment;
87 pub struct StatRecorder<'a, 'tcx: 'a> {
88 ccx: &'a CrateContext<'a, 'tcx>,
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();
104 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
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);
117 pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
118 bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
121 pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
122 bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
125 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
127 -> llvm::IntPredicate {
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 },
136 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
143 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
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,
152 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
159 pub fn compare_simd_types<'a, 'tcx>(
160 bcx: &Builder<'a, 'tcx>,
167 let signed = match t.sty {
169 let cmp = bin_op_to_fcmp_predicate(op);
170 return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
172 ty::TyUint(_) => false,
173 ty::TyInt(_) => true,
174 _ => bug!("compare_simd_types: invalid SIMD type"),
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)
185 /// Retrieve the information we are losing (making dynamic) in an unsizing
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>,
194 old_info: Option<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")
205 (_, &ty::TyDynamic(ref data, ..)) => {
206 consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
207 Type::vtable_ptr(ccx))
209 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
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>,
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))
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))
240 _ => bug!("unsize_thin_ptr: called on bad types"),
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);
262 let base = load_ty(bcx, src.llval, src.alignment, src_ty);
263 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
265 store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
267 match (&src_ty.sty, &dst_ty.sty) {
268 (&ty::TyRef(..), &ty::TyRef(..)) |
269 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
270 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
273 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
277 (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
278 assert_eq!(def_a, def_b);
280 let src_fields = def_a.variants[0].fields.iter().map(|f| {
281 monomorphize::field_ty(bcx.tcx(), substs_a, f)
283 let dst_fields = def_b.variants[0].fields.iter().map(|f| {
284 monomorphize::field_ty(bcx.tcx(), substs_b, f)
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) {
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);
300 &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
301 &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
306 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
312 pub fn cast_shift_expr_rhs(
313 cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
315 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
318 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
322 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
323 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
326 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
332 where F: FnOnce(ValueRef, Type) -> ValueRef,
333 G: FnOnce(ValueRef, Type) -> ValueRef
335 // Shifts may have any size int on the rhs
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()
342 if lhs_llty.kind() == Vector {
343 lhs_llty = lhs_llty.element_type()
345 let rhs_sz = rhs_llty.int_width();
346 let lhs_sz = lhs_llty.int_width();
349 } else if lhs_sz > rhs_sz {
350 // FIXME (#1877: If shifting by negative
351 // values becomes not undefined then this is wrong.
361 /// Returns whether this session's target will use SEH-based unwinding.
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
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);
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 {
381 if type_is_zero_size(ccx, t) {
382 return C_undef(type_of::type_of(ccx, t));
386 let global = llvm::LLVMIsAGlobalVariable(ptr);
387 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
388 let val = llvm::LLVMGetInitializer(global);
391 return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
399 b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
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)
408 b.load_nonnull(ptr, alignment.to_align())
410 b.load(ptr, alignment.to_align())
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));
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);
425 cx.store(from_immediate(cx, v), dst, dst_align.to_align());
429 pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
433 dst_align: Alignment,
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());
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())
447 b.load(ptr, alignment.to_align())
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
454 let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
455 b.load_nonnull(meta, None)
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))
471 pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
473 bcx.trunc(val, Type::i1(bcx.ccx))
479 pub enum Lifetime { Start, End }
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.
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 {
495 let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
500 let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
501 Lifetime::Start => "llvm.lifetime.start",
502 Lifetime::End => "llvm.lifetime.end"
505 let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
506 b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
510 pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
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);
527 pub fn memcpy_ty<'a, 'tcx>(
528 bcx: &Builder<'a, 'tcx>,
536 let size = ccx.size_of(t);
541 let align = align.unwrap_or_else(|| ccx.align_of(t));
542 call_memcpy(bcx, dst, src, C_uint(ccx, size), align);
545 pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
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)
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))
568 // this is an info! to allow collecting monomorphization statistics
569 // and to allow finding the last function before LLVM aborts from
571 info!("trans_instance({})", instance);
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);
577 let lldecl = match ccx.instances().borrow().get(&instance) {
579 None => bug!("Instance `{:?}` not already declared", instance)
582 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
584 // The `uwtable` attribute according to LLVM is:
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.
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.
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);
605 let mir = ccx.tcx().instance_mir(instance.def);
606 mir::trans_mir(ccx, lldecl, &mir, instance, sig);
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.
616 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
617 // and don't have to be, LLVM treats them as no-ops.
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),
634 pub fn set_link_section(ccx: &CrateContext,
636 attrs: &[ast::Attribute]) {
637 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
638 if contains_null(§.as_str()) {
639 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
642 let buf = CString::new(sect.as_str().as_bytes()).unwrap();
643 llvm::LLVMSetSection(llval, buf.as_ptr());
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)
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");
666 let instance = Instance::mono(ccx.tcx(), main_def_id);
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
674 let main_llfn = callee::get_fn(ccx, instance);
676 let et = ccx.sess().entry_type.get().unwrap();
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.
683 fn create_entry_fn(ccx: &CrateContext,
686 use_start_lang_item: bool) {
687 let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
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")
694 ccx.sess().abort_if_errors();
697 let llfn = declare::declare_cfn(ccx, "main", llfty);
699 // `main` should respect same config for frame pointer elimination as rest of code
700 attributes::set_frame_pointer_elimination(ccx, llfn);
702 let bld = Builder::new_block(ccx, llfn, "top");
704 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
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),
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)])
717 let result = bld.call(start_fn, &args, None);
722 fn contains_null(s: &str) -> bool {
723 s.bytes().any(|b| b == 0)
726 fn write_metadata(cx: &SharedCrateContext,
727 exported_symbols: &NodeSet) -> Vec<u8> {
730 #[derive(PartialEq, Eq, PartialOrd, Ord)]
737 let kind = cx.sess().crate_types.borrow().iter().map(|ty| {
739 config::CrateTypeExecutable |
740 config::CrateTypeStaticlib |
741 config::CrateTypeCdylib => MetadataKind::None,
743 config::CrateTypeRlib => MetadataKind::Uncompressed,
745 config::CrateTypeDylib |
746 config::CrateTypeProcMacro => MetadataKind::Compressed,
750 if kind == MetadataKind::None {
754 let cstore = &cx.tcx().sess.cstore;
755 let metadata = cstore.encode_metadata(cx.tcx(),
758 if kind == MetadataKind::Uncompressed {
762 assert!(kind == MetadataKind::Compressed);
763 let mut compressed = cstore.metadata_encoding_version().to_vec();
764 compressed.extend_from_slice(&flate::deflate_bytes(&metadata));
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())
774 llvm::LLVMSetInitializer(llglobal, llconst);
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());
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())
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());
799 let exported_symbols = exported_symbols
800 .exported_symbols(LOCAL_CRATE)
802 .filter(|&&(_, export_level)| {
803 symbol_export::is_below_threshold(export_level, export_threshold)
805 .map(|&(ref name, _)| &name[..])
806 .collect::<FxHashSet<&str>>();
808 let scx = ccxs.shared();
811 let incr_comp = sess.opts.debugging_opts.incremental.is_some();
813 // 'unsafe' because we are holding on to CStr's from the LLVM module within
816 let mut referenced_somewhere = FxHashSet();
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
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;
832 if is_decl || is_available_externally {
833 let symbol_name = CStr::from_ptr(llvm::LLVMGetValueName(val));
834 referenced_somewhere.insert(symbol_name);
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();
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());
851 locally_defined_symbols.insert(symbol_name);
854 (locally_defined_symbols, linkage_fixed_explicitly)
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);
864 let is_externally_visible = (linkage == llvm::Linkage::ExternalLinkage) ||
865 (linkage == llvm::Linkage::LinkOnceODRLinkage) ||
866 (linkage == llvm::Linkage::WeakODRLinkage);
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.
874 let name_cstr = CStr::from_ptr(llvm::LLVMGetValueName(val));
875 let name_str = name_cstr.to_str().unwrap();
877 if exported_symbols.contains(&name_str) {
878 // This symbol is explicitly exported, so we can't
879 // mark it as internal or hidden.
883 let is_declaration = llvm::LLVMIsDeclaration(val) == llvm::True;
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);
893 let has_fixed_linkage = linkage_fixed_explicitly.contains(name_str);
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);
903 llvm::LLVMRustSetLinkage(val, llvm::Linkage::InternalLinkage);
906 llvm::LLVMSetDLLStorageClass(val, llvm::DLLStorageClass::Default);
907 llvm::UnsetComdat(val);
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" {
931 for ccx in cx.iter_need_trans() {
932 let exported: Vec<_> = iter_globals(ccx.llmod())
934 llvm::LLVMRustGetLinkage(val) ==
935 llvm::Linkage::ExternalLinkage &&
936 llvm::LLVMIsDeclaration(val) == 0
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(),
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);
959 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
962 impl Iterator for ValueIter {
963 type Item = ValueRef;
965 fn next(&mut self) -> Option<ValueRef> {
968 self.cur = unsafe { (self.step)(old) };
976 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
979 cur: llvm::LLVMGetFirstGlobal(llmod),
980 step: llvm::LLVMGetNextGlobal,
985 fn iter_functions(llmod: llvm::ModuleRef) -> ValueIter {
988 cur: llvm::LLVMGetFirstFunction(llmod),
989 step: llvm::LLVMGetNextFunction,
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.
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
1008 // 1. Those that are included statically via a static library
1009 // 2. Those included otherwise (e.g. dynamically or via a framework)
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.
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)
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)
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);
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();
1056 let ty::CrateAnalysis { reachable, name, .. } = analysis;
1057 let exported_symbols = find_exported_symbols(tcx, reachable);
1059 let check_overflow = tcx.sess.overflow_checks();
1061 let link_meta = link::build_link_meta(incremental_hashes_map, &name);
1063 let shared_ccx = SharedCrateContext::new(tcx,
1067 // Translate the metadata.
1068 let metadata = time(tcx.sess.time_passes(), "write metadata", || {
1069 write_metadata(&shared_ccx, shared_ccx.exported_symbols())
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(),
1080 let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
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 {
1089 metadata_module: metadata_module,
1092 exported_symbols: empty_exported_symbols,
1093 no_builtins: no_builtins,
1094 linker_info: linker_info,
1095 windows_subsystem: None,
1099 // Run the translation item collector and partition the collected items into
1101 let (codegen_units, symbol_map) = collect_and_partition_translation_items(&shared_ccx);
1103 let symbol_map = Rc::new(symbol_map);
1105 let previous_work_products = trans_reuse_previous_work_products(&shared_ccx,
1109 let crate_context_list = CrateContextList::new(&shared_ccx,
1111 previous_work_products,
1112 symbol_map.clone());
1113 let modules: Vec<_> = crate_context_list.iter_all()
1115 let source = match ccx.previous_work_product() {
1116 Some(buf) => ModuleSource::Preexisting(buf.clone()),
1117 None => ModuleSource::Translated(ModuleLlvm {
1124 name: String::from(ccx.codegen_unit().name()),
1125 symbol_name_hash: ccx.codegen_unit()
1126 .compute_symbol_name_hash(&shared_ccx,
1133 assert_module_sources::assert_module_sources(tcx, &modules);
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,
1140 AssertDepGraphSafe(symbol_map.clone()),
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);
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,
1161 AssertDepGraphSafe(symbol_map.clone()),
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);
1175 // If this codegen unit contains the main function, also create the
1177 maybe_create_entry_wrapper(&ccx);
1179 // Run replace-all-uses-with for statics that need it
1180 for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1182 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1183 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1184 llvm::LLVMDeleteGlobal(old_g);
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());
1196 let g = llvm::LLVMAddGlobal(ccx.llmod(),
1197 val_ty(array).to_ref(),
1199 llvm::LLVMSetInitializer(g, array);
1200 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1201 llvm::LLVMSetSection(g, section.as_ptr());
1205 // Finalize debuginfo
1206 if ccx.sess().opts.debuginfo != NoDebugInfo {
1207 debuginfo::finalize(&ccx);
1212 symbol_names_test::report_symbol_names(&shared_ccx);
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());
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)
1228 for tuple in stats.fn_stats.borrow().iter() {
1230 (ref name, insns) => {
1231 println!("{} insns, {}", insns, *name);
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);
1243 let sess = shared_ccx.sess();
1245 let exported_symbols = ExportedSymbols::compute_from(&shared_ccx,
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,
1257 if tcx.sess.opts.debugging_opts.print_type_sizes {
1258 gather_type_sizes(tcx);
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);
1266 let linker_info = LinkerInfo::new(&shared_ccx, &exported_symbols);
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",
1276 subsystem.to_string()
1281 metadata_module: metadata_module,
1284 exported_symbols: exported_symbols,
1285 no_builtins: no_builtins,
1286 linker_info: linker_info,
1287 windows_subsystem: windows_subsystem,
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() {
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,
1308 let (adt_def, substs) = match ty.sty {
1309 ty::TyAdt(ref adt_def, substs) => {
1310 debug!("print-type-size t: `{:?}` process adt", ty);
1314 ty::TyClosure(..) => {
1315 debug!("print-type-size t: `{:?}` record closure", ty);
1316 record(DataTypeKind::Closure, None, vec![]);
1321 debug!("print-type-size t: `{:?}` skip non-nominal", ty);
1326 let adt_kind = adt_def.adt_kind();
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(),
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(),
1353 WithDiscrim(&'a layout::Struct),
1354 NoDiscrim(&'a layout::Struct),
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..]),
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))
1367 session::VariantInfo {
1368 name: n.map(|n|n.to_string()),
1370 session::SizeKind::Exact
1372 session::SizeKind::Min
1374 align: s.align.abi(),
1375 size: s.min_size.bytes(),
1381 Layout::StructWrappedNullablePointer { nonnull: ref variant_layout,
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)))
1391 record(adt_kind.into(),
1393 vec![build_variant_info(Some(variant_def.name),
1395 Fields::NoDiscrim(variant_layout))]);
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)]);
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<_>>()
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)))
1417 record(adt_kind.into(),
1419 vec![build_variant_info(Some(variant_def.name),
1421 Fields::NoDiscrim(variant_layout))]);
1423 // (This case arises for *empty* enums; so give it
1425 record(adt_kind.into(), None, vec![]);
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)))
1438 build_variant_info(Some(variant_def.name),
1440 Fields::WithDiscrim(variant_layout))
1443 record(adt_kind.into(), Some(discr.size()), variant_infos);
1446 Layout::UntaggedUnion { ref variants } => {
1447 debug!("print-type-size t: `{:?}` adt union variants {:?}",
1449 // layout does not currently store info about each
1451 record(adt_kind.into(), None, Vec::new());
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))
1462 record(adt_kind.into(), Some(discr.size()), variant_infos);
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())
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()");
1488 let id = cgu.work_product_id();
1490 let hash = cgu.compute_symbol_name_hash(scx, symbol_map);
1492 debug!("trans_reuse_previous_work_products: id={:?} hash={}", id, hash);
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);
1499 if scx.sess().opts.debugging_opts.incremental_info {
1500 println!("incremental: CGU `{}` invalidated because of \
1501 changed partitioning hash.",
1504 debug!("trans_reuse_previous_work_products: \
1505 not reusing {:?} because hash changed to {:?}",
1506 work_product, hash);
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();
1519 let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
1521 let mode_string = s.to_lowercase();
1522 let mode_string = mode_string.trim();
1523 if mode_string == "eager" {
1524 TransItemCollectionMode::Eager
1526 if mode_string != "lazy" {
1527 let message = format!("Unknown codegen-item collection mode '{}'. \
1528 Falling back to 'lazy' mode.",
1530 scx.sess().warn(&message);
1533 TransItemCollectionMode::Lazy
1536 None => TransItemCollectionMode::Lazy
1539 let (items, inlining_map) =
1540 time(time_passes, "translation item collection", || {
1541 collector::collect_crate_translation_items(&scx, collection_mode)
1544 let symbol_map = SymbolMap::build(scx, items.iter().cloned());
1546 let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1547 PartitioningStrategy::PerModule
1549 PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1552 let codegen_units = time(time_passes, "codegen unit partitioning", || {
1553 partitioning::partition(scx,
1554 items.iter().cloned(),
1559 assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1560 scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1563 let mut ccx_map = scx.translation_items().borrow_mut();
1565 for trans_item in items.iter().cloned() {
1566 ccx_map.insert(trans_item);
1570 if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
1571 let mut item_to_cgus = FxHashMap();
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));
1581 let mut item_keys: Vec<_> = items
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());
1590 for &(ref cgu_name, linkage) in cgus.iter() {
1591 output.push_str(" ");
1592 output.push_str(&cgu_name);
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",
1608 output.push_str("[");
1609 output.push_str(linkage_abbrev);
1610 output.push_str("]");
1618 for item in item_keys {
1619 println!("TRANS_ITEM {}", item);
1623 (codegen_units, symbol_map)