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 //! Codegen the completed AST to the LLVM IR.
13 //! Some functions here, such as codegen_block and codegen_expr, return a value --
14 //! the result of the codegen to LLVM -- while others, such as codegen_fn
15 //! and mono_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 codegen:
20 //! * There's no way to find out the Ty type of a Value. Doing so
21 //! would be "trying to get the eggs out of an omelette" (credit:
22 //! pcwalton). You can, instead, find out its llvm::Type by calling val_ty,
23 //! but one llvm::Type corresponds to many `Ty`s; for instance, tup(int, int,
24 //! int) and rec(x=int, y=int, z=int) will have the same llvm::Type.
26 use super::ModuleLlvm;
27 use super::ModuleCodegen;
28 use super::ModuleKind;
29 use super::CachedModuleCodegen;
32 use back::write::{self, OngoingCodegen};
33 use llvm::{self, TypeKind, get_param};
35 use rustc::dep_graph::cgu_reuse_tracker::CguReuse;
36 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
37 use rustc::middle::lang_items::StartFnLangItem;
38 use rustc::middle::weak_lang_items;
39 use rustc::mir::mono::{Linkage, Visibility, Stats, CodegenUnitNameBuilder};
40 use rustc::middle::cstore::{EncodedMetadata};
41 use rustc::ty::{self, Ty, TyCtxt};
42 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf};
43 use rustc::ty::query::Providers;
44 use rustc::middle::cstore::{self, LinkagePreference};
45 use rustc::middle::exported_symbols;
46 use rustc::util::common::{time, print_time_passes_entry};
47 use rustc::util::profiling::ProfileCategory;
48 use rustc::session::config::{self, DebugInfo, EntryFnType, Lto};
49 use rustc::session::Session;
50 use rustc_incremental;
52 use mir::place::PlaceRef;
54 use builder::{Builder, MemFlags};
56 use common::{C_bool, C_bytes_in_context, C_i32, C_usize};
57 use rustc_mir::monomorphize::collector::{self, MonoItemCollectionMode};
58 use rustc_mir::monomorphize::item::DefPathBasedNames;
59 use common::{C_struct_in_context, C_array, val_ty};
61 use context::CodegenCx;
66 use monomorphize::Instance;
67 use monomorphize::partitioning::{self, PartitioningStrategy, CodegenUnit, CodegenUnitExt};
68 use rustc_codegen_utils::symbol_names_test;
70 use mono_item::{MonoItem, BaseMonoItemExt, MonoItemExt};
72 use type_of::LayoutLlvmExt;
73 use rustc::util::nodemap::{FxHashMap, DefIdSet};
75 use rustc_data_structures::small_c_str::SmallCStr;
76 use rustc_data_structures::sync::Lrc;
79 use std::ffi::CString;
81 use std::time::{Instant, Duration};
86 use syntax_pos::symbol::InternedString;
88 use rustc::hir::{self, CodegenFnAttrs};
92 use mir::operand::OperandValue;
94 use rustc_codegen_utils::check_for_rustc_errors_attr;
96 pub struct StatRecorder<'a, 'll: 'a, 'tcx: 'll> {
97 cx: &'a CodegenCx<'ll, 'tcx>,
102 impl StatRecorder<'a, 'll, 'tcx> {
103 pub fn new(cx: &'a CodegenCx<'ll, 'tcx>, name: String) -> Self {
104 let istart = cx.stats.borrow().n_llvm_insns;
113 impl Drop for StatRecorder<'a, 'll, 'tcx> {
115 if self.cx.sess().codegen_stats() {
116 let mut stats = self.cx.stats.borrow_mut();
117 let iend = stats.n_llvm_insns;
118 stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
120 // Reset LLVM insn count to avoid compound costs.
121 stats.n_llvm_insns = self.istart;
126 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind,
128 -> llvm::IntPredicate {
130 hir::BinOpKind::Eq => llvm::IntEQ,
131 hir::BinOpKind::Ne => llvm::IntNE,
132 hir::BinOpKind::Lt => if signed { llvm::IntSLT } else { llvm::IntULT },
133 hir::BinOpKind::Le => if signed { llvm::IntSLE } else { llvm::IntULE },
134 hir::BinOpKind::Gt => if signed { llvm::IntSGT } else { llvm::IntUGT },
135 hir::BinOpKind::Ge => if signed { llvm::IntSGE } else { llvm::IntUGE },
137 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
144 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> llvm::RealPredicate {
146 hir::BinOpKind::Eq => llvm::RealOEQ,
147 hir::BinOpKind::Ne => llvm::RealUNE,
148 hir::BinOpKind::Lt => llvm::RealOLT,
149 hir::BinOpKind::Le => llvm::RealOLE,
150 hir::BinOpKind::Gt => llvm::RealOGT,
151 hir::BinOpKind::Ge => llvm::RealOGE,
153 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
160 pub fn compare_simd_types(
161 bx: &Builder<'a, 'll, 'tcx>,
168 let signed = match t.sty {
170 let cmp = bin_op_to_fcmp_predicate(op);
171 return bx.sext(bx.fcmp(cmp, lhs, rhs), ret_ty);
173 ty::Uint(_) => false,
175 _ => bug!("compare_simd_types: invalid SIMD type"),
178 let cmp = bin_op_to_icmp_predicate(op, signed);
179 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
180 // to get the correctly sized type. This will compile to a single instruction
181 // once the IR is converted to assembly if the SIMD instruction is supported
182 // by the target architecture.
183 bx.sext(bx.icmp(cmp, lhs, rhs), ret_ty)
186 /// Retrieve the information we are losing (making dynamic) in an unsizing
189 /// The `old_info` argument is a bit funny. It is intended for use
190 /// in an upcast, where the new vtable for an object will be derived
191 /// from the old one.
193 cx: &CodegenCx<'ll, 'tcx>,
196 old_info: Option<&'ll Value>,
198 let (source, target) = cx.tcx.struct_lockstep_tails(source, target);
199 match (&source.sty, &target.sty) {
200 (&ty::Array(_, len), &ty::Slice(_)) => {
201 C_usize(cx, len.unwrap_usize(cx.tcx))
203 (&ty::Dynamic(..), &ty::Dynamic(..)) => {
204 // For now, upcasts are limited to changes in marker
205 // traits, and hence never actually require an actual
206 // change to the vtable.
207 old_info.expect("unsized_info: missing old info for trait upcast")
209 (_, &ty::Dynamic(ref data, ..)) => {
210 let vtable_ptr = cx.layout_of(cx.tcx.mk_mut_ptr(target))
211 .field(cx, abi::FAT_PTR_EXTRA);
212 consts::ptrcast(meth::get_vtable(cx, source, data.principal()),
213 vtable_ptr.llvm_type(cx))
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(
223 bx: &Builder<'a, 'll, 'tcx>,
227 ) -> (&'ll Value, &'ll Value) {
228 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
229 match (&src_ty.sty, &dst_ty.sty) {
233 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) |
234 (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }),
235 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
236 assert!(bx.cx.type_is_sized(a));
237 let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
238 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
240 (&ty::Adt(def_a, _), &ty::Adt(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!(bx.cx.type_is_sized(a));
243 let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
244 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
246 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
247 assert_eq!(def_a, def_b);
249 let src_layout = bx.cx.layout_of(src_ty);
250 let dst_layout = bx.cx.layout_of(dst_ty);
251 let mut result = None;
252 for i in 0..src_layout.fields.count() {
253 let src_f = src_layout.field(bx.cx, i);
254 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
255 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
259 assert_eq!(src_layout.size, src_f.size);
261 let dst_f = dst_layout.field(bx.cx, i);
262 assert_ne!(src_f.ty, dst_f.ty);
263 assert_eq!(result, None);
264 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
266 let (lldata, llextra) = result.unwrap();
267 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
268 (bx.bitcast(lldata, dst_layout.scalar_pair_element_llvm_type(bx.cx, 0, true)),
269 bx.bitcast(llextra, dst_layout.scalar_pair_element_llvm_type(bx.cx, 1, true)))
271 _ => bug!("unsize_thin_ptr: called on bad types"),
275 /// Coerce `src`, which is a reference to a value of type `src_ty`,
276 /// to a value of type `dst_ty` and store the result in `dst`
277 pub fn coerce_unsized_into(
278 bx: &Builder<'a, 'll, 'tcx>,
279 src: PlaceRef<'ll, 'tcx>,
280 dst: PlaceRef<'ll, 'tcx>
282 let src_ty = src.layout.ty;
283 let dst_ty = dst.layout.ty;
284 let coerce_ptr = || {
285 let (base, info) = match src.load(bx).val {
286 OperandValue::Pair(base, info) => {
287 // fat-ptr to fat-ptr unsize preserves the vtable
288 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
289 // So we need to pointercast the base to ensure
290 // the types match up.
291 let thin_ptr = dst.layout.field(bx.cx, abi::FAT_PTR_ADDR);
292 (bx.pointercast(base, thin_ptr.llvm_type(bx.cx)), info)
294 OperandValue::Immediate(base) => {
295 unsize_thin_ptr(bx, base, src_ty, dst_ty)
297 OperandValue::Ref(..) => bug!()
299 OperandValue::Pair(base, info).store(bx, dst);
301 match (&src_ty.sty, &dst_ty.sty) {
302 (&ty::Ref(..), &ty::Ref(..)) |
303 (&ty::Ref(..), &ty::RawPtr(..)) |
304 (&ty::RawPtr(..), &ty::RawPtr(..)) => {
307 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
311 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
312 assert_eq!(def_a, def_b);
314 for i in 0..def_a.variants[0].fields.len() {
315 let src_f = src.project_field(bx, i);
316 let dst_f = dst.project_field(bx, i);
318 if dst_f.layout.is_zst() {
322 if src_f.layout.ty == dst_f.layout.ty {
323 memcpy_ty(bx, dst_f.llval, src_f.llval, src_f.layout,
324 src_f.align.min(dst_f.align), MemFlags::empty());
326 coerce_unsized_into(bx, src_f, dst_f);
330 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
336 pub fn cast_shift_expr_rhs(
337 cx: &Builder<'_, 'll, '_>, op: hir::BinOpKind, lhs: &'ll Value, rhs: &'ll Value
339 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
342 fn cast_shift_rhs<'ll, F, G>(op: hir::BinOpKind,
348 where F: FnOnce(&'ll Value, &'ll Type) -> &'ll Value,
349 G: FnOnce(&'ll Value, &'ll Type) -> &'ll Value
351 // Shifts may have any size int on the rhs
353 let mut rhs_llty = val_ty(rhs);
354 let mut lhs_llty = val_ty(lhs);
355 if rhs_llty.kind() == TypeKind::Vector {
356 rhs_llty = rhs_llty.element_type()
358 if lhs_llty.kind() == TypeKind::Vector {
359 lhs_llty = lhs_llty.element_type()
361 let rhs_sz = rhs_llty.int_width();
362 let lhs_sz = lhs_llty.int_width();
365 } else if lhs_sz > rhs_sz {
366 // FIXME (#1877: If in the future shifting by negative
367 // values is no longer undefined then this is wrong.
377 /// Returns whether this session's target will use SEH-based unwinding.
379 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
380 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
381 /// 64-bit MinGW) instead of "full SEH".
382 pub fn wants_msvc_seh(sess: &Session) -> bool {
383 sess.target.target.options.is_like_msvc
386 pub fn call_assume(bx: &Builder<'_, 'll, '_>, val: &'ll Value) {
387 let assume_intrinsic = bx.cx.get_intrinsic("llvm.assume");
388 bx.call(assume_intrinsic, &[val], None);
391 pub fn from_immediate(bx: &Builder<'_, 'll, '_>, val: &'ll Value) -> &'ll Value {
392 if val_ty(val) == Type::i1(bx.cx) {
393 bx.zext(val, Type::i8(bx.cx))
400 bx: &Builder<'_, 'll, '_>,
402 layout: layout::TyLayout,
404 if let layout::Abi::Scalar(ref scalar) = layout.abi {
405 return to_immediate_scalar(bx, val, scalar);
410 pub fn to_immediate_scalar(
411 bx: &Builder<'_, 'll, '_>,
413 scalar: &layout::Scalar,
415 if scalar.is_bool() {
416 return bx.trunc(val, Type::i1(bx.cx));
422 bx: &Builder<'_, 'll, '_>,
429 if flags.contains(MemFlags::NONTEMPORAL) {
430 // HACK(nox): This is inefficient but there is no nontemporal memcpy.
431 let val = bx.load(src, align);
432 let ptr = bx.pointercast(dst, val_ty(val).ptr_to());
433 bx.store_with_flags(val, ptr, align, flags);
437 let ptr_width = &cx.sess().target.target.target_pointer_width;
438 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
439 let memcpy = cx.get_intrinsic(&key);
440 let src_ptr = bx.pointercast(src, Type::i8p(cx));
441 let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
442 let size = bx.intcast(n_bytes, cx.isize_ty, false);
443 let align = C_i32(cx, align.abi() as i32);
444 let volatile = C_bool(cx, flags.contains(MemFlags::VOLATILE));
445 bx.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
449 bx: &Builder<'_, 'll, 'tcx>,
452 layout: TyLayout<'tcx>,
456 let size = layout.size.bytes();
461 call_memcpy(bx, dst, src, C_usize(bx.cx, size), align, flags);
465 bx: &Builder<'_, 'll, '_>,
467 fill_byte: &'ll Value,
472 let ptr_width = &bx.cx.sess().target.target.target_pointer_width;
473 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
474 let llintrinsicfn = bx.cx.get_intrinsic(&intrinsic_key);
475 let volatile = C_bool(bx.cx, volatile);
476 bx.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
479 pub fn codegen_instance<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, instance: Instance<'tcx>) {
480 let _s = if cx.sess().codegen_stats() {
481 let mut instance_name = String::new();
482 DefPathBasedNames::new(cx.tcx, true, true)
483 .push_def_path(instance.def_id(), &mut instance_name);
484 Some(StatRecorder::new(cx, instance_name))
489 // this is an info! to allow collecting monomorphization statistics
490 // and to allow finding the last function before LLVM aborts from
492 info!("codegen_instance({})", instance);
494 let sig = instance.fn_sig(cx.tcx);
495 let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
497 let lldecl = cx.instances.borrow().get(&instance).cloned().unwrap_or_else(||
498 bug!("Instance `{:?}` not already declared", instance));
500 cx.stats.borrow_mut().n_closures += 1;
502 let mir = cx.tcx.instance_mir(instance.def);
503 mir::codegen_mir(cx, lldecl, &mir, instance, sig);
506 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
507 let sect = match attrs.link_section {
512 let buf = SmallCStr::new(§.as_str());
513 llvm::LLVMSetSection(llval, buf.as_ptr());
517 /// Create the `main` function which will initialize the rust runtime and call
518 /// users main function.
519 fn maybe_create_entry_wrapper(cx: &CodegenCx) {
520 let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
521 Some((id, span, _)) => {
522 (cx.tcx.hir.local_def_id(id), span)
527 let instance = Instance::mono(cx.tcx, main_def_id);
529 if !cx.codegen_unit.contains_item(&MonoItem::Fn(instance)) {
530 // We want to create the wrapper in the same codegen unit as Rust's main
535 let main_llfn = callee::get_fn(cx, instance);
537 let et = cx.sess().entry_fn.get().map(|e| e.2);
539 Some(EntryFnType::Main) => create_entry_fn(cx, span, main_llfn, main_def_id, true),
540 Some(EntryFnType::Start) => create_entry_fn(cx, span, main_llfn, main_def_id, false),
541 None => {} // Do nothing.
545 cx: &CodegenCx<'ll, '_>,
547 rust_main: &'ll Value,
548 rust_main_def_id: DefId,
549 use_start_lang_item: bool,
551 let llfty = Type::func(&[Type::c_int(cx), Type::i8p(cx).ptr_to()], Type::c_int(cx));
553 let main_ret_ty = cx.tcx.fn_sig(rust_main_def_id).output();
554 // Given that `main()` has no arguments,
555 // then its return type cannot have
556 // late-bound regions, since late-bound
557 // regions must appear in the argument
559 let main_ret_ty = cx.tcx.erase_regions(
560 &main_ret_ty.no_late_bound_regions().unwrap(),
563 if declare::get_defined_value(cx, "main").is_some() {
564 // FIXME: We should be smart and show a better diagnostic here.
565 cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
566 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
568 cx.sess().abort_if_errors();
571 let llfn = declare::declare_cfn(cx, "main", llfty);
573 // `main` should respect same config for frame pointer elimination as rest of code
574 attributes::set_frame_pointer_elimination(cx, llfn);
575 attributes::apply_target_cpu_attr(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(
592 cx.tcx.intern_substs(&[main_ret_ty.into()]),
594 (start_fn, vec![bx.pointercast(rust_main, Type::i8p(cx).ptr_to()),
597 debug!("using user-defined start fn");
598 (rust_main, vec![arg_argc, arg_argv])
601 let result = bx.call(start_fn, &args, None);
602 bx.ret(bx.intcast(result, Type::c_int(cx), true));
606 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
607 llvm_module: &ModuleLlvm)
610 use flate2::Compression;
611 use flate2::write::DeflateEncoder;
613 let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
615 #[derive(PartialEq, Eq, PartialOrd, Ord)]
622 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
624 config::CrateType::Executable |
625 config::CrateType::Staticlib |
626 config::CrateType::Cdylib => MetadataKind::None,
628 config::CrateType::Rlib => MetadataKind::Uncompressed,
630 config::CrateType::Dylib |
631 config::CrateType::ProcMacro => MetadataKind::Compressed,
633 }).max().unwrap_or(MetadataKind::None);
635 if kind == MetadataKind::None {
636 return EncodedMetadata::new();
639 let metadata = tcx.encode_metadata();
640 if kind == MetadataKind::Uncompressed {
644 assert!(kind == MetadataKind::Compressed);
645 let mut compressed = tcx.metadata_encoding_version();
646 DeflateEncoder::new(&mut compressed, Compression::fast())
647 .write_all(&metadata.raw_data).unwrap();
649 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
650 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
651 let name = exported_symbols::metadata_symbol_name(tcx);
652 let buf = CString::new(name).unwrap();
653 let llglobal = unsafe {
654 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst), buf.as_ptr())
657 llvm::LLVMSetInitializer(llglobal, llconst);
658 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
659 let name = SmallCStr::new(section_name);
660 llvm::LLVMSetSection(llglobal, name.as_ptr());
662 // Also generate a .section directive to force no
663 // flags, at least for ELF outputs, so that the
664 // metadata doesn't get loaded into memory.
665 let directive = format!(".section {}", section_name);
666 let directive = CString::new(directive).unwrap();
667 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
672 pub struct ValueIter<'ll> {
673 cur: Option<&'ll Value>,
674 step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
677 impl Iterator for ValueIter<'ll> {
678 type Item = &'ll Value;
680 fn next(&mut self) -> Option<&'ll Value> {
682 if let Some(old) = old {
683 self.cur = unsafe { (self.step)(old) };
689 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
692 cur: llvm::LLVMGetFirstGlobal(llmod),
693 step: llvm::LLVMGetNextGlobal,
698 fn determine_cgu_reuse<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
699 cgu: &CodegenUnit<'tcx>)
701 if !tcx.dep_graph.is_fully_enabled() {
705 let work_product_id = &cgu.work_product_id();
706 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
707 // We don't have anything cached for this CGU. This can happen
708 // if the CGU did not exist in the previous session.
712 // Try to mark the CGU as green. If it we can do so, it means that nothing
713 // affecting the LLVM module has changed and we can re-use a cached version.
714 // If we compile with any kind of LTO, this means we can re-use the bitcode
715 // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
716 // know that later). If we are not doing LTO, there is only one optimized
717 // version of each module, so we re-use that.
718 let dep_node = cgu.codegen_dep_node(tcx);
719 assert!(!tcx.dep_graph.dep_node_exists(&dep_node),
720 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
723 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
724 // We can re-use either the pre- or the post-thinlto state
725 if tcx.sess.lto() != Lto::No {
735 pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
736 rx: mpsc::Receiver<Box<dyn Any + Send>>)
739 check_for_rustc_errors_attr(tcx);
741 if let Some(true) = tcx.sess.opts.debugging_opts.thinlto {
742 if unsafe { !llvm::LLVMRustThinLTOAvailable() } {
743 tcx.sess.fatal("this compiler's LLVM does not support ThinLTO");
747 if (tcx.sess.opts.debugging_opts.pgo_gen.is_some() ||
748 !tcx.sess.opts.debugging_opts.pgo_use.is_empty()) &&
749 unsafe { !llvm::LLVMRustPGOAvailable() }
751 tcx.sess.fatal("this compiler's LLVM does not support PGO");
754 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
756 // Codegen the metadata.
757 tcx.sess.profiler(|p| p.start_activity(ProfileCategory::Codegen));
759 let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
761 Some("metadata")).as_str()
763 let metadata_llvm_module = ModuleLlvm::new(tcx.sess, &metadata_cgu_name);
764 let metadata = time(tcx.sess, "write metadata", || {
765 write_metadata(tcx, &metadata_llvm_module)
767 tcx.sess.profiler(|p| p.end_activity(ProfileCategory::Codegen));
769 let metadata_module = ModuleCodegen {
770 name: metadata_cgu_name,
771 module_llvm: metadata_llvm_module,
772 kind: ModuleKind::Metadata,
775 let time_graph = if tcx.sess.opts.debugging_opts.codegen_time_graph {
776 Some(time_graph::TimeGraph::new())
781 // Skip crate items and just output metadata in -Z no-codegen mode.
782 if tcx.sess.opts.debugging_opts.no_codegen ||
783 !tcx.sess.opts.output_types.should_codegen() {
784 let ongoing_codegen = write::start_async_codegen(
791 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
792 ongoing_codegen.codegen_finished(tcx);
794 assert_and_save_dep_graph(tcx);
796 ongoing_codegen.check_for_errors(tcx.sess);
798 return ongoing_codegen;
801 // Run the monomorphization collector and partition the collected items into
803 let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
804 let codegen_units = (*codegen_units).clone();
806 // Force all codegen_unit queries so they are already either red or green
807 // when compile_codegen_unit accesses them. We are not able to re-execute
808 // the codegen_unit query from just the DepNode, so an unknown color would
809 // lead to having to re-execute compile_codegen_unit, possibly
811 if tcx.dep_graph.is_fully_enabled() {
812 for cgu in &codegen_units {
813 tcx.codegen_unit(cgu.name().clone());
817 let ongoing_codegen = write::start_async_codegen(
822 codegen_units.len());
824 // Codegen an allocator shim, if necessary.
826 // If the crate doesn't have an `allocator_kind` set then there's definitely
827 // no shim to generate. Otherwise we also check our dependency graph for all
828 // our output crate types. If anything there looks like its a `Dynamic`
829 // linkage, then it's already got an allocator shim and we'll be using that
830 // one instead. If nothing exists then it's our job to generate the
832 let any_dynamic_crate = tcx.sess.dependency_formats.borrow()
835 use rustc::middle::dependency_format::Linkage;
836 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
838 let allocator_module = if any_dynamic_crate {
840 } else if let Some(kind) = *tcx.sess.allocator_kind.get() {
841 let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
843 Some("allocator")).as_str()
845 let modules = ModuleLlvm::new(tcx.sess, &llmod_id);
846 time(tcx.sess, "write allocator module", || {
848 allocator::codegen(tcx, &modules, kind)
854 module_llvm: modules,
855 kind: ModuleKind::Allocator,
861 if let Some(allocator_module) = allocator_module {
862 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
865 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
867 // We sort the codegen units by size. This way we can schedule work for LLVM
868 // a bit more efficiently.
869 let codegen_units = {
870 let mut codegen_units = codegen_units;
871 codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
875 let mut total_codegen_time = Duration::new(0, 0);
876 let mut all_stats = Stats::default();
878 for cgu in codegen_units.into_iter() {
879 ongoing_codegen.wait_for_signal_to_codegen_item();
880 ongoing_codegen.check_for_errors(tcx.sess);
882 let cgu_reuse = determine_cgu_reuse(tcx, &cgu);
883 tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
887 let _timing_guard = time_graph.as_ref().map(|time_graph| {
888 time_graph.start(write::CODEGEN_WORKER_TIMELINE,
889 write::CODEGEN_WORK_PACKAGE_KIND,
890 &format!("codegen {}", cgu.name()))
892 let start_time = Instant::now();
893 let stats = compile_codegen_unit(tcx, *cgu.name());
894 all_stats.extend(stats);
895 total_codegen_time += start_time.elapsed();
898 CguReuse::PreLto => {
899 write::submit_pre_lto_module_to_llvm(tcx, CachedModuleCodegen {
900 name: cgu.name().to_string(),
901 source: cgu.work_product(tcx),
905 CguReuse::PostLto => {
906 write::submit_post_lto_module_to_llvm(tcx, CachedModuleCodegen {
907 name: cgu.name().to_string(),
908 source: cgu.work_product(tcx),
915 ongoing_codegen.codegen_finished(tcx);
917 // Since the main thread is sometimes blocked during codegen, we keep track
918 // -Ztime-passes output manually.
919 print_time_passes_entry(tcx.sess.time_passes(),
920 "codegen to LLVM IR",
923 rustc_incremental::assert_module_sources::assert_module_sources(tcx);
925 symbol_names_test::report_symbol_names(tcx);
927 if tcx.sess.codegen_stats() {
928 println!("--- codegen stats ---");
929 println!("n_glues_created: {}", all_stats.n_glues_created);
930 println!("n_null_glues: {}", all_stats.n_null_glues);
931 println!("n_real_glues: {}", all_stats.n_real_glues);
933 println!("n_fns: {}", all_stats.n_fns);
934 println!("n_inlines: {}", all_stats.n_inlines);
935 println!("n_closures: {}", all_stats.n_closures);
936 println!("fn stats:");
937 all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
938 for &(ref name, insns) in all_stats.fn_stats.iter() {
939 println!("{} insns, {}", insns, *name);
943 if tcx.sess.count_llvm_insns() {
944 for (k, v) in all_stats.llvm_insns.iter() {
945 println!("{:7} {}", *v, *k);
949 ongoing_codegen.check_for_errors(tcx.sess);
951 assert_and_save_dep_graph(tcx);
955 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
958 || rustc_incremental::assert_dep_graph(tcx));
961 "serialize dep graph",
962 || rustc_incremental::save_dep_graph(tcx));
965 fn collect_and_partition_mono_items<'a, 'tcx>(
966 tcx: TyCtxt<'a, 'tcx, 'tcx>,
968 ) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
970 assert_eq!(cnum, LOCAL_CRATE);
972 let collection_mode = match tcx.sess.opts.debugging_opts.print_mono_items {
974 let mode_string = s.to_lowercase();
975 let mode_string = mode_string.trim();
976 if mode_string == "eager" {
977 MonoItemCollectionMode::Eager
979 if mode_string != "lazy" {
980 let message = format!("Unknown codegen-item collection mode '{}'. \
981 Falling back to 'lazy' mode.",
983 tcx.sess.warn(&message);
986 MonoItemCollectionMode::Lazy
990 if tcx.sess.opts.cg.link_dead_code {
991 MonoItemCollectionMode::Eager
993 MonoItemCollectionMode::Lazy
998 let (items, inlining_map) =
999 time(tcx.sess, "monomorphization collection", || {
1000 collector::collect_crate_mono_items(tcx, collection_mode)
1003 tcx.sess.abort_if_errors();
1005 ::rustc_mir::monomorphize::assert_symbols_are_distinct(tcx, items.iter());
1007 let strategy = if tcx.sess.opts.incremental.is_some() {
1008 PartitioningStrategy::PerModule
1010 PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
1013 let codegen_units = time(tcx.sess, "codegen unit partitioning", || {
1014 partitioning::partition(tcx,
1015 items.iter().cloned(),
1020 .collect::<Vec<_>>()
1023 let mono_items: DefIdSet = items.iter().filter_map(|mono_item| {
1025 MonoItem::Fn(ref instance) => Some(instance.def_id()),
1026 MonoItem::Static(def_id) => Some(def_id),
1031 if tcx.sess.opts.debugging_opts.print_mono_items.is_some() {
1032 let mut item_to_cgus: FxHashMap<_, Vec<_>> = Default::default();
1034 for cgu in &codegen_units {
1035 for (&mono_item, &linkage) in cgu.items() {
1036 item_to_cgus.entry(mono_item)
1038 .push((cgu.name().clone(), linkage));
1042 let mut item_keys: Vec<_> = items
1045 let mut output = i.to_string(tcx);
1046 output.push_str(" @@");
1047 let mut empty = Vec::new();
1048 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1049 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1051 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1052 output.push_str(" ");
1053 output.push_str(&cgu_name.as_str());
1055 let linkage_abbrev = match linkage {
1056 Linkage::External => "External",
1057 Linkage::AvailableExternally => "Available",
1058 Linkage::LinkOnceAny => "OnceAny",
1059 Linkage::LinkOnceODR => "OnceODR",
1060 Linkage::WeakAny => "WeakAny",
1061 Linkage::WeakODR => "WeakODR",
1062 Linkage::Appending => "Appending",
1063 Linkage::Internal => "Internal",
1064 Linkage::Private => "Private",
1065 Linkage::ExternalWeak => "ExternalWeak",
1066 Linkage::Common => "Common",
1069 output.push_str("[");
1070 output.push_str(linkage_abbrev);
1071 output.push_str("]");
1079 for item in item_keys {
1080 println!("MONO_ITEM {}", item);
1084 (Arc::new(mono_items), Arc::new(codegen_units))
1088 pub fn new(tcx: TyCtxt) -> CrateInfo {
1089 let mut info = CrateInfo {
1090 panic_runtime: None,
1091 compiler_builtins: None,
1092 profiler_runtime: None,
1093 sanitizer_runtime: None,
1094 is_no_builtins: Default::default(),
1095 native_libraries: Default::default(),
1096 used_libraries: tcx.native_libraries(LOCAL_CRATE),
1097 link_args: tcx.link_args(LOCAL_CRATE),
1098 crate_name: Default::default(),
1099 used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1100 used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1101 used_crate_source: Default::default(),
1102 wasm_imports: Default::default(),
1103 lang_item_to_crate: Default::default(),
1104 missing_lang_items: Default::default(),
1106 let lang_items = tcx.lang_items();
1108 let load_wasm_items = tcx.sess.crate_types.borrow()
1110 .any(|c| *c != config::CrateType::Rlib) &&
1111 tcx.sess.opts.target_triple.triple() == "wasm32-unknown-unknown";
1113 if load_wasm_items {
1114 info.load_wasm_imports(tcx, LOCAL_CRATE);
1117 let crates = tcx.crates();
1119 let n_crates = crates.len();
1120 info.native_libraries.reserve(n_crates);
1121 info.crate_name.reserve(n_crates);
1122 info.used_crate_source.reserve(n_crates);
1123 info.missing_lang_items.reserve(n_crates);
1125 for &cnum in crates.iter() {
1126 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1127 info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1128 info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1129 if tcx.is_panic_runtime(cnum) {
1130 info.panic_runtime = Some(cnum);
1132 if tcx.is_compiler_builtins(cnum) {
1133 info.compiler_builtins = Some(cnum);
1135 if tcx.is_profiler_runtime(cnum) {
1136 info.profiler_runtime = Some(cnum);
1138 if tcx.is_sanitizer_runtime(cnum) {
1139 info.sanitizer_runtime = Some(cnum);
1141 if tcx.is_no_builtins(cnum) {
1142 info.is_no_builtins.insert(cnum);
1144 if load_wasm_items {
1145 info.load_wasm_imports(tcx, cnum);
1147 let missing = tcx.missing_lang_items(cnum);
1148 for &item in missing.iter() {
1149 if let Ok(id) = lang_items.require(item) {
1150 info.lang_item_to_crate.insert(item, id.krate);
1154 // No need to look for lang items that are whitelisted and don't
1155 // actually need to exist.
1156 let missing = missing.iter()
1158 .filter(|&l| !weak_lang_items::whitelisted(tcx, l))
1160 info.missing_lang_items.insert(cnum, missing);
1166 fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
1167 self.wasm_imports.extend(tcx.wasm_import_module_map(cnum).iter().map(|(&id, module)| {
1168 let instance = Instance::mono(tcx, id);
1169 let import_name = tcx.symbol_name(instance);
1171 (import_name.to_string(), module.clone())
1176 fn is_codegened_item(tcx: TyCtxt, id: DefId) -> bool {
1177 let (all_mono_items, _) =
1178 tcx.collect_and_partition_mono_items(LOCAL_CRATE);
1179 all_mono_items.contains(&id)
1182 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1183 cgu_name: InternedString)
1185 let start_time = Instant::now();
1187 let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
1188 let ((stats, module), _) = tcx.dep_graph.with_task(dep_node,
1192 let time_to_codegen = start_time.elapsed();
1194 // We assume that the cost to run LLVM on a CGU is proportional to
1195 // the time we needed for codegenning it.
1196 let cost = time_to_codegen.as_secs() * 1_000_000_000 +
1197 time_to_codegen.subsec_nanos() as u64;
1199 write::submit_codegened_module_to_llvm(tcx,
1204 fn module_codegen<'a, 'tcx>(
1205 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1206 cgu_name: InternedString)
1207 -> (Stats, ModuleCodegen)
1209 let cgu = tcx.codegen_unit(cgu_name);
1211 // Instantiate monomorphizations without filling out definitions yet...
1212 let llvm_module = ModuleLlvm::new(tcx.sess, &cgu_name.as_str());
1214 let cx = CodegenCx::new(tcx, cgu, &llvm_module);
1215 let mono_items = cx.codegen_unit
1216 .items_in_deterministic_order(cx.tcx);
1217 for &(mono_item, (linkage, visibility)) in &mono_items {
1218 mono_item.predefine(&cx, linkage, visibility);
1221 // ... and now that we have everything pre-defined, fill out those definitions.
1222 for &(mono_item, _) in &mono_items {
1223 mono_item.define(&cx);
1226 // If this codegen unit contains the main function, also create the
1228 maybe_create_entry_wrapper(&cx);
1230 // Run replace-all-uses-with for statics that need it
1231 for &(old_g, new_g) in cx.statics_to_rauw.borrow().iter() {
1233 let bitcast = llvm::LLVMConstPointerCast(new_g, val_ty(old_g));
1234 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1235 llvm::LLVMDeleteGlobal(old_g);
1239 // Create the llvm.used variable
1240 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1241 if !cx.used_statics.borrow().is_empty() {
1242 let name = const_cstr!("llvm.used");
1243 let section = const_cstr!("llvm.metadata");
1244 let array = C_array(Type::i8(&cx).ptr_to(), &*cx.used_statics.borrow());
1247 let g = llvm::LLVMAddGlobal(cx.llmod,
1250 llvm::LLVMSetInitializer(g, array);
1251 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1252 llvm::LLVMSetSection(g, section.as_ptr());
1256 // Finalize debuginfo
1257 if cx.sess().opts.debuginfo != DebugInfo::None {
1258 debuginfo::finalize(&cx);
1261 cx.stats.into_inner()
1264 (stats, ModuleCodegen {
1265 name: cgu_name.to_string(),
1266 module_llvm: llvm_module,
1267 kind: ModuleKind::Regular,
1272 pub fn provide(providers: &mut Providers) {
1273 providers.collect_and_partition_mono_items =
1274 collect_and_partition_mono_items;
1276 providers.is_codegened_item = is_codegened_item;
1278 providers.codegen_unit = |tcx, name| {
1279 let (_, all) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
1281 .find(|cgu| *cgu.name() == name)
1283 .unwrap_or_else(|| panic!("failed to find cgu with name {:?}", name))
1286 provide_extern(providers);
1289 pub fn provide_extern(providers: &mut Providers) {
1290 providers.dllimport_foreign_items = |tcx, krate| {
1291 let module_map = tcx.foreign_modules(krate);
1292 let module_map = module_map.iter()
1293 .map(|lib| (lib.def_id, lib))
1294 .collect::<FxHashMap<_, _>>();
1296 let dllimports = tcx.native_libraries(krate)
1299 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
1302 let cfg = match lib.cfg {
1303 Some(ref cfg) => cfg,
1304 None => return true,
1306 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
1308 .filter_map(|lib| lib.foreign_module)
1309 .map(|id| &module_map[&id])
1310 .flat_map(|module| module.foreign_items.iter().cloned())
1312 Lrc::new(dllimports)
1315 providers.is_dllimport_foreign_item = |tcx, def_id| {
1316 tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
1320 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1322 Linkage::External => llvm::Linkage::ExternalLinkage,
1323 Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1324 Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1325 Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1326 Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1327 Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1328 Linkage::Appending => llvm::Linkage::AppendingLinkage,
1329 Linkage::Internal => llvm::Linkage::InternalLinkage,
1330 Linkage::Private => llvm::Linkage::PrivateLinkage,
1331 Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1332 Linkage::Common => llvm::Linkage::CommonLinkage,
1336 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1338 Visibility::Default => llvm::Visibility::Default,
1339 Visibility::Hidden => llvm::Visibility::Hidden,
1340 Visibility::Protected => llvm::Visibility::Protected,
1344 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1345 // the HashStable trait. Normally DepGraph::with_task() calls are
1346 // hidden behind queries, but CGU creation is a special case in two
1347 // ways: (1) it's not a query and (2) CGU are output nodes, so their
1348 // Fingerprints are not actually needed. It remains to be clarified
1349 // how exactly this case will be handled in the red/green system but
1350 // for now we content ourselves with providing a no-op HashStable
1351 // implementation for CGUs.
1352 mod temp_stable_hash_impls {
1353 use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1357 impl<HCX> HashStable<HCX> for ModuleCodegen {
1358 fn hash_stable<W: StableHasherResult>(&self,
1360 _: &mut StableHasher<W>) {