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::ModuleLlvm;
27 use super::ModuleSource;
28 use super::ModuleTranslation;
29 use super::ModuleKind;
31 use assert_module_sources;
33 use back::linker::LinkerInfo;
34 use back::symbol_export::{self, ExportedSymbols};
35 use back::write::{self, OngoingCrateTranslation};
36 use llvm::{ContextRef, Linkage, ModuleRef, ValueRef, Vector, get_param};
39 use rustc::hir::def_id::LOCAL_CRATE;
40 use rustc::middle::lang_items::StartFnLangItem;
41 use rustc::middle::cstore::{EncodedMetadata, EncodedMetadataHashes};
42 use rustc::ty::{self, Ty, TyCtxt};
43 use rustc::dep_graph::AssertDepGraphSafe;
44 use rustc::middle::cstore::LinkMeta;
45 use rustc::hir::map as hir_map;
46 use rustc::util::common::{time, print_time_passes_entry};
47 use rustc::session::config::{self, NoDebugInfo, OutputFilenames, OutputType};
48 use rustc::session::Session;
49 use rustc_incremental::{self, IncrementalHashesMap};
52 use mir::lvalue::LvalueRef;
56 use common::{C_bool, C_bytes_in_context, C_i32, C_uint};
57 use collector::{self, TransItemCollectionMode};
58 use common::{C_struct_in_context, C_u64, C_undef, C_array};
59 use common::CrateContext;
60 use common::{type_is_zero_size, val_ty};
63 use context::{self, LocalCrateContext, SharedCrateContext, Stats};
69 use monomorphize::{self, Instance};
70 use partitioning::{self, PartitioningStrategy, CodegenUnit};
71 use symbol_names_test;
73 use trans_item::{TransItem, DefPathBasedNames};
77 use rustc::util::nodemap::{NodeSet, FxHashMap, FxHashSet};
81 use std::ffi::{CStr, CString};
84 use std::time::{Instant, Duration};
91 use mir::lvalue::Alignment;
93 pub struct StatRecorder<'a, 'tcx: 'a> {
94 ccx: &'a CrateContext<'a, 'tcx>,
99 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
100 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
101 let istart = ccx.stats().n_llvm_insns.get();
110 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
112 if self.ccx.sess().trans_stats() {
113 let iend = self.ccx.stats().n_llvm_insns.get();
114 self.ccx.stats().fn_stats.borrow_mut()
115 .push((self.name.take().unwrap(), iend - self.istart));
116 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
117 // Reset LLVM insn count to avoid compound costs.
118 self.ccx.stats().n_llvm_insns.set(self.istart);
123 pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
124 bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
127 pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
128 bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
131 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
133 -> llvm::IntPredicate {
135 hir::BiEq => llvm::IntEQ,
136 hir::BiNe => llvm::IntNE,
137 hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
138 hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
139 hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
140 hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
142 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
149 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
151 hir::BiEq => llvm::RealOEQ,
152 hir::BiNe => llvm::RealUNE,
153 hir::BiLt => llvm::RealOLT,
154 hir::BiLe => llvm::RealOLE,
155 hir::BiGt => llvm::RealOGT,
156 hir::BiGe => llvm::RealOGE,
158 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
165 pub fn compare_simd_types<'a, 'tcx>(
166 bcx: &Builder<'a, 'tcx>,
173 let signed = match t.sty {
175 let cmp = bin_op_to_fcmp_predicate(op);
176 return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
178 ty::TyUint(_) => false,
179 ty::TyInt(_) => true,
180 _ => bug!("compare_simd_types: invalid SIMD type"),
183 let cmp = bin_op_to_icmp_predicate(op, signed);
184 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
185 // to get the correctly sized type. This will compile to a single instruction
186 // once the IR is converted to assembly if the SIMD instruction is supported
187 // by the target architecture.
188 bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
191 /// Retrieve the information we are losing (making dynamic) in an unsizing
194 /// The `old_info` argument is a bit funny. It is intended for use
195 /// in an upcast, where the new vtable for an object will be derived
196 /// from the old one.
197 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
200 old_info: Option<ValueRef>)
202 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
203 match (&source.sty, &target.sty) {
204 (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
205 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
206 // For now, upcasts are limited to changes in marker
207 // traits, and hence never actually require an actual
208 // change to the vtable.
209 old_info.expect("unsized_info: missing old info for trait upcast")
211 (_, &ty::TyDynamic(ref data, ..)) => {
212 consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
213 Type::vtable_ptr(ccx))
215 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
221 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
222 pub fn unsize_thin_ptr<'a, 'tcx>(
223 bcx: &Builder<'a, 'tcx>,
227 ) -> (ValueRef, ValueRef) {
228 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
229 match (&src_ty.sty, &dst_ty.sty) {
230 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
231 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
232 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
233 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
234 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
235 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
236 assert!(bcx.ccx.shared().type_is_sized(a));
237 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
238 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
240 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
241 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
242 assert!(bcx.ccx.shared().type_is_sized(a));
243 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
244 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
246 _ => bug!("unsize_thin_ptr: called on bad types"),
250 /// Coerce `src`, which is a reference to a value of type `src_ty`,
251 /// to a value of type `dst_ty` and store the result in `dst`
252 pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
253 src: &LvalueRef<'tcx>,
254 dst: &LvalueRef<'tcx>) {
255 let src_ty = src.ty.to_ty(bcx.tcx());
256 let dst_ty = dst.ty.to_ty(bcx.tcx());
257 let coerce_ptr = || {
258 let (base, info) = if common::type_is_fat_ptr(bcx.ccx, src_ty) {
259 // fat-ptr to fat-ptr unsize preserves the vtable
260 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
261 // So we need to pointercast the base to ensure
262 // the types match up.
263 let (base, info) = load_fat_ptr(bcx, src.llval, src.alignment, src_ty);
264 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, dst_ty);
265 let base = bcx.pointercast(base, llcast_ty);
268 let base = load_ty(bcx, src.llval, src.alignment, src_ty);
269 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
271 store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
273 match (&src_ty.sty, &dst_ty.sty) {
274 (&ty::TyRef(..), &ty::TyRef(..)) |
275 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
276 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
279 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
283 (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
284 assert_eq!(def_a, def_b);
286 let src_fields = def_a.variants[0].fields.iter().map(|f| {
287 monomorphize::field_ty(bcx.tcx(), substs_a, f)
289 let dst_fields = def_b.variants[0].fields.iter().map(|f| {
290 monomorphize::field_ty(bcx.tcx(), substs_b, f)
293 let iter = src_fields.zip(dst_fields).enumerate();
294 for (i, (src_fty, dst_fty)) in iter {
295 if type_is_zero_size(bcx.ccx, dst_fty) {
299 let (src_f, src_f_align) = src.trans_field_ptr(bcx, i);
300 let (dst_f, dst_f_align) = dst.trans_field_ptr(bcx, i);
301 if src_fty == dst_fty {
302 memcpy_ty(bcx, dst_f, src_f, src_fty, None);
306 &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
307 &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
312 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
318 pub fn cast_shift_expr_rhs(
319 cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
321 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
324 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
328 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
329 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
332 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
338 where F: FnOnce(ValueRef, Type) -> ValueRef,
339 G: FnOnce(ValueRef, Type) -> ValueRef
341 // Shifts may have any size int on the rhs
343 let mut rhs_llty = val_ty(rhs);
344 let mut lhs_llty = val_ty(lhs);
345 if rhs_llty.kind() == Vector {
346 rhs_llty = rhs_llty.element_type()
348 if lhs_llty.kind() == Vector {
349 lhs_llty = lhs_llty.element_type()
351 let rhs_sz = rhs_llty.int_width();
352 let lhs_sz = lhs_llty.int_width();
355 } else if lhs_sz > rhs_sz {
356 // FIXME (#1877: If shifting by negative
357 // values becomes not undefined then this is wrong.
367 /// Returns whether this session's target will use SEH-based unwinding.
369 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
370 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
371 /// 64-bit MinGW) instead of "full SEH".
372 pub fn wants_msvc_seh(sess: &Session) -> bool {
373 sess.target.target.options.is_like_msvc
376 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
377 let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
378 b.call(assume_intrinsic, &[val], None);
381 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
382 /// differs from the type used for SSA values. Also handles various special cases where the type
383 /// gives us better information about what we are loading.
384 pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,
385 alignment: Alignment, t: Ty<'tcx>) -> ValueRef {
387 if type_is_zero_size(ccx, t) {
388 return C_undef(type_of::type_of(ccx, t));
392 let global = llvm::LLVMIsAGlobalVariable(ptr);
393 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
394 let val = llvm::LLVMGetInitializer(global);
397 return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
405 b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
407 } else if t.is_char() {
408 // a char is a Unicode codepoint, and so takes values from 0
409 // to 0x10FFFF inclusive only.
410 b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False, alignment.to_align())
411 } else if (t.is_region_ptr() || t.is_box() || t.is_fn())
412 && !common::type_is_fat_ptr(ccx, t)
414 b.load_nonnull(ptr, alignment.to_align())
416 b.load(ptr, alignment.to_align())
420 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
421 /// differs from the type used for SSA values.
422 pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,
423 dst_align: Alignment, t: Ty<'tcx>) {
424 debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
426 if common::type_is_fat_ptr(cx.ccx, t) {
427 let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
428 let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
429 store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);
431 cx.store(from_immediate(cx, v), dst, dst_align.to_align());
435 pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
439 dst_align: Alignment,
441 // FIXME: emit metadata
442 cx.store(data, get_dataptr(cx, dst), dst_align.to_align());
443 cx.store(extra, get_meta(cx, dst), dst_align.to_align());
446 pub fn load_fat_ptr<'a, 'tcx>(
447 b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx>
448 ) -> (ValueRef, ValueRef) {
449 let ptr = get_dataptr(b, src);
450 let ptr = if t.is_region_ptr() || t.is_box() {
451 b.load_nonnull(ptr, alignment.to_align())
453 b.load(ptr, alignment.to_align())
456 let meta = get_meta(b, src);
457 let meta_ty = val_ty(meta);
458 // If the 'meta' field is a pointer, it's a vtable, so use load_nonnull
460 let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
461 b.load_nonnull(meta, None)
469 pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
470 if val_ty(val) == Type::i1(bcx.ccx) {
471 bcx.zext(val, Type::i8(bcx.ccx))
477 pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
479 bcx.trunc(val, Type::i1(bcx.ccx))
485 pub enum Lifetime { Start, End }
488 // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
489 // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
490 // and the intrinsic for `lt` and passes them to `emit`, which is in
491 // charge of generating code to call the passed intrinsic on whatever
492 // block of generated code is targeted for the intrinsic.
494 // If LLVM lifetime intrinsic support is disabled (i.e. optimizations
495 // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
496 pub fn call(self, b: &Builder, ptr: ValueRef) {
497 if b.ccx.sess().opts.optimize == config::OptLevel::No {
501 let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
506 let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
507 Lifetime::Start => "llvm.lifetime.start",
508 Lifetime::End => "llvm.lifetime.end"
511 let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
512 b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
516 pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
522 let ptr_width = &ccx.sess().target.target.target_pointer_width;
523 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
524 let memcpy = ccx.get_intrinsic(&key);
525 let src_ptr = b.pointercast(src, Type::i8p(ccx));
526 let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
527 let size = b.intcast(n_bytes, ccx.int_type(), false);
528 let align = C_i32(ccx, align as i32);
529 let volatile = C_bool(ccx, false);
530 b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
533 pub fn memcpy_ty<'a, 'tcx>(
534 bcx: &Builder<'a, 'tcx>,
542 let size = ccx.size_of(t);
547 let align = align.unwrap_or_else(|| ccx.align_of(t));
548 call_memcpy(bcx, dst, src, C_uint(ccx, size), align);
551 pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
556 volatile: bool) -> ValueRef {
557 let ptr_width = &b.ccx.sess().target.target.target_pointer_width;
558 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
559 let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
560 let volatile = C_bool(b.ccx, volatile);
561 b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
564 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
565 let _s = if ccx.sess().trans_stats() {
566 let mut instance_name = String::new();
567 DefPathBasedNames::new(ccx.tcx(), true, true)
568 .push_def_path(instance.def_id(), &mut instance_name);
569 Some(StatRecorder::new(ccx, instance_name))
574 // this is an info! to allow collecting monomorphization statistics
575 // and to allow finding the last function before LLVM aborts from
577 info!("trans_instance({})", instance);
579 let fn_ty = common::instance_ty(ccx.shared(), &instance);
580 let sig = common::ty_fn_sig(ccx, fn_ty);
581 let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
583 let lldecl = match ccx.instances().borrow().get(&instance) {
585 None => bug!("Instance `{:?}` not already declared", instance)
588 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
590 // The `uwtable` attribute according to LLVM is:
592 // This attribute indicates that the ABI being targeted requires that an
593 // unwind table entry be produced for this function even if we can show
594 // that no exceptions passes by it. This is normally the case for the
595 // ELF x86-64 abi, but it can be disabled for some compilation units.
597 // Typically when we're compiling with `-C panic=abort` (which implies this
598 // `no_landing_pads` check) we don't need `uwtable` because we can't
599 // generate any exceptions! On Windows, however, exceptions include other
600 // events such as illegal instructions, segfaults, etc. This means that on
601 // Windows we end up still needing the `uwtable` attribute even if the `-C
602 // panic=abort` flag is passed.
604 // You can also find more info on why Windows is whitelisted here in:
605 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
606 if !ccx.sess().no_landing_pads() ||
607 ccx.sess().target.target.options.is_like_windows {
608 attributes::emit_uwtable(lldecl, true);
611 let mir = ccx.tcx().instance_mir(instance.def);
612 mir::trans_mir(ccx, lldecl, &mir, instance, sig);
615 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
616 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
617 // applicable to variable declarations and may not really make sense for
618 // Rust code in the first place but whitelist them anyway and trust that
619 // the user knows what s/he's doing. Who knows, unanticipated use cases
620 // may pop up in the future.
622 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
623 // and don't have to be, LLVM treats them as no-ops.
625 "appending" => Some(llvm::Linkage::AppendingLinkage),
626 "available_externally" => Some(llvm::Linkage::AvailableExternallyLinkage),
627 "common" => Some(llvm::Linkage::CommonLinkage),
628 "extern_weak" => Some(llvm::Linkage::ExternalWeakLinkage),
629 "external" => Some(llvm::Linkage::ExternalLinkage),
630 "internal" => Some(llvm::Linkage::InternalLinkage),
631 "linkonce" => Some(llvm::Linkage::LinkOnceAnyLinkage),
632 "linkonce_odr" => Some(llvm::Linkage::LinkOnceODRLinkage),
633 "private" => Some(llvm::Linkage::PrivateLinkage),
634 "weak" => Some(llvm::Linkage::WeakAnyLinkage),
635 "weak_odr" => Some(llvm::Linkage::WeakODRLinkage),
640 pub fn set_link_section(ccx: &CrateContext,
642 attrs: &[ast::Attribute]) {
643 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
644 if contains_null(§.as_str()) {
645 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
648 let buf = CString::new(sect.as_str().as_bytes()).unwrap();
649 llvm::LLVMSetSection(llval, buf.as_ptr());
654 // check for the #[rustc_error] annotation, which forces an
655 // error in trans. This is used to write compile-fail tests
656 // that actually test that compilation succeeds without
657 // reporting an error.
658 fn check_for_rustc_errors_attr(tcx: TyCtxt) {
659 if let Some((id, span)) = *tcx.sess.entry_fn.borrow() {
660 let main_def_id = tcx.hir.local_def_id(id);
662 if tcx.has_attr(main_def_id, "rustc_error") {
663 tcx.sess.span_fatal(span, "compilation successful");
668 /// Create the `main` function which will initialize the rust runtime and call
669 /// users main function.
670 fn maybe_create_entry_wrapper(ccx: &CrateContext) {
671 let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
672 Some((id, span)) => {
673 (ccx.tcx().hir.local_def_id(id), span)
678 let instance = Instance::mono(ccx.tcx(), main_def_id);
680 if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
681 // We want to create the wrapper in the same codegen unit as Rust's main
686 let main_llfn = callee::get_fn(ccx, instance);
688 let et = ccx.sess().entry_type.get().unwrap();
690 config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
691 config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
692 config::EntryNone => {} // Do nothing.
695 fn create_entry_fn(ccx: &CrateContext,
698 use_start_lang_item: bool) {
699 let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
701 if declare::get_defined_value(ccx, "main").is_some() {
702 // FIXME: We should be smart and show a better diagnostic here.
703 ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
704 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
706 ccx.sess().abort_if_errors();
709 let llfn = declare::declare_cfn(ccx, "main", llfty);
711 // `main` should respect same config for frame pointer elimination as rest of code
712 attributes::set_frame_pointer_elimination(ccx, llfn);
714 let bld = Builder::new_block(ccx, llfn, "top");
716 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
718 let (start_fn, args) = if use_start_lang_item {
719 let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
720 let start_instance = Instance::mono(ccx.tcx(), start_def_id);
721 let start_fn = callee::get_fn(ccx, start_instance);
722 (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()), get_param(llfn, 0),
725 debug!("using user-defined start fn");
726 (rust_main, vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)])
729 let result = bld.call(start_fn, &args, None);
734 fn contains_null(s: &str) -> bool {
735 s.bytes().any(|b| b == 0)
738 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
739 link_meta: &LinkMeta,
740 exported_symbols: &NodeSet)
741 -> (ContextRef, ModuleRef,
742 EncodedMetadata, EncodedMetadataHashes) {
744 use flate2::Compression;
745 use flate2::write::DeflateEncoder;
747 let (metadata_llcx, metadata_llmod) = unsafe {
748 context::create_context_and_module(tcx.sess, "metadata")
751 #[derive(PartialEq, Eq, PartialOrd, Ord)]
758 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
760 config::CrateTypeExecutable |
761 config::CrateTypeStaticlib |
762 config::CrateTypeCdylib => MetadataKind::None,
764 config::CrateTypeRlib => MetadataKind::Uncompressed,
766 config::CrateTypeDylib |
767 config::CrateTypeProcMacro => MetadataKind::Compressed,
771 if kind == MetadataKind::None {
772 return (metadata_llcx,
774 EncodedMetadata::new(),
775 EncodedMetadataHashes::new());
778 let cstore = &tcx.sess.cstore;
779 let (metadata, hashes) = cstore.encode_metadata(tcx,
782 if kind == MetadataKind::Uncompressed {
783 return (metadata_llcx, metadata_llmod, metadata, hashes);
786 assert!(kind == MetadataKind::Compressed);
787 let mut compressed = cstore.metadata_encoding_version().to_vec();
788 DeflateEncoder::new(&mut compressed, Compression::Fast)
789 .write_all(&metadata.raw_data).unwrap();
791 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
792 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
793 let name = symbol_export::metadata_symbol_name(tcx);
794 let buf = CString::new(name).unwrap();
795 let llglobal = unsafe {
796 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
799 llvm::LLVMSetInitializer(llglobal, llconst);
800 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
801 let name = CString::new(section_name).unwrap();
802 llvm::LLVMSetSection(llglobal, name.as_ptr());
804 // Also generate a .section directive to force no
805 // flags, at least for ELF outputs, so that the
806 // metadata doesn't get loaded into memory.
807 let directive = format!(".section {}", section_name);
808 let directive = CString::new(directive).unwrap();
809 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
811 return (metadata_llcx, metadata_llmod, metadata, hashes);
814 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
815 // This is required to satisfy `dllimport` references to static data in .rlibs
816 // when using MSVC linker. We do this only for data, as linker can fix up
817 // code references on its own.
818 // See #26591, #27438
819 fn create_imps(sess: &Session,
820 llvm_module: &ModuleLlvm) {
821 // The x86 ABI seems to require that leading underscores are added to symbol
822 // names, so we need an extra underscore on 32-bit. There's also a leading
823 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
824 // underscores added in front).
825 let prefix = if sess.target.target.target_pointer_width == "32" {
831 let exported: Vec<_> = iter_globals(llvm_module.llmod)
833 llvm::LLVMRustGetLinkage(val) ==
834 llvm::Linkage::ExternalLinkage &&
835 llvm::LLVMIsDeclaration(val) == 0
839 let i8p_ty = Type::i8p_llcx(llvm_module.llcx);
840 for val in exported {
841 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
842 let mut imp_name = prefix.as_bytes().to_vec();
843 imp_name.extend(name.to_bytes());
844 let imp_name = CString::new(imp_name).unwrap();
845 let imp = llvm::LLVMAddGlobal(llvm_module.llmod,
847 imp_name.as_ptr() as *const _);
848 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
849 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
856 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
859 impl Iterator for ValueIter {
860 type Item = ValueRef;
862 fn next(&mut self) -> Option<ValueRef> {
865 self.cur = unsafe { (self.step)(old) };
873 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
876 cur: llvm::LLVMGetFirstGlobal(llmod),
877 step: llvm::LLVMGetNextGlobal,
882 /// The context provided lists a set of reachable ids as calculated by
883 /// middle::reachable, but this contains far more ids and symbols than we're
884 /// actually exposing from the object file. This function will filter the set in
885 /// the context to the set of ids which correspond to symbols that are exposed
886 /// from the object file being generated.
888 /// This list is later used by linkers to determine the set of symbols needed to
889 /// be exposed from a dynamic library and it's also encoded into the metadata.
890 pub fn find_exported_symbols(tcx: TyCtxt, reachable: &NodeSet) -> NodeSet {
891 reachable.iter().cloned().filter(|&id| {
892 // Next, we want to ignore some FFI functions that are not exposed from
893 // this crate. Reachable FFI functions can be lumped into two
896 // 1. Those that are included statically via a static library
897 // 2. Those included otherwise (e.g. dynamically or via a framework)
899 // Although our LLVM module is not literally emitting code for the
900 // statically included symbols, it's an export of our library which
901 // needs to be passed on to the linker and encoded in the metadata.
903 // As a result, if this id is an FFI item (foreign item) then we only
904 // let it through if it's included statically.
905 match tcx.hir.get(id) {
906 hir_map::NodeForeignItem(..) => {
907 let def_id = tcx.hir.local_def_id(id);
908 tcx.is_statically_included_foreign_item(def_id)
911 // Only consider nodes that actually have exported symbols.
912 hir_map::NodeItem(&hir::Item {
913 node: hir::ItemStatic(..), .. }) |
914 hir_map::NodeItem(&hir::Item {
915 node: hir::ItemFn(..), .. }) |
916 hir_map::NodeImplItem(&hir::ImplItem {
917 node: hir::ImplItemKind::Method(..), .. }) => {
918 let def_id = tcx.hir.local_def_id(id);
919 let generics = tcx.generics_of(def_id);
920 let attributes = tcx.get_attrs(def_id);
921 (generics.parent_types == 0 && generics.types.is_empty()) &&
922 // Functions marked with #[inline] are only ever translated
923 // with "internal" linkage and are never exported.
924 !attr::requests_inline(&attributes)
932 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
933 analysis: ty::CrateAnalysis,
934 incremental_hashes_map: IncrementalHashesMap,
935 output_filenames: &OutputFilenames)
936 -> OngoingCrateTranslation {
937 check_for_rustc_errors_attr(tcx);
939 // Be careful with this krate: obviously it gives access to the
940 // entire contents of the krate. So if you push any subtasks of
941 // `TransCrate`, you need to be careful to register "reads" of the
942 // particular items that will be processed.
943 let krate = tcx.hir.krate();
944 let ty::CrateAnalysis { reachable, .. } = analysis;
945 let check_overflow = tcx.sess.overflow_checks();
946 let link_meta = link::build_link_meta(&incremental_hashes_map);
947 let exported_symbol_node_ids = find_exported_symbols(tcx, &reachable);
949 let shared_ccx = SharedCrateContext::new(tcx,
952 // Translate the metadata.
953 let (metadata_llcx, metadata_llmod, metadata, metadata_incr_hashes) =
954 time(tcx.sess.time_passes(), "write metadata", || {
955 write_metadata(tcx, &link_meta, &exported_symbol_node_ids)
958 let metadata_module = ModuleTranslation {
959 name: link::METADATA_MODULE_NAME.to_string(),
960 symbol_name_hash: 0, // we always rebuild metadata, at least for now
961 source: ModuleSource::Translated(ModuleLlvm {
963 llmod: metadata_llmod,
965 kind: ModuleKind::Metadata,
968 let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
969 let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
970 Some(time_graph::TimeGraph::new())
974 let crate_info = CrateInfo::new(tcx);
976 // Skip crate items and just output metadata in -Z no-trans mode.
977 if tcx.sess.opts.debugging_opts.no_trans ||
978 !tcx.sess.opts.output_types.should_trans() {
979 let empty_exported_symbols = ExportedSymbols::empty();
980 let linker_info = LinkerInfo::new(&shared_ccx, &empty_exported_symbols);
981 let ongoing_translation = write::start_async_translation(
985 tcx.crate_name(LOCAL_CRATE),
988 Arc::new(empty_exported_symbols),
995 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess, metadata_module, true);
997 assert_and_save_dep_graph(tcx,
998 incremental_hashes_map,
999 metadata_incr_hashes,
1002 ongoing_translation.check_for_errors(tcx.sess);
1004 return ongoing_translation;
1007 let exported_symbols = Arc::new(ExportedSymbols::compute(tcx,
1008 &exported_symbol_node_ids));
1010 // Run the translation item collector and partition the collected items into
1012 let (translation_items, codegen_units) =
1013 collect_and_partition_translation_items(&shared_ccx, &exported_symbols);
1015 assert!(codegen_units.len() <= 1 || !tcx.sess.lto());
1017 let linker_info = LinkerInfo::new(&shared_ccx, &exported_symbols);
1018 let subsystem = attr::first_attr_value_str_by_name(&krate.attrs,
1019 "windows_subsystem");
1020 let windows_subsystem = subsystem.map(|subsystem| {
1021 if subsystem != "windows" && subsystem != "console" {
1022 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
1023 `windows` and `console` are allowed",
1026 subsystem.to_string()
1029 let no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1030 (tcx.sess.target.target.options.no_integrated_as &&
1031 (output_filenames.outputs.contains_key(&OutputType::Object) ||
1032 output_filenames.outputs.contains_key(&OutputType::Exe)));
1034 let ongoing_translation = write::start_async_translation(
1038 tcx.crate_name(LOCAL_CRATE),
1041 exported_symbols.clone(),
1048 // Translate an allocator shim, if any
1050 // If LTO is enabled and we've got some previous LLVM module we translated
1051 // above, then we can just translate directly into that LLVM module. If not,
1052 // however, we need to create a separate module and trans into that. Note
1053 // that the separate translation is critical for the standard library where
1054 // the rlib's object file doesn't have allocator functions but the dylib
1055 // links in an object file that has allocator functions. When we're
1056 // compiling a final LTO artifact, though, there's no need to worry about
1057 // this as we're not working with this dual "rlib/dylib" functionality.
1058 let allocator_module = if tcx.sess.lto() {
1060 } else if let Some(kind) = tcx.sess.allocator_kind.get() {
1063 context::create_context_and_module(tcx.sess, "allocator");
1064 let modules = ModuleLlvm {
1068 time(tcx.sess.time_passes(), "write allocator module", || {
1069 allocator::trans(tcx, &modules, kind)
1072 Some(ModuleTranslation {
1073 name: link::ALLOCATOR_MODULE_NAME.to_string(),
1074 symbol_name_hash: 0, // we always rebuild allocator shims
1075 source: ModuleSource::Translated(modules),
1076 kind: ModuleKind::Allocator,
1083 if let Some(allocator_module) = allocator_module {
1084 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess, allocator_module, false);
1087 let codegen_unit_count = codegen_units.len();
1088 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess,
1090 codegen_unit_count == 0);
1092 let translation_items = Arc::new(translation_items);
1094 let mut all_stats = Stats::default();
1095 let mut module_dispositions = tcx.sess.opts.incremental.as_ref().map(|_| Vec::new());
1097 // We sort the codegen units by size. This way we can schedule work for LLVM
1098 // a bit more efficiently. Note that "size" is defined rather crudely at the
1099 // moment as it is just the number of TransItems in the CGU, not taking into
1100 // account the size of each TransItem.
1101 let codegen_units = {
1102 let mut codegen_units = codegen_units;
1103 codegen_units.sort_by_key(|cgu| -(cgu.items().len() as isize));
1107 let mut total_trans_time = Duration::new(0, 0);
1109 for (cgu_index, cgu) in codegen_units.into_iter().enumerate() {
1110 ongoing_translation.wait_for_signal_to_translate_item();
1111 ongoing_translation.check_for_errors(tcx.sess);
1113 let start_time = Instant::now();
1116 let _timing_guard = time_graph
1118 .map(|time_graph| time_graph.start(write::TRANS_WORKER_TIMELINE,
1119 write::TRANS_WORK_PACKAGE_KIND));
1120 let dep_node = cgu.work_product_dep_node();
1121 let ((stats, module), _) =
1122 tcx.dep_graph.with_task(dep_node,
1123 AssertDepGraphSafe(&shared_ccx),
1124 AssertDepGraphSafe((cgu,
1125 translation_items.clone(),
1126 exported_symbols.clone())),
1127 module_translation);
1128 all_stats.extend(stats);
1130 if let Some(ref mut module_dispositions) = module_dispositions {
1131 module_dispositions.push(module.disposition());
1137 let time_to_translate = Instant::now().duration_since(start_time);
1139 // We assume that the cost to run LLVM on a CGU is proportional to
1140 // the time we needed for translating it.
1141 let cost = time_to_translate.as_secs() * 1_000_000_000 +
1142 time_to_translate.subsec_nanos() as u64;
1144 total_trans_time += time_to_translate;
1146 let is_last_cgu = (cgu_index + 1) == codegen_unit_count;
1148 ongoing_translation.submit_translated_module_to_llvm(tcx.sess,
1152 ongoing_translation.check_for_errors(tcx.sess);
1155 // Since the main thread is sometimes blocked during trans, we keep track
1156 // -Ztime-passes output manually.
1157 print_time_passes_entry(tcx.sess.time_passes(),
1158 "translate to LLVM IR",
1161 if let Some(module_dispositions) = module_dispositions {
1162 assert_module_sources::assert_module_sources(tcx, &module_dispositions);
1165 fn module_translation<'a, 'tcx>(
1166 scx: AssertDepGraphSafe<&SharedCrateContext<'a, 'tcx>>,
1167 args: AssertDepGraphSafe<(CodegenUnit<'tcx>,
1168 Arc<FxHashSet<TransItem<'tcx>>>,
1169 Arc<ExportedSymbols>)>)
1170 -> (Stats, ModuleTranslation)
1172 // FIXME(#40304): We ought to be using the id as a key and some queries, I think.
1173 let AssertDepGraphSafe(scx) = scx;
1174 let AssertDepGraphSafe((cgu, crate_trans_items, exported_symbols)) = args;
1176 let cgu_name = String::from(cgu.name());
1177 let cgu_id = cgu.work_product_id();
1178 let symbol_name_hash = cgu.compute_symbol_name_hash(scx);
1180 // Check whether there is a previous work-product we can
1181 // re-use. Not only must the file exist, and the inputs not
1182 // be dirty, but the hash of the symbols we will generate must
1184 let previous_work_product =
1185 scx.dep_graph().previous_work_product(&cgu_id).and_then(|work_product| {
1186 if work_product.input_hash == symbol_name_hash {
1187 debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1190 if scx.sess().opts.debugging_opts.incremental_info {
1191 eprintln!("incremental: CGU `{}` invalidated because of \
1192 changed partitioning hash.",
1195 debug!("trans_reuse_previous_work_products: \
1196 not reusing {:?} because hash changed to {:?}",
1197 work_product, symbol_name_hash);
1202 if let Some(buf) = previous_work_product {
1203 // Don't need to translate this module.
1204 let module = ModuleTranslation {
1207 source: ModuleSource::Preexisting(buf.clone()),
1208 kind: ModuleKind::Regular,
1210 return (Stats::default(), module);
1213 // Instantiate translation items without filling out definitions yet...
1214 let lcx = LocalCrateContext::new(scx, cgu, crate_trans_items, exported_symbols);
1216 let ccx = CrateContext::new(scx, &lcx);
1217 let trans_items = ccx.codegen_unit()
1218 .items_in_deterministic_order(ccx.tcx());
1219 for &(trans_item, (linkage, visibility)) in &trans_items {
1220 trans_item.predefine(&ccx, linkage, visibility);
1223 // ... and now that we have everything pre-defined, fill out those definitions.
1224 for &(trans_item, _) in &trans_items {
1225 trans_item.define(&ccx);
1228 // If this codegen unit contains the main function, also create the
1230 maybe_create_entry_wrapper(&ccx);
1232 // Run replace-all-uses-with for statics that need it
1233 for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1235 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1236 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1237 llvm::LLVMDeleteGlobal(old_g);
1241 // Create the llvm.used variable
1242 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1243 if !ccx.used_statics().borrow().is_empty() {
1244 let name = CString::new("llvm.used").unwrap();
1245 let section = CString::new("llvm.metadata").unwrap();
1246 let array = C_array(Type::i8(&ccx).ptr_to(), &*ccx.used_statics().borrow());
1249 let g = llvm::LLVMAddGlobal(ccx.llmod(),
1250 val_ty(array).to_ref(),
1252 llvm::LLVMSetInitializer(g, array);
1253 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1254 llvm::LLVMSetSection(g, section.as_ptr());
1258 // Finalize debuginfo
1259 if ccx.sess().opts.debuginfo != NoDebugInfo {
1260 debuginfo::finalize(&ccx);
1263 let llvm_module = ModuleLlvm {
1268 // In LTO mode we inject the allocator shim into the existing
1270 if ccx.sess().lto() {
1271 if let Some(kind) = ccx.sess().allocator_kind.get() {
1272 time(ccx.sess().time_passes(), "write allocator module", || {
1274 allocator::trans(ccx.tcx(), &llvm_module, kind);
1280 // Adjust exported symbols for MSVC dllimport
1281 if ccx.sess().target.target.options.is_like_msvc &&
1282 ccx.sess().crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1283 create_imps(ccx.sess(), &llvm_module);
1289 source: ModuleSource::Translated(llvm_module),
1290 kind: ModuleKind::Regular,
1294 (lcx.into_stats(), module)
1297 symbol_names_test::report_symbol_names(tcx);
1299 if shared_ccx.sess().trans_stats() {
1300 println!("--- trans stats ---");
1301 println!("n_glues_created: {}", all_stats.n_glues_created.get());
1302 println!("n_null_glues: {}", all_stats.n_null_glues.get());
1303 println!("n_real_glues: {}", all_stats.n_real_glues.get());
1305 println!("n_fns: {}", all_stats.n_fns.get());
1306 println!("n_inlines: {}", all_stats.n_inlines.get());
1307 println!("n_closures: {}", all_stats.n_closures.get());
1308 println!("fn stats:");
1309 all_stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1310 insns_b.cmp(&insns_a)
1312 for tuple in all_stats.fn_stats.borrow().iter() {
1314 (ref name, insns) => {
1315 println!("{} insns, {}", insns, *name);
1321 if shared_ccx.sess().count_llvm_insns() {
1322 for (k, v) in all_stats.llvm_insns.borrow().iter() {
1323 println!("{:7} {}", *v, *k);
1327 ongoing_translation.check_for_errors(tcx.sess);
1329 assert_and_save_dep_graph(tcx,
1330 incremental_hashes_map,
1331 metadata_incr_hashes,
1336 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1337 incremental_hashes_map: IncrementalHashesMap,
1338 metadata_incr_hashes: EncodedMetadataHashes,
1339 link_meta: LinkMeta) {
1340 time(tcx.sess.time_passes(),
1342 || rustc_incremental::assert_dep_graph(tcx));
1344 time(tcx.sess.time_passes(),
1345 "serialize dep graph",
1346 || rustc_incremental::save_dep_graph(tcx,
1347 incremental_hashes_map,
1348 &metadata_incr_hashes,
1349 link_meta.crate_hash));
1352 #[inline(never)] // give this a place in the profiler
1353 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
1354 where I: Iterator<Item=&'a TransItem<'tcx>>
1356 let mut symbols: Vec<_> = trans_items.map(|trans_item| {
1357 (trans_item, trans_item.symbol_name(tcx))
1360 (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
1364 for pair in (&symbols[..]).windows(2) {
1365 let sym1 = &pair[0].1;
1366 let sym2 = &pair[1].1;
1369 let trans_item1 = pair[0].0;
1370 let trans_item2 = pair[1].0;
1372 let span1 = trans_item1.local_span(tcx);
1373 let span2 = trans_item2.local_span(tcx);
1375 // Deterministically select one of the spans for error reporting
1376 let span = match (span1, span2) {
1377 (Some(span1), Some(span2)) => {
1378 Some(if span1.lo().0 > span2.lo().0 {
1384 (Some(span), None) |
1385 (None, Some(span)) => Some(span),
1389 let error_message = format!("symbol `{}` is already defined", sym1);
1391 if let Some(span) = span {
1392 tcx.sess.span_fatal(span, &error_message)
1394 tcx.sess.fatal(&error_message)
1400 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
1401 exported_symbols: &ExportedSymbols)
1402 -> (FxHashSet<TransItem<'tcx>>,
1403 Vec<CodegenUnit<'tcx>>) {
1404 let time_passes = scx.sess().time_passes();
1406 let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
1408 let mode_string = s.to_lowercase();
1409 let mode_string = mode_string.trim();
1410 if mode_string == "eager" {
1411 TransItemCollectionMode::Eager
1413 if mode_string != "lazy" {
1414 let message = format!("Unknown codegen-item collection mode '{}'. \
1415 Falling back to 'lazy' mode.",
1417 scx.sess().warn(&message);
1420 TransItemCollectionMode::Lazy
1423 None => TransItemCollectionMode::Lazy
1426 let (items, inlining_map) =
1427 time(time_passes, "translation item collection", || {
1428 collector::collect_crate_translation_items(&scx,
1433 assert_symbols_are_distinct(scx.tcx(), items.iter());
1435 let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1436 PartitioningStrategy::PerModule
1438 PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1441 let codegen_units = time(time_passes, "codegen unit partitioning", || {
1442 partitioning::partition(scx,
1443 items.iter().cloned(),
1449 assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1450 scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1452 let translation_items: FxHashSet<TransItem<'tcx>> = items.iter().cloned().collect();
1454 if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
1455 let mut item_to_cgus = FxHashMap();
1457 for cgu in &codegen_units {
1458 for (&trans_item, &linkage) in cgu.items() {
1459 item_to_cgus.entry(trans_item)
1460 .or_insert(Vec::new())
1461 .push((cgu.name().clone(), linkage));
1465 let mut item_keys: Vec<_> = items
1468 let mut output = i.to_string(scx.tcx());
1469 output.push_str(" @@");
1470 let mut empty = Vec::new();
1471 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1472 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1474 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1475 output.push_str(" ");
1476 output.push_str(&cgu_name);
1478 let linkage_abbrev = match linkage {
1479 llvm::Linkage::ExternalLinkage => "External",
1480 llvm::Linkage::AvailableExternallyLinkage => "Available",
1481 llvm::Linkage::LinkOnceAnyLinkage => "OnceAny",
1482 llvm::Linkage::LinkOnceODRLinkage => "OnceODR",
1483 llvm::Linkage::WeakAnyLinkage => "WeakAny",
1484 llvm::Linkage::WeakODRLinkage => "WeakODR",
1485 llvm::Linkage::AppendingLinkage => "Appending",
1486 llvm::Linkage::InternalLinkage => "Internal",
1487 llvm::Linkage::PrivateLinkage => "Private",
1488 llvm::Linkage::ExternalWeakLinkage => "ExternalWeak",
1489 llvm::Linkage::CommonLinkage => "Common",
1492 output.push_str("[");
1493 output.push_str(linkage_abbrev);
1494 output.push_str("]");
1502 for item in item_keys {
1503 println!("TRANS_ITEM {}", item);
1507 (translation_items, codegen_units)
1511 pub fn new(tcx: TyCtxt) -> CrateInfo {
1512 let mut info = CrateInfo {
1513 panic_runtime: None,
1514 compiler_builtins: None,
1515 profiler_runtime: None,
1516 sanitizer_runtime: None,
1517 is_no_builtins: FxHashSet(),
1518 native_libraries: FxHashMap(),
1519 used_libraries: tcx.native_libraries(LOCAL_CRATE),
1520 link_args: tcx.link_args(LOCAL_CRATE),
1523 for cnum in tcx.sess.cstore.crates() {
1524 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1525 if tcx.is_panic_runtime(cnum) {
1526 info.panic_runtime = Some(cnum);
1528 if tcx.is_compiler_builtins(cnum) {
1529 info.compiler_builtins = Some(cnum);
1531 if tcx.is_profiler_runtime(cnum) {
1532 info.profiler_runtime = Some(cnum);
1534 if tcx.is_sanitizer_runtime(cnum) {
1535 info.sanitizer_runtime = Some(cnum);
1537 if tcx.is_no_builtins(cnum) {
1538 info.is_no_builtins.insert(cnum);