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;
33 use back::symbol_export;
34 use back::write::{self, OngoingCrateTranslation, create_target_machine};
35 use llvm::{ContextRef, ModuleRef, ValueRef, Vector, get_param};
38 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
39 use rustc::middle::lang_items::StartFnLangItem;
40 use rustc::mir::mono::{Linkage, Visibility, Stats};
41 use rustc::middle::cstore::{EncodedMetadata};
42 use rustc::ty::{self, Ty, TyCtxt};
43 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf};
44 use rustc::ty::maps::Providers;
45 use rustc::dep_graph::{DepNode, DepConstructor};
46 use rustc::ty::subst::Kind;
47 use rustc::middle::cstore::{self, LinkMeta, LinkagePreference};
48 use rustc::util::common::{time, print_time_passes_entry};
49 use rustc::session::config::{self, NoDebugInfo};
50 use rustc::session::Session;
51 use rustc_incremental;
53 use mir::place::PlaceRef;
57 use common::{C_bool, C_bytes_in_context, C_i32, C_usize};
58 use rustc_mir::monomorphize::collector::{self, MonoItemCollectionMode};
59 use common::{self, C_struct_in_context, C_array, val_ty};
61 use context::{self, CodegenCx};
66 use monomorphize::Instance;
67 use monomorphize::partitioning::{self, PartitioningStrategy, CodegenUnit, CodegenUnitExt};
68 use rustc_trans_utils::symbol_names_test;
70 use trans_item::{MonoItem, BaseMonoItemExt, MonoItemExt, DefPathBasedNames};
72 use type_of::LayoutLlvmExt;
73 use rustc::util::nodemap::{NodeSet, FxHashMap, FxHashSet, DefIdSet};
77 use std::ffi::CString;
80 use std::time::{Instant, Duration};
81 use std::{i32, usize};
85 use syntax_pos::symbol::InternedString;
90 use mir::operand::OperandValue;
92 pub use rustc_trans_utils::{find_exported_symbols, check_for_rustc_errors_attr};
93 pub use rustc_mir::monomorphize::item::linkage_by_name;
95 pub struct StatRecorder<'a, 'tcx: 'a> {
96 cx: &'a CodegenCx<'a, 'tcx>,
101 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
102 pub fn new(cx: &'a CodegenCx<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
103 let istart = cx.stats.borrow().n_llvm_insns;
112 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
114 if self.cx.sess().trans_stats() {
115 let mut stats = self.cx.stats.borrow_mut();
116 let iend = stats.n_llvm_insns;
117 stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
119 // Reset LLVM insn count to avoid compound costs.
120 stats.n_llvm_insns = self.istart;
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 bx: &Builder<'a, 'tcx>,
167 let signed = match t.sty {
169 let cmp = bin_op_to_fcmp_predicate(op);
170 return bx.sext(bx.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 bx.sext(bx.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 derived
190 /// from the old one.
191 pub fn unsized_info<'cx, 'tcx>(cx: &CodegenCx<'cx, 'tcx>,
194 old_info: Option<ValueRef>)
196 let (source, target) = cx.tcx.struct_lockstep_tails(source, target);
197 match (&source.sty, &target.sty) {
198 (&ty::TyArray(_, len), &ty::TySlice(_)) => {
199 C_usize(cx, len.val.to_const_int().unwrap().to_u64().unwrap())
201 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
202 // For now, upcasts are limited to changes in marker
203 // traits, and hence never actually require an actual
204 // change to the vtable.
205 old_info.expect("unsized_info: missing old info for trait upcast")
207 (_, &ty::TyDynamic(ref data, ..)) => {
208 let vtable_ptr = cx.layout_of(cx.tcx.mk_mut_ptr(target))
209 .field(cx, abi::FAT_PTR_EXTRA);
210 consts::ptrcast(meth::get_vtable(cx, source, data.principal()),
211 vtable_ptr.llvm_type(cx))
213 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
219 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
220 pub fn unsize_thin_ptr<'a, 'tcx>(
221 bx: &Builder<'a, 'tcx>,
225 ) -> (ValueRef, ValueRef) {
226 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
227 match (&src_ty.sty, &dst_ty.sty) {
228 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
229 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
230 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
231 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
232 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
233 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
234 assert!(bx.cx.type_is_sized(a));
235 let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
236 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
238 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
239 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
240 assert!(bx.cx.type_is_sized(a));
241 let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
242 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
244 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
245 assert_eq!(def_a, def_b);
247 let src_layout = bx.cx.layout_of(src_ty);
248 let dst_layout = bx.cx.layout_of(dst_ty);
249 let mut result = None;
250 for i in 0..src_layout.fields.count() {
251 let src_f = src_layout.field(bx.cx, i);
252 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
253 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
257 assert_eq!(src_layout.size, src_f.size);
259 let dst_f = dst_layout.field(bx.cx, i);
260 assert_ne!(src_f.ty, dst_f.ty);
261 assert_eq!(result, None);
262 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
264 let (lldata, llextra) = result.unwrap();
265 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
266 (bx.bitcast(lldata, dst_layout.scalar_pair_element_llvm_type(bx.cx, 0)),
267 bx.bitcast(llextra, dst_layout.scalar_pair_element_llvm_type(bx.cx, 1)))
269 _ => bug!("unsize_thin_ptr: called on bad types"),
273 /// Coerce `src`, which is a reference to a value of type `src_ty`,
274 /// to a value of type `dst_ty` and store the result in `dst`
275 pub fn coerce_unsized_into<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
277 dst: PlaceRef<'tcx>) {
278 let src_ty = src.layout.ty;
279 let dst_ty = dst.layout.ty;
280 let coerce_ptr = || {
281 let (base, info) = match src.load(bx).val {
282 OperandValue::Pair(base, info) => {
283 // fat-ptr to fat-ptr unsize preserves the vtable
284 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
285 // So we need to pointercast the base to ensure
286 // the types match up.
287 let thin_ptr = dst.layout.field(bx.cx, abi::FAT_PTR_ADDR);
288 (bx.pointercast(base, thin_ptr.llvm_type(bx.cx)), info)
290 OperandValue::Immediate(base) => {
291 unsize_thin_ptr(bx, base, src_ty, dst_ty)
293 OperandValue::Ref(..) => bug!()
295 OperandValue::Pair(base, info).store(bx, dst);
297 match (&src_ty.sty, &dst_ty.sty) {
298 (&ty::TyRef(..), &ty::TyRef(..)) |
299 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
300 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
303 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
307 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
308 assert_eq!(def_a, def_b);
310 for i in 0..def_a.variants[0].fields.len() {
311 let src_f = src.project_field(bx, i);
312 let dst_f = dst.project_field(bx, i);
314 if dst_f.layout.is_zst() {
318 if src_f.layout.ty == dst_f.layout.ty {
319 memcpy_ty(bx, dst_f.llval, src_f.llval, src_f.layout,
320 src_f.align.min(dst_f.align));
322 coerce_unsized_into(bx, src_f, dst_f);
326 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
332 pub fn cast_shift_expr_rhs(
333 cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
335 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
338 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
342 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
343 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
346 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
352 where F: FnOnce(ValueRef, Type) -> ValueRef,
353 G: FnOnce(ValueRef, Type) -> ValueRef
355 // Shifts may have any size int on the rhs
357 let mut rhs_llty = val_ty(rhs);
358 let mut lhs_llty = val_ty(lhs);
359 if rhs_llty.kind() == Vector {
360 rhs_llty = rhs_llty.element_type()
362 if lhs_llty.kind() == Vector {
363 lhs_llty = lhs_llty.element_type()
365 let rhs_sz = rhs_llty.int_width();
366 let lhs_sz = lhs_llty.int_width();
369 } else if lhs_sz > rhs_sz {
370 // FIXME (#1877: If shifting by negative
371 // values becomes not undefined then this is wrong.
381 /// Returns whether this session's target will use SEH-based unwinding.
383 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
384 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
385 /// 64-bit MinGW) instead of "full SEH".
386 pub fn wants_msvc_seh(sess: &Session) -> bool {
387 sess.target.target.options.is_like_msvc
390 pub fn call_assume<'a, 'tcx>(bx: &Builder<'a, 'tcx>, val: ValueRef) {
391 let assume_intrinsic = bx.cx.get_intrinsic("llvm.assume");
392 bx.call(assume_intrinsic, &[val], None);
395 pub fn from_immediate(bx: &Builder, val: ValueRef) -> ValueRef {
396 if val_ty(val) == Type::i1(bx.cx) {
397 bx.zext(val, Type::i8(bx.cx))
403 pub fn to_immediate(bx: &Builder, val: ValueRef, layout: layout::TyLayout) -> ValueRef {
404 if let layout::Abi::Scalar(ref scalar) = layout.abi {
405 if scalar.is_bool() {
406 return bx.trunc(val, Type::i1(bx.cx));
412 pub fn call_memcpy(bx: &Builder,
418 let ptr_width = &cx.sess().target.target.target_pointer_width;
419 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
420 let memcpy = cx.get_intrinsic(&key);
421 let src_ptr = bx.pointercast(src, Type::i8p(cx));
422 let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
423 let size = bx.intcast(n_bytes, cx.isize_ty, false);
424 let align = C_i32(cx, align.abi() as i32);
425 let volatile = C_bool(cx, false);
426 bx.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
429 pub fn memcpy_ty<'a, 'tcx>(
430 bx: &Builder<'a, 'tcx>,
433 layout: TyLayout<'tcx>,
436 let size = layout.size.bytes();
441 call_memcpy(bx, dst, src, C_usize(bx.cx, size), align);
444 pub fn call_memset<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
449 volatile: bool) -> ValueRef {
450 let ptr_width = &bx.cx.sess().target.target.target_pointer_width;
451 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
452 let llintrinsicfn = bx.cx.get_intrinsic(&intrinsic_key);
453 let volatile = C_bool(bx.cx, volatile);
454 bx.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
457 pub fn trans_instance<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, instance: Instance<'tcx>) {
458 let _s = if cx.sess().trans_stats() {
459 let mut instance_name = String::new();
460 DefPathBasedNames::new(cx.tcx, true, true)
461 .push_def_path(instance.def_id(), &mut instance_name);
462 Some(StatRecorder::new(cx, instance_name))
467 // this is an info! to allow collecting monomorphization statistics
468 // and to allow finding the last function before LLVM aborts from
470 info!("trans_instance({})", instance);
472 let fn_ty = instance.ty(cx.tcx);
473 let sig = common::ty_fn_sig(cx, fn_ty);
474 let sig = cx.tcx.erase_late_bound_regions_and_normalize(&sig);
476 let lldecl = match cx.instances.borrow().get(&instance) {
478 None => bug!("Instance `{:?}` not already declared", instance)
481 cx.stats.borrow_mut().n_closures += 1;
483 // The `uwtable` attribute according to LLVM is:
485 // This attribute indicates that the ABI being targeted requires that an
486 // unwind table entry be produced for this function even if we can show
487 // that no exceptions passes by it. This is normally the case for the
488 // ELF x86-64 abi, but it can be disabled for some compilation units.
490 // Typically when we're compiling with `-C panic=abort` (which implies this
491 // `no_landing_pads` check) we don't need `uwtable` because we can't
492 // generate any exceptions! On Windows, however, exceptions include other
493 // events such as illegal instructions, segfaults, etc. This means that on
494 // Windows we end up still needing the `uwtable` attribute even if the `-C
495 // panic=abort` flag is passed.
497 // You can also find more info on why Windows is whitelisted here in:
498 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
499 if !cx.sess().no_landing_pads() ||
500 cx.sess().target.target.options.is_like_windows {
501 attributes::emit_uwtable(lldecl, true);
504 let mir = cx.tcx.instance_mir(instance.def);
505 mir::trans_mir(cx, lldecl, &mir, instance, sig);
508 pub fn set_link_section(cx: &CodegenCx,
510 attrs: &[ast::Attribute]) {
511 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
512 if contains_null(§.as_str()) {
513 cx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
516 let buf = CString::new(sect.as_str().as_bytes()).unwrap();
517 llvm::LLVMSetSection(llval, buf.as_ptr());
522 /// Create the `main` function which will initialize the rust runtime and call
523 /// users main function.
524 fn maybe_create_entry_wrapper(cx: &CodegenCx) {
525 let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
526 Some((id, span)) => {
527 (cx.tcx.hir.local_def_id(id), span)
532 let instance = Instance::mono(cx.tcx, main_def_id);
534 if !cx.codegen_unit.contains_item(&MonoItem::Fn(instance)) {
535 // We want to create the wrapper in the same codegen unit as Rust's main
540 let main_llfn = callee::get_fn(cx, instance);
542 let et = cx.sess().entry_type.get().unwrap();
544 config::EntryMain => create_entry_fn(cx, span, main_llfn, main_def_id, true),
545 config::EntryStart => create_entry_fn(cx, span, main_llfn, main_def_id, false),
546 config::EntryNone => {} // Do nothing.
549 fn create_entry_fn<'cx>(cx: &'cx CodegenCx,
552 rust_main_def_id: DefId,
553 use_start_lang_item: bool) {
554 let llfty = Type::func(&[Type::c_int(cx), Type::i8p(cx).ptr_to()], &Type::c_int(cx));
556 let main_ret_ty = cx.tcx.fn_sig(rust_main_def_id).output();
557 // Given that `main()` has no arguments,
558 // then its return type cannot have
559 // late-bound regions, since late-bound
560 // regions must appear in the argument
562 let main_ret_ty = main_ret_ty.no_late_bound_regions().unwrap();
564 if declare::get_defined_value(cx, "main").is_some() {
565 // FIXME: We should be smart and show a better diagnostic here.
566 cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
567 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
569 cx.sess().abort_if_errors();
572 let llfn = declare::declare_cfn(cx, "main", llfty);
574 // `main` should respect same config for frame pointer elimination as rest of code
575 attributes::set_frame_pointer_elimination(cx, llfn);
577 let bx = Builder::new_block(cx, llfn, "top");
579 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(&bx);
581 // Params from native main() used as args for rust start function
582 let param_argc = get_param(llfn, 0);
583 let param_argv = get_param(llfn, 1);
584 let arg_argc = bx.intcast(param_argc, cx.isize_ty, true);
585 let arg_argv = param_argv;
587 let (start_fn, args) = if use_start_lang_item {
588 let start_def_id = cx.tcx.require_lang_item(StartFnLangItem);
589 let start_fn = callee::resolve_and_get_fn(cx, start_def_id, cx.tcx.mk_substs(
590 iter::once(Kind::from(main_ret_ty))));
591 (start_fn, vec![bx.pointercast(rust_main, Type::i8p(cx).ptr_to()),
594 debug!("using user-defined start fn");
595 (rust_main, vec![arg_argc, arg_argv])
598 let result = bx.call(start_fn, &args, None);
599 bx.ret(bx.intcast(result, Type::c_int(cx), true));
603 fn contains_null(s: &str) -> bool {
604 s.bytes().any(|b| b == 0)
607 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
609 link_meta: &LinkMeta,
610 exported_symbols: &NodeSet)
611 -> (ContextRef, ModuleRef, EncodedMetadata) {
613 use flate2::Compression;
614 use flate2::write::DeflateEncoder;
616 let (metadata_llcx, metadata_llmod) = unsafe {
617 context::create_context_and_module(tcx.sess, llmod_id)
620 #[derive(PartialEq, Eq, PartialOrd, Ord)]
627 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
629 config::CrateTypeExecutable |
630 config::CrateTypeStaticlib |
631 config::CrateTypeCdylib => MetadataKind::None,
633 config::CrateTypeRlib => MetadataKind::Uncompressed,
635 config::CrateTypeDylib |
636 config::CrateTypeProcMacro => MetadataKind::Compressed,
640 if kind == MetadataKind::None {
641 return (metadata_llcx,
643 EncodedMetadata::new());
646 let metadata = tcx.encode_metadata(link_meta, exported_symbols);
647 if kind == MetadataKind::Uncompressed {
648 return (metadata_llcx, metadata_llmod, metadata);
651 assert!(kind == MetadataKind::Compressed);
652 let mut compressed = tcx.metadata_encoding_version();
653 DeflateEncoder::new(&mut compressed, Compression::fast())
654 .write_all(&metadata.raw_data).unwrap();
656 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
657 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
658 let name = symbol_export::metadata_symbol_name(tcx);
659 let buf = CString::new(name).unwrap();
660 let llglobal = unsafe {
661 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
664 llvm::LLVMSetInitializer(llglobal, llconst);
665 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
666 let name = CString::new(section_name).unwrap();
667 llvm::LLVMSetSection(llglobal, name.as_ptr());
669 // Also generate a .section directive to force no
670 // flags, at least for ELF outputs, so that the
671 // metadata doesn't get loaded into memory.
672 let directive = format!(".section {}", section_name);
673 let directive = CString::new(directive).unwrap();
674 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
676 return (metadata_llcx, metadata_llmod, metadata);
679 pub struct ValueIter {
681 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
684 impl Iterator for ValueIter {
685 type Item = ValueRef;
687 fn next(&mut self) -> Option<ValueRef> {
690 self.cur = unsafe { (self.step)(old) };
698 pub fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
701 cur: llvm::LLVMGetFirstGlobal(llmod),
702 step: llvm::LLVMGetNextGlobal,
707 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
708 rx: mpsc::Receiver<Box<Any + Send>>)
709 -> OngoingCrateTranslation {
711 check_for_rustc_errors_attr(tcx);
713 if let Some(true) = tcx.sess.opts.debugging_opts.thinlto {
714 if unsafe { !llvm::LLVMRustThinLTOAvailable() } {
715 tcx.sess.fatal("this compiler's LLVM does not support ThinLTO");
719 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
720 let link_meta = link::build_link_meta(crate_hash);
721 let exported_symbol_node_ids = find_exported_symbols(tcx);
723 // Translate the metadata.
724 let llmod_id = "metadata";
725 let (metadata_llcx, metadata_llmod, metadata) =
726 time(tcx.sess.time_passes(), "write metadata", || {
727 write_metadata(tcx, llmod_id, &link_meta, &exported_symbol_node_ids)
730 let metadata_module = ModuleTranslation {
731 name: link::METADATA_MODULE_NAME.to_string(),
732 llmod_id: llmod_id.to_string(),
733 source: ModuleSource::Translated(ModuleLlvm {
735 llmod: metadata_llmod,
736 tm: create_target_machine(tcx.sess),
738 kind: ModuleKind::Metadata,
741 let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
742 Some(time_graph::TimeGraph::new())
747 // Skip crate items and just output metadata in -Z no-trans mode.
748 if tcx.sess.opts.debugging_opts.no_trans ||
749 !tcx.sess.opts.output_types.should_trans() {
750 let ongoing_translation = write::start_async_translation(
758 ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
759 ongoing_translation.translation_finished(tcx);
761 assert_and_save_dep_graph(tcx);
763 ongoing_translation.check_for_errors(tcx.sess);
765 return ongoing_translation;
768 // Run the translation item collector and partition the collected items into
771 tcx.collect_and_partition_translation_items(LOCAL_CRATE).1;
772 let codegen_units = (*codegen_units).clone();
774 // Force all codegen_unit queries so they are already either red or green
775 // when compile_codegen_unit accesses them. We are not able to re-execute
776 // the codegen_unit query from just the DepNode, so an unknown color would
777 // lead to having to re-execute compile_codegen_unit, possibly
779 if tcx.dep_graph.is_fully_enabled() {
780 for cgu in &codegen_units {
781 tcx.codegen_unit(cgu.name().clone());
785 let ongoing_translation = write::start_async_translation(
791 codegen_units.len());
793 // Translate an allocator shim, if any
794 let allocator_module = if let Some(kind) = tcx.sess.allocator_kind.get() {
796 let llmod_id = "allocator";
798 context::create_context_and_module(tcx.sess, llmod_id);
799 let modules = ModuleLlvm {
802 tm: create_target_machine(tcx.sess),
804 time(tcx.sess.time_passes(), "write allocator module", || {
805 allocator::trans(tcx, &modules, kind)
808 Some(ModuleTranslation {
809 name: link::ALLOCATOR_MODULE_NAME.to_string(),
810 llmod_id: llmod_id.to_string(),
811 source: ModuleSource::Translated(modules),
812 kind: ModuleKind::Allocator,
819 if let Some(allocator_module) = allocator_module {
820 ongoing_translation.submit_pre_translated_module_to_llvm(tcx, allocator_module);
823 ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
825 // We sort the codegen units by size. This way we can schedule work for LLVM
826 // a bit more efficiently.
827 let codegen_units = {
828 let mut codegen_units = codegen_units;
829 codegen_units.sort_by_key(|cgu| usize::MAX - cgu.size_estimate());
833 let mut total_trans_time = Duration::new(0, 0);
834 let mut all_stats = Stats::default();
836 for cgu in codegen_units.into_iter() {
837 ongoing_translation.wait_for_signal_to_translate_item();
838 ongoing_translation.check_for_errors(tcx.sess);
840 // First, if incremental compilation is enabled, we try to re-use the
841 // codegen unit from the cache.
842 if tcx.dep_graph.is_fully_enabled() {
843 let cgu_id = cgu.work_product_id();
845 // Check whether there is a previous work-product we can
846 // re-use. Not only must the file exist, and the inputs not
847 // be dirty, but the hash of the symbols we will generate must
849 if let Some(buf) = tcx.dep_graph.previous_work_product(&cgu_id) {
850 let dep_node = &DepNode::new(tcx,
851 DepConstructor::CompileCodegenUnit(cgu.name().clone()));
853 // We try to mark the DepNode::CompileCodegenUnit green. If we
854 // succeed it means that none of the dependencies has changed
855 // and we can safely re-use.
856 if let Some(dep_node_index) = tcx.dep_graph.try_mark_green(tcx, dep_node) {
857 // Append ".rs" to LLVM module identifier.
859 // LLVM code generator emits a ".file filename" directive
860 // for ELF backends. Value of the "filename" is set as the
861 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
862 // crashes if the module identifier is same as other symbols
863 // such as a function name in the module.
864 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
865 let llmod_id = format!("{}.rs", cgu.name());
867 let module = ModuleTranslation {
868 name: cgu.name().to_string(),
869 source: ModuleSource::Preexisting(buf),
870 kind: ModuleKind::Regular,
873 tcx.dep_graph.mark_loaded_from_cache(dep_node_index, true);
874 write::submit_translated_module_to_llvm(tcx, module, 0);
875 // Continue to next cgu, this one is done.
879 // This can happen if files were deleted from the cache
880 // directory for some reason. We just re-compile then.
884 let _timing_guard = time_graph.as_ref().map(|time_graph| {
885 time_graph.start(write::TRANS_WORKER_TIMELINE,
886 write::TRANS_WORK_PACKAGE_KIND,
887 &format!("codegen {}", cgu.name()))
889 let start_time = Instant::now();
890 all_stats.extend(tcx.compile_codegen_unit(*cgu.name()));
891 total_trans_time += start_time.elapsed();
892 ongoing_translation.check_for_errors(tcx.sess);
895 ongoing_translation.translation_finished(tcx);
897 // Since the main thread is sometimes blocked during trans, we keep track
898 // -Ztime-passes output manually.
899 print_time_passes_entry(tcx.sess.time_passes(),
900 "translate to LLVM IR",
903 if tcx.sess.opts.incremental.is_some() {
904 ::rustc_incremental::assert_module_sources::assert_module_sources(tcx);
907 symbol_names_test::report_symbol_names(tcx);
909 if tcx.sess.trans_stats() {
910 println!("--- trans stats ---");
911 println!("n_glues_created: {}", all_stats.n_glues_created);
912 println!("n_null_glues: {}", all_stats.n_null_glues);
913 println!("n_real_glues: {}", all_stats.n_real_glues);
915 println!("n_fns: {}", all_stats.n_fns);
916 println!("n_inlines: {}", all_stats.n_inlines);
917 println!("n_closures: {}", all_stats.n_closures);
918 println!("fn stats:");
919 all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
920 for &(ref name, insns) in all_stats.fn_stats.iter() {
921 println!("{} insns, {}", insns, *name);
925 if tcx.sess.count_llvm_insns() {
926 for (k, v) in all_stats.llvm_insns.iter() {
927 println!("{:7} {}", *v, *k);
931 ongoing_translation.check_for_errors(tcx.sess);
933 assert_and_save_dep_graph(tcx);
937 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
938 time(tcx.sess.time_passes(),
940 || rustc_incremental::assert_dep_graph(tcx));
942 time(tcx.sess.time_passes(),
943 "serialize dep graph",
944 || rustc_incremental::save_dep_graph(tcx));
947 fn collect_and_partition_translation_items<'a, 'tcx>(
948 tcx: TyCtxt<'a, 'tcx, 'tcx>,
950 ) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
952 assert_eq!(cnum, LOCAL_CRATE);
953 let time_passes = tcx.sess.time_passes();
955 let collection_mode = match tcx.sess.opts.debugging_opts.print_trans_items {
957 let mode_string = s.to_lowercase();
958 let mode_string = mode_string.trim();
959 if mode_string == "eager" {
960 MonoItemCollectionMode::Eager
962 if mode_string != "lazy" {
963 let message = format!("Unknown codegen-item collection mode '{}'. \
964 Falling back to 'lazy' mode.",
966 tcx.sess.warn(&message);
969 MonoItemCollectionMode::Lazy
973 if tcx.sess.opts.cg.link_dead_code {
974 MonoItemCollectionMode::Eager
976 MonoItemCollectionMode::Lazy
981 let (items, inlining_map) =
982 time(time_passes, "translation item collection", || {
983 collector::collect_crate_mono_items(tcx, collection_mode)
986 ::rustc_mir::monomorphize::assert_symbols_are_distinct(tcx, items.iter());
988 let strategy = if tcx.sess.opts.incremental.is_some() {
989 PartitioningStrategy::PerModule
991 PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
994 let codegen_units = time(time_passes, "codegen unit partitioning", || {
995 partitioning::partition(tcx,
996 items.iter().cloned(),
1001 .collect::<Vec<_>>()
1004 let translation_items: DefIdSet = items.iter().filter_map(|trans_item| {
1006 MonoItem::Fn(ref instance) => Some(instance.def_id()),
1007 MonoItem::Static(def_id) => Some(def_id),
1012 if tcx.sess.opts.debugging_opts.print_trans_items.is_some() {
1013 let mut item_to_cgus = FxHashMap();
1015 for cgu in &codegen_units {
1016 for (&trans_item, &linkage) in cgu.items() {
1017 item_to_cgus.entry(trans_item)
1018 .or_insert(Vec::new())
1019 .push((cgu.name().clone(), linkage));
1023 let mut item_keys: Vec<_> = items
1026 let mut output = i.to_string(tcx);
1027 output.push_str(" @@");
1028 let mut empty = Vec::new();
1029 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1030 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1032 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1033 output.push_str(" ");
1034 output.push_str(&cgu_name);
1036 let linkage_abbrev = match linkage {
1037 Linkage::External => "External",
1038 Linkage::AvailableExternally => "Available",
1039 Linkage::LinkOnceAny => "OnceAny",
1040 Linkage::LinkOnceODR => "OnceODR",
1041 Linkage::WeakAny => "WeakAny",
1042 Linkage::WeakODR => "WeakODR",
1043 Linkage::Appending => "Appending",
1044 Linkage::Internal => "Internal",
1045 Linkage::Private => "Private",
1046 Linkage::ExternalWeak => "ExternalWeak",
1047 Linkage::Common => "Common",
1050 output.push_str("[");
1051 output.push_str(linkage_abbrev);
1052 output.push_str("]");
1060 for item in item_keys {
1061 println!("TRANS_ITEM {}", item);
1065 (Arc::new(translation_items), Arc::new(codegen_units))
1069 pub fn new(tcx: TyCtxt) -> CrateInfo {
1070 let mut info = CrateInfo {
1071 panic_runtime: None,
1072 compiler_builtins: None,
1073 profiler_runtime: None,
1074 sanitizer_runtime: None,
1075 is_no_builtins: FxHashSet(),
1076 native_libraries: FxHashMap(),
1077 used_libraries: tcx.native_libraries(LOCAL_CRATE),
1078 link_args: tcx.link_args(LOCAL_CRATE),
1079 crate_name: FxHashMap(),
1080 used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1081 used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1082 used_crate_source: FxHashMap(),
1085 for &cnum in tcx.crates().iter() {
1086 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1087 info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1088 info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1089 if tcx.is_panic_runtime(cnum) {
1090 info.panic_runtime = Some(cnum);
1092 if tcx.is_compiler_builtins(cnum) {
1093 info.compiler_builtins = Some(cnum);
1095 if tcx.is_profiler_runtime(cnum) {
1096 info.profiler_runtime = Some(cnum);
1098 if tcx.is_sanitizer_runtime(cnum) {
1099 info.sanitizer_runtime = Some(cnum);
1101 if tcx.is_no_builtins(cnum) {
1102 info.is_no_builtins.insert(cnum);
1111 fn is_translated_item(tcx: TyCtxt, id: DefId) -> bool {
1112 let (all_trans_items, _) =
1113 tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1114 all_trans_items.contains(&id)
1117 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1118 cgu: InternedString) -> Stats {
1119 let cgu = tcx.codegen_unit(cgu);
1121 let start_time = Instant::now();
1122 let (stats, module) = module_translation(tcx, cgu);
1123 let time_to_translate = start_time.elapsed();
1125 // We assume that the cost to run LLVM on a CGU is proportional to
1126 // the time we needed for translating it.
1127 let cost = time_to_translate.as_secs() * 1_000_000_000 +
1128 time_to_translate.subsec_nanos() as u64;
1130 write::submit_translated_module_to_llvm(tcx,
1135 fn module_translation<'a, 'tcx>(
1136 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1137 cgu: Arc<CodegenUnit<'tcx>>)
1138 -> (Stats, ModuleTranslation)
1140 let cgu_name = cgu.name().to_string();
1142 // Append ".rs" to LLVM module identifier.
1144 // LLVM code generator emits a ".file filename" directive
1145 // for ELF backends. Value of the "filename" is set as the
1146 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
1147 // crashes if the module identifier is same as other symbols
1148 // such as a function name in the module.
1149 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
1150 let llmod_id = format!("{}-{}.rs",
1152 tcx.crate_disambiguator(LOCAL_CRATE)
1153 .to_fingerprint().to_hex());
1155 // Instantiate translation items without filling out definitions yet...
1156 let cx = CodegenCx::new(tcx, cgu, &llmod_id);
1158 let trans_items = cx.codegen_unit
1159 .items_in_deterministic_order(cx.tcx);
1160 for &(trans_item, (linkage, visibility)) in &trans_items {
1161 trans_item.predefine(&cx, linkage, visibility);
1164 // ... and now that we have everything pre-defined, fill out those definitions.
1165 for &(trans_item, _) in &trans_items {
1166 trans_item.define(&cx);
1169 // If this codegen unit contains the main function, also create the
1171 maybe_create_entry_wrapper(&cx);
1173 // Run replace-all-uses-with for statics that need it
1174 for &(old_g, new_g) in cx.statics_to_rauw.borrow().iter() {
1176 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1177 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1178 llvm::LLVMDeleteGlobal(old_g);
1182 // Create the llvm.used variable
1183 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1184 if !cx.used_statics.borrow().is_empty() {
1185 let name = CString::new("llvm.used").unwrap();
1186 let section = CString::new("llvm.metadata").unwrap();
1187 let array = C_array(Type::i8(&cx).ptr_to(), &*cx.used_statics.borrow());
1190 let g = llvm::LLVMAddGlobal(cx.llmod,
1191 val_ty(array).to_ref(),
1193 llvm::LLVMSetInitializer(g, array);
1194 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1195 llvm::LLVMSetSection(g, section.as_ptr());
1199 // Finalize debuginfo
1200 if cx.sess().opts.debuginfo != NoDebugInfo {
1201 debuginfo::finalize(&cx);
1204 let llvm_module = ModuleLlvm {
1207 tm: create_target_machine(cx.sess()),
1212 source: ModuleSource::Translated(llvm_module),
1213 kind: ModuleKind::Regular,
1218 (cx.into_stats(), module)
1222 pub fn provide(providers: &mut Providers) {
1223 providers.collect_and_partition_translation_items =
1224 collect_and_partition_translation_items;
1226 providers.is_translated_item = is_translated_item;
1228 providers.codegen_unit = |tcx, name| {
1229 let (_, all) = tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1231 .find(|cgu| *cgu.name() == name)
1233 .expect(&format!("failed to find cgu with name {:?}", name))
1235 providers.compile_codegen_unit = compile_codegen_unit;
1238 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1240 Linkage::External => llvm::Linkage::ExternalLinkage,
1241 Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1242 Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1243 Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1244 Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1245 Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1246 Linkage::Appending => llvm::Linkage::AppendingLinkage,
1247 Linkage::Internal => llvm::Linkage::InternalLinkage,
1248 Linkage::Private => llvm::Linkage::PrivateLinkage,
1249 Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1250 Linkage::Common => llvm::Linkage::CommonLinkage,
1254 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1256 Visibility::Default => llvm::Visibility::Default,
1257 Visibility::Hidden => llvm::Visibility::Hidden,
1258 Visibility::Protected => llvm::Visibility::Protected,
1262 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1263 // the HashStable trait. Normally DepGraph::with_task() calls are
1264 // hidden behind queries, but CGU creation is a special case in two
1265 // ways: (1) it's not a query and (2) CGU are output nodes, so their
1266 // Fingerprints are not actually needed. It remains to be clarified
1267 // how exactly this case will be handled in the red/green system but
1268 // for now we content ourselves with providing a no-op HashStable
1269 // implementation for CGUs.
1270 mod temp_stable_hash_impls {
1271 use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1273 use ModuleTranslation;
1275 impl<HCX> HashStable<HCX> for ModuleTranslation {
1276 fn hash_stable<W: StableHasherResult>(&self,
1278 _: &mut StableHasher<W>) {