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, 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, VariantIdx};
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 rustc_mir::monomorphize::item::DefPathBasedNames;
57 use common::{self, IntPredicate, RealPredicate, TypeKind};
58 use context::CodegenCx;
63 use monomorphize::Instance;
64 use monomorphize::partitioning::{CodegenUnit, CodegenUnitExt};
65 use rustc_codegen_utils::symbol_names_test;
67 use mono_item::{MonoItem, MonoItemExt};
68 use type_of::LayoutLlvmExt;
69 use rustc::util::nodemap::FxHashMap;
71 use rustc_data_structures::small_c_str::SmallCStr;
72 use rustc_data_structures::sync::Lrc;
73 use rustc_data_structures::indexed_vec::Idx;
79 use std::ffi::CString;
80 use std::ops::{Deref, DerefMut};
82 use std::time::{Instant, Duration};
84 use syntax_pos::symbol::InternedString;
86 use rustc::hir::{self, CodegenFnAttrs};
90 use mir::operand::OperandValue;
92 use rustc_codegen_utils::check_for_rustc_errors_attr;
94 pub struct StatRecorder<'a, 'll: 'a, 'tcx: 'll> {
95 cx: &'a CodegenCx<'ll, 'tcx>,
100 impl StatRecorder<'a, 'll, 'tcx> {
101 pub fn new(cx: &'a CodegenCx<'ll, 'tcx>, name: String) -> Self {
102 let istart = cx.stats.borrow().n_llvm_insns;
111 impl Drop for StatRecorder<'a, 'll, 'tcx> {
113 if self.cx.sess().codegen_stats() {
114 let mut stats = self.cx.stats.borrow_mut();
115 let iend = stats.n_llvm_insns;
116 stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
118 // Reset LLVM insn count to avoid compound costs.
119 stats.n_llvm_insns = self.istart;
124 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind,
128 hir::BinOpKind::Eq => IntPredicate::IntEQ,
129 hir::BinOpKind::Ne => IntPredicate::IntNE,
130 hir::BinOpKind::Lt => if signed { IntPredicate::IntSLT } else { IntPredicate::IntULT },
131 hir::BinOpKind::Le => if signed { IntPredicate::IntSLE } else { IntPredicate::IntULE },
132 hir::BinOpKind::Gt => if signed { IntPredicate::IntSGT } else { IntPredicate::IntUGT },
133 hir::BinOpKind::Ge => if signed { IntPredicate::IntSGE } else { IntPredicate::IntUGE },
135 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
142 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> RealPredicate {
144 hir::BinOpKind::Eq => RealPredicate::RealOEQ,
145 hir::BinOpKind::Ne => RealPredicate::RealUNE,
146 hir::BinOpKind::Lt => RealPredicate::RealOLT,
147 hir::BinOpKind::Le => RealPredicate::RealOLE,
148 hir::BinOpKind::Gt => RealPredicate::RealOGT,
149 hir::BinOpKind::Ge => RealPredicate::RealOGE,
151 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
158 pub fn compare_simd_types<'a, 'tcx: 'a, Builder: BuilderMethods<'a, 'tcx>>(
163 ret_ty: Builder::Type,
165 ) -> Builder::Value {
166 let signed = match t.sty {
168 let cmp = bin_op_to_fcmp_predicate(op);
169 return bx.sext(bx.fcmp(cmp, lhs, rhs), ret_ty);
171 ty::Uint(_) => false,
173 _ => bug!("compare_simd_types: invalid SIMD type"),
176 let cmp = bin_op_to_icmp_predicate(op, signed);
177 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
178 // to get the correctly sized type. This will compile to a single instruction
179 // once the IR is converted to assembly if the SIMD instruction is supported
180 // by the target architecture.
181 bx.sext(bx.icmp(cmp, lhs, rhs), ret_ty)
184 /// Retrieve the information we are losing (making dynamic) in an unsizing
187 /// The `old_info` argument is a bit funny. It is intended for use
188 /// in an upcast, where the new vtable for an object will be derived
189 /// from the old one.
190 pub fn unsized_info<'tcx, Cx: CodegenMethods<'tcx>>(
194 old_info: Option<Cx::Value>,
196 let (source, target) = cx.tcx().struct_lockstep_tails(source, target);
197 match (&source.sty, &target.sty) {
198 (&ty::Array(_, len), &ty::Slice(_)) => {
199 cx.const_usize(len.unwrap_usize(cx.tcx()))
201 (&ty::Dynamic(..), &ty::Dynamic(..)) => {
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::Dynamic(ref data, ..)) => {
208 let vtable_ptr = cx.layout_of(cx.tcx().mk_mut_ptr(target))
209 .field(cx, abi::FAT_PTR_EXTRA);
210 cx.static_ptrcast(meth::get_vtable(cx, source, data.principal()),
211 cx.backend_type(vtable_ptr))
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(
221 bx: &Builder<'a, 'll, 'tcx>,
225 ) -> (&'ll Value, &'ll Value) {
226 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
227 match (&src_ty.sty, &dst_ty.sty) {
231 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) |
232 (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }),
233 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
234 assert!(bx.cx().type_is_sized(a));
235 let ptr_ty = bx.cx().type_ptr_to(bx.cx().layout_of(b).llvm_type(bx.cx()));
236 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
238 (&ty::Adt(def_a, _), &ty::Adt(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().type_ptr_to(bx.cx().layout_of(b).llvm_type(bx.cx()));
242 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
244 (&ty::Adt(def_a, _), &ty::Adt(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, true)),
267 bx.bitcast(llextra, dst_layout.scalar_pair_element_llvm_type(bx.cx(), 1, true)))
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(
276 bx: &Builder<'a, 'll, 'tcx>,
277 src: PlaceRef<'tcx, &'ll Value>,
278 dst: PlaceRef<'tcx, &'ll Value>
280 let src_ty = src.layout.ty;
281 let dst_ty = dst.layout.ty;
282 let coerce_ptr = || {
283 let (base, info) = match src.load(bx).val {
284 OperandValue::Pair(base, info) => {
285 // fat-ptr to fat-ptr unsize preserves the vtable
286 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
287 // So we need to pointercast the base to ensure
288 // the types match up.
289 let thin_ptr = dst.layout.field(bx.cx(), abi::FAT_PTR_ADDR);
290 (bx.pointercast(base, thin_ptr.llvm_type(bx.cx())), info)
292 OperandValue::Immediate(base) => {
293 unsize_thin_ptr(bx, base, src_ty, dst_ty)
295 OperandValue::Ref(..) => bug!()
297 OperandValue::Pair(base, info).store(bx, dst);
299 match (&src_ty.sty, &dst_ty.sty) {
300 (&ty::Ref(..), &ty::Ref(..)) |
301 (&ty::Ref(..), &ty::RawPtr(..)) |
302 (&ty::RawPtr(..), &ty::RawPtr(..)) => {
305 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
309 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
310 assert_eq!(def_a, def_b);
312 for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
313 let src_f = src.project_field(bx, i);
314 let dst_f = dst.project_field(bx, i);
316 if dst_f.layout.is_zst() {
320 if src_f.layout.ty == dst_f.layout.ty {
321 memcpy_ty(bx, dst_f.llval, dst_f.align, src_f.llval, src_f.align,
322 src_f.layout, MemFlags::empty());
324 coerce_unsized_into(bx, src_f, dst_f);
328 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
334 pub fn cast_shift_expr_rhs<'a, 'tcx: 'a, Builder: BuilderMethods<'a, 'tcx>>(
339 ) -> Builder::Value {
340 cast_shift_rhs(bx, op, lhs, rhs, |a, b| bx.trunc(a, b), |a, b| bx.zext(a, b))
343 fn cast_shift_rhs<'a, 'tcx: 'a, F, G, Builder: BuilderMethods<'a, 'tcx>>(
360 // Shifts may have any size int on the rhs
362 let mut rhs_llty = bx.cx().val_ty(rhs);
363 let mut lhs_llty = bx.cx().val_ty(lhs);
364 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
365 rhs_llty = bx.cx().element_type(rhs_llty)
367 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
368 lhs_llty = bx.cx().element_type(lhs_llty)
370 let rhs_sz = bx.cx().int_width(rhs_llty);
371 let lhs_sz = bx.cx().int_width(lhs_llty);
374 } else if lhs_sz > rhs_sz {
375 // FIXME (#1877: If in the future shifting by negative
376 // values is no longer undefined then this is wrong.
386 /// Returns whether this session's target will use SEH-based unwinding.
388 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
389 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
390 /// 64-bit MinGW) instead of "full SEH".
391 pub fn wants_msvc_seh(sess: &Session) -> bool {
392 sess.target.target.options.is_like_msvc
395 pub fn call_assume(bx: &Builder<'_, 'll, '_>, val: &'ll Value) {
396 let assume_intrinsic = bx.cx().get_intrinsic("llvm.assume");
397 bx.call(assume_intrinsic, &[val], None);
400 pub fn from_immediate<'a, 'tcx: 'a, Builder: BuilderMethods<'a, 'tcx>>(
403 ) -> Builder::Value {
404 if bx.cx().val_ty(val) == bx.cx().type_i1() {
405 bx.zext(val, bx.cx().type_i8())
411 pub fn to_immediate<'a, 'tcx: 'a, Builder: BuilderMethods<'a, 'tcx>>(
414 layout: layout::TyLayout,
415 ) -> Builder::Value {
416 if let layout::Abi::Scalar(ref scalar) = layout.abi {
417 return to_immediate_scalar(bx, val, scalar);
422 pub fn to_immediate_scalar<'a, 'tcx: 'a, Builder: BuilderMethods<'a, 'tcx>>(
425 scalar: &layout::Scalar,
426 ) -> Builder::Value {
427 if scalar.is_bool() {
428 return bx.trunc(val, bx.cx().type_i1());
433 pub fn memcpy_ty<'a, 'tcx: 'a, Builder: BuilderMethods<'a, 'tcx>>(
439 layout: TyLayout<'tcx>,
442 let size = layout.size.bytes();
447 bx.memcpy(dst, dst_align, src, src_align, bx.cx().const_usize(size), flags);
450 pub fn codegen_instance<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, instance: Instance<'tcx>) {
451 let _s = if cx.sess().codegen_stats() {
452 let mut instance_name = String::new();
453 DefPathBasedNames::new(cx.tcx, true, true)
454 .push_def_path(instance.def_id(), &mut instance_name);
455 Some(StatRecorder::new(cx, instance_name))
460 // this is an info! to allow collecting monomorphization statistics
461 // and to allow finding the last function before LLVM aborts from
463 info!("codegen_instance({})", instance);
465 let sig = instance.fn_sig(cx.tcx);
466 let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
468 let lldecl = cx.instances.borrow().get(&instance).cloned().unwrap_or_else(||
469 bug!("Instance `{:?}` not already declared", instance));
471 cx.stats.borrow_mut().n_closures += 1;
473 let mir = cx.tcx.instance_mir(instance.def);
474 mir::codegen_mir(cx, lldecl, &mir, instance, sig);
477 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
478 let sect = match attrs.link_section {
483 let buf = SmallCStr::new(§.as_str());
484 llvm::LLVMSetSection(llval, buf.as_ptr());
488 /// Create the `main` function which will initialize the rust runtime and call
489 /// users main function.
490 fn maybe_create_entry_wrapper(cx: &CodegenCx) {
491 let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
492 Some((id, span, _)) => {
493 (cx.tcx.hir.local_def_id(id), span)
498 let instance = Instance::mono(cx.tcx, main_def_id);
500 if !cx.codegen_unit.contains_item(&MonoItem::Fn(instance)) {
501 // We want to create the wrapper in the same codegen unit as Rust's main
506 let main_llfn = callee::get_fn(cx, instance);
508 let et = cx.sess().entry_fn.get().map(|e| e.2);
510 Some(EntryFnType::Main) => create_entry_fn(cx, span, main_llfn, main_def_id, true),
511 Some(EntryFnType::Start) => create_entry_fn(cx, span, main_llfn, main_def_id, false),
512 None => {} // Do nothing.
516 cx: &CodegenCx<'ll, '_>,
518 rust_main: &'ll Value,
519 rust_main_def_id: DefId,
520 use_start_lang_item: bool,
523 cx.type_func(&[cx.type_int(), cx.type_ptr_to(cx.type_i8p())], cx.type_int());
525 let main_ret_ty = cx.tcx.fn_sig(rust_main_def_id).output();
526 // Given that `main()` has no arguments,
527 // then its return type cannot have
528 // late-bound regions, since late-bound
529 // regions must appear in the argument
531 let main_ret_ty = cx.tcx.erase_regions(
532 &main_ret_ty.no_bound_vars().unwrap(),
535 if declare::get_defined_value(cx, "main").is_some() {
536 // FIXME: We should be smart and show a better diagnostic here.
537 cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
538 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
540 cx.sess().abort_if_errors();
543 let llfn = declare::declare_cfn(cx, "main", llfty);
545 // `main` should respect same config for frame pointer elimination as rest of code
546 attributes::set_frame_pointer_elimination(cx, llfn);
547 attributes::apply_target_cpu_attr(cx, llfn);
549 let bx = Builder::new_block(cx, llfn, "top");
551 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(&bx);
553 // Params from native main() used as args for rust start function
554 let param_argc = get_param(llfn, 0);
555 let param_argv = get_param(llfn, 1);
556 let arg_argc = bx.intcast(param_argc, cx.isize_ty, true);
557 let arg_argv = param_argv;
559 let (start_fn, args) = if use_start_lang_item {
560 let start_def_id = cx.tcx.require_lang_item(StartFnLangItem);
561 let start_fn = callee::resolve_and_get_fn(
564 cx.tcx.intern_substs(&[main_ret_ty.into()]),
566 (start_fn, vec![bx.pointercast(rust_main, cx.type_ptr_to(cx.type_i8p())),
569 debug!("using user-defined start fn");
570 (rust_main, vec![arg_argc, arg_argv])
573 let result = bx.call(start_fn, &args, None);
574 bx.ret(bx.intcast(result, cx.type_int(), true));
578 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
579 llvm_module: &ModuleLlvm)
582 use flate2::Compression;
583 use flate2::write::DeflateEncoder;
585 let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
587 #[derive(PartialEq, Eq, PartialOrd, Ord)]
594 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
596 config::CrateType::Executable |
597 config::CrateType::Staticlib |
598 config::CrateType::Cdylib => MetadataKind::None,
600 config::CrateType::Rlib => MetadataKind::Uncompressed,
602 config::CrateType::Dylib |
603 config::CrateType::ProcMacro => MetadataKind::Compressed,
605 }).max().unwrap_or(MetadataKind::None);
607 if kind == MetadataKind::None {
608 return EncodedMetadata::new();
611 let metadata = tcx.encode_metadata();
612 if kind == MetadataKind::Uncompressed {
616 assert!(kind == MetadataKind::Compressed);
617 let mut compressed = tcx.metadata_encoding_version();
618 DeflateEncoder::new(&mut compressed, Compression::fast())
619 .write_all(&metadata.raw_data).unwrap();
621 let llmeta = common::bytes_in_context(metadata_llcx, &compressed);
622 let llconst = common::struct_in_context(metadata_llcx, &[llmeta], false);
623 let name = exported_symbols::metadata_symbol_name(tcx);
624 let buf = CString::new(name).unwrap();
625 let llglobal = unsafe {
626 llvm::LLVMAddGlobal(metadata_llmod, common::val_ty(llconst), buf.as_ptr())
629 llvm::LLVMSetInitializer(llglobal, llconst);
630 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
631 let name = SmallCStr::new(section_name);
632 llvm::LLVMSetSection(llglobal, name.as_ptr());
634 // Also generate a .section directive to force no
635 // flags, at least for ELF outputs, so that the
636 // metadata doesn't get loaded into memory.
637 let directive = format!(".section {}", section_name);
638 let directive = CString::new(directive).unwrap();
639 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
644 pub struct ValueIter<'ll> {
645 cur: Option<&'ll Value>,
646 step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
649 impl Iterator for ValueIter<'ll> {
650 type Item = &'ll Value;
652 fn next(&mut self) -> Option<&'ll Value> {
654 if let Some(old) = old {
655 self.cur = unsafe { (self.step)(old) };
661 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
664 cur: llvm::LLVMGetFirstGlobal(llmod),
665 step: llvm::LLVMGetNextGlobal,
670 fn determine_cgu_reuse<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
671 cgu: &CodegenUnit<'tcx>)
673 if !tcx.dep_graph.is_fully_enabled() {
677 let work_product_id = &cgu.work_product_id();
678 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
679 // We don't have anything cached for this CGU. This can happen
680 // if the CGU did not exist in the previous session.
684 // Try to mark the CGU as green. If it we can do so, it means that nothing
685 // affecting the LLVM module has changed and we can re-use a cached version.
686 // If we compile with any kind of LTO, this means we can re-use the bitcode
687 // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
688 // know that later). If we are not doing LTO, there is only one optimized
689 // version of each module, so we re-use that.
690 let dep_node = cgu.codegen_dep_node(tcx);
691 assert!(!tcx.dep_graph.dep_node_exists(&dep_node),
692 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
695 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
696 // We can re-use either the pre- or the post-thinlto state
697 if tcx.sess.lto() != Lto::No {
707 pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
708 rx: mpsc::Receiver<Box<dyn Any + Send>>)
711 check_for_rustc_errors_attr(tcx);
713 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
715 // Codegen the metadata.
716 tcx.sess.profiler(|p| p.start_activity(ProfileCategory::Codegen));
718 let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
720 Some("metadata")).as_str()
722 let metadata_llvm_module = ModuleLlvm::new(tcx.sess, &metadata_cgu_name);
723 let metadata = time(tcx.sess, "write metadata", || {
724 write_metadata(tcx, &metadata_llvm_module)
726 tcx.sess.profiler(|p| p.end_activity(ProfileCategory::Codegen));
728 let metadata_module = ModuleCodegen {
729 name: metadata_cgu_name,
730 module_llvm: metadata_llvm_module,
731 kind: ModuleKind::Metadata,
734 let time_graph = if tcx.sess.opts.debugging_opts.codegen_time_graph {
735 Some(time_graph::TimeGraph::new())
740 // Skip crate items and just output metadata in -Z no-codegen mode.
741 if tcx.sess.opts.debugging_opts.no_codegen ||
742 !tcx.sess.opts.output_types.should_codegen() {
743 let ongoing_codegen = write::start_async_codegen(
750 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
751 ongoing_codegen.codegen_finished(tcx);
753 assert_and_save_dep_graph(tcx);
755 ongoing_codegen.check_for_errors(tcx.sess);
757 return ongoing_codegen;
760 // Run the monomorphization collector and partition the collected items into
762 let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
763 let codegen_units = (*codegen_units).clone();
765 // Force all codegen_unit queries so they are already either red or green
766 // when compile_codegen_unit accesses them. We are not able to re-execute
767 // the codegen_unit query from just the DepNode, so an unknown color would
768 // lead to having to re-execute compile_codegen_unit, possibly
770 if tcx.dep_graph.is_fully_enabled() {
771 for cgu in &codegen_units {
772 tcx.codegen_unit(cgu.name().clone());
776 let ongoing_codegen = write::start_async_codegen(
781 codegen_units.len());
782 let ongoing_codegen = AbortCodegenOnDrop(Some(ongoing_codegen));
784 // Codegen an allocator shim, if necessary.
786 // If the crate doesn't have an `allocator_kind` set then there's definitely
787 // no shim to generate. Otherwise we also check our dependency graph for all
788 // our output crate types. If anything there looks like its a `Dynamic`
789 // linkage, then it's already got an allocator shim and we'll be using that
790 // one instead. If nothing exists then it's our job to generate the
792 let any_dynamic_crate = tcx.sess.dependency_formats.borrow()
795 use rustc::middle::dependency_format::Linkage;
796 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
798 let allocator_module = if any_dynamic_crate {
800 } else if let Some(kind) = *tcx.sess.allocator_kind.get() {
801 let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
803 Some("allocator")).as_str()
805 let modules = ModuleLlvm::new(tcx.sess, &llmod_id);
806 time(tcx.sess, "write allocator module", || {
808 allocator::codegen(tcx, &modules, kind)
814 module_llvm: modules,
815 kind: ModuleKind::Allocator,
821 if let Some(allocator_module) = allocator_module {
822 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
825 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
827 // We sort the codegen units by size. This way we can schedule work for LLVM
828 // a bit more efficiently.
829 let codegen_units = {
830 let mut codegen_units = codegen_units;
831 codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
835 let mut total_codegen_time = Duration::new(0, 0);
836 let mut all_stats = Stats::default();
838 for cgu in codegen_units.into_iter() {
839 ongoing_codegen.wait_for_signal_to_codegen_item();
840 ongoing_codegen.check_for_errors(tcx.sess);
842 let cgu_reuse = determine_cgu_reuse(tcx, &cgu);
843 tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
847 let _timing_guard = time_graph.as_ref().map(|time_graph| {
848 time_graph.start(write::CODEGEN_WORKER_TIMELINE,
849 write::CODEGEN_WORK_PACKAGE_KIND,
850 &format!("codegen {}", cgu.name()))
852 let start_time = Instant::now();
853 let stats = compile_codegen_unit(tcx, *cgu.name());
854 all_stats.extend(stats);
855 total_codegen_time += start_time.elapsed();
858 CguReuse::PreLto => {
859 write::submit_pre_lto_module_to_llvm(tcx, CachedModuleCodegen {
860 name: cgu.name().to_string(),
861 source: cgu.work_product(tcx),
865 CguReuse::PostLto => {
866 write::submit_post_lto_module_to_llvm(tcx, CachedModuleCodegen {
867 name: cgu.name().to_string(),
868 source: cgu.work_product(tcx),
875 ongoing_codegen.codegen_finished(tcx);
877 // Since the main thread is sometimes blocked during codegen, we keep track
878 // -Ztime-passes output manually.
879 print_time_passes_entry(tcx.sess.time_passes(),
880 "codegen to LLVM IR",
883 rustc_incremental::assert_module_sources::assert_module_sources(tcx);
885 symbol_names_test::report_symbol_names(tcx);
887 if tcx.sess.codegen_stats() {
888 println!("--- codegen stats ---");
889 println!("n_glues_created: {}", all_stats.n_glues_created);
890 println!("n_null_glues: {}", all_stats.n_null_glues);
891 println!("n_real_glues: {}", all_stats.n_real_glues);
893 println!("n_fns: {}", all_stats.n_fns);
894 println!("n_inlines: {}", all_stats.n_inlines);
895 println!("n_closures: {}", all_stats.n_closures);
896 println!("fn stats:");
897 all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
898 for &(ref name, insns) in all_stats.fn_stats.iter() {
899 println!("{} insns, {}", insns, *name);
903 if tcx.sess.count_llvm_insns() {
904 for (k, v) in all_stats.llvm_insns.iter() {
905 println!("{:7} {}", *v, *k);
909 ongoing_codegen.check_for_errors(tcx.sess);
911 assert_and_save_dep_graph(tcx);
912 ongoing_codegen.into_inner()
915 /// A curious wrapper structure whose only purpose is to call `codegen_aborted`
916 /// when it's dropped abnormally.
918 /// In the process of working on rust-lang/rust#55238 a mysterious segfault was
919 /// stumbled upon. The segfault was never reproduced locally, but it was
920 /// suspected to be related to the fact that codegen worker threads were
921 /// sticking around by the time the main thread was exiting, causing issues.
923 /// This structure is an attempt to fix that issue where the `codegen_aborted`
924 /// message will block until all workers have finished. This should ensure that
925 /// even if the main codegen thread panics we'll wait for pending work to
926 /// complete before returning from the main thread, hopefully avoiding
929 /// If you see this comment in the code, then it means that this workaround
930 /// worked! We may yet one day track down the mysterious cause of that
932 struct AbortCodegenOnDrop(Option<OngoingCodegen>);
934 impl AbortCodegenOnDrop {
935 fn into_inner(mut self) -> OngoingCodegen {
936 self.0.take().unwrap()
940 impl Deref for AbortCodegenOnDrop {
941 type Target = OngoingCodegen;
943 fn deref(&self) -> &OngoingCodegen {
944 self.0.as_ref().unwrap()
948 impl DerefMut for AbortCodegenOnDrop {
949 fn deref_mut(&mut self) -> &mut OngoingCodegen {
950 self.0.as_mut().unwrap()
954 impl Drop for AbortCodegenOnDrop {
956 if let Some(codegen) = self.0.take() {
957 codegen.codegen_aborted();
962 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
965 || rustc_incremental::assert_dep_graph(tcx));
968 "serialize dep graph",
969 || rustc_incremental::save_dep_graph(tcx));
973 pub fn new(tcx: TyCtxt) -> CrateInfo {
974 let mut info = CrateInfo {
976 compiler_builtins: None,
977 profiler_runtime: None,
978 sanitizer_runtime: None,
979 is_no_builtins: Default::default(),
980 native_libraries: Default::default(),
981 used_libraries: tcx.native_libraries(LOCAL_CRATE),
982 link_args: tcx.link_args(LOCAL_CRATE),
983 crate_name: Default::default(),
984 used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
985 used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
986 used_crate_source: Default::default(),
987 wasm_imports: Default::default(),
988 lang_item_to_crate: Default::default(),
989 missing_lang_items: Default::default(),
991 let lang_items = tcx.lang_items();
993 let load_wasm_items = tcx.sess.crate_types.borrow()
995 .any(|c| *c != config::CrateType::Rlib) &&
996 tcx.sess.opts.target_triple.triple() == "wasm32-unknown-unknown";
999 info.load_wasm_imports(tcx, LOCAL_CRATE);
1002 let crates = tcx.crates();
1004 let n_crates = crates.len();
1005 info.native_libraries.reserve(n_crates);
1006 info.crate_name.reserve(n_crates);
1007 info.used_crate_source.reserve(n_crates);
1008 info.missing_lang_items.reserve(n_crates);
1010 for &cnum in crates.iter() {
1011 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1012 info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1013 info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1014 if tcx.is_panic_runtime(cnum) {
1015 info.panic_runtime = Some(cnum);
1017 if tcx.is_compiler_builtins(cnum) {
1018 info.compiler_builtins = Some(cnum);
1020 if tcx.is_profiler_runtime(cnum) {
1021 info.profiler_runtime = Some(cnum);
1023 if tcx.is_sanitizer_runtime(cnum) {
1024 info.sanitizer_runtime = Some(cnum);
1026 if tcx.is_no_builtins(cnum) {
1027 info.is_no_builtins.insert(cnum);
1029 if load_wasm_items {
1030 info.load_wasm_imports(tcx, cnum);
1032 let missing = tcx.missing_lang_items(cnum);
1033 for &item in missing.iter() {
1034 if let Ok(id) = lang_items.require(item) {
1035 info.lang_item_to_crate.insert(item, id.krate);
1039 // No need to look for lang items that are whitelisted and don't
1040 // actually need to exist.
1041 let missing = missing.iter()
1043 .filter(|&l| !weak_lang_items::whitelisted(tcx, l))
1045 info.missing_lang_items.insert(cnum, missing);
1051 fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
1052 self.wasm_imports.extend(tcx.wasm_import_module_map(cnum).iter().map(|(&id, module)| {
1053 let instance = Instance::mono(tcx, id);
1054 let import_name = tcx.symbol_name(instance);
1056 (import_name.to_string(), module.clone())
1061 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1062 cgu_name: InternedString)
1064 let start_time = Instant::now();
1066 let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
1067 let ((stats, module), _) = tcx.dep_graph.with_task(dep_node,
1071 let time_to_codegen = start_time.elapsed();
1073 // We assume that the cost to run LLVM on a CGU is proportional to
1074 // the time we needed for codegenning it.
1075 let cost = time_to_codegen.as_secs() * 1_000_000_000 +
1076 time_to_codegen.subsec_nanos() as u64;
1078 write::submit_codegened_module_to_llvm(tcx,
1083 fn module_codegen<'a, 'tcx>(
1084 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1085 cgu_name: InternedString)
1086 -> (Stats, ModuleCodegen)
1088 let cgu = tcx.codegen_unit(cgu_name);
1090 // Instantiate monomorphizations without filling out definitions yet...
1091 let llvm_module = ModuleLlvm::new(tcx.sess, &cgu_name.as_str());
1093 let cx = CodegenCx::new(tcx, cgu, &llvm_module);
1094 let mono_items = cx.codegen_unit
1095 .items_in_deterministic_order(cx.tcx);
1096 for &(mono_item, (linkage, visibility)) in &mono_items {
1097 mono_item.predefine(&cx, linkage, visibility);
1100 // ... and now that we have everything pre-defined, fill out those definitions.
1101 for &(mono_item, _) in &mono_items {
1102 mono_item.define(&cx);
1105 // If this codegen unit contains the main function, also create the
1107 maybe_create_entry_wrapper(&cx);
1109 // Run replace-all-uses-with for statics that need it
1110 for &(old_g, new_g) in cx.statics_to_rauw.borrow().iter() {
1112 let bitcast = llvm::LLVMConstPointerCast(new_g, cx.val_ty(old_g));
1113 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1114 llvm::LLVMDeleteGlobal(old_g);
1118 // Create the llvm.used variable
1119 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1120 if !cx.used_statics.borrow().is_empty() {
1121 let name = const_cstr!("llvm.used");
1122 let section = const_cstr!("llvm.metadata");
1123 let array = cx.const_array(
1124 &cx.type_ptr_to(cx.type_i8()),
1125 &*cx.used_statics.borrow()
1129 let g = llvm::LLVMAddGlobal(cx.llmod,
1132 llvm::LLVMSetInitializer(g, array);
1133 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1134 llvm::LLVMSetSection(g, section.as_ptr());
1138 // Finalize debuginfo
1139 if cx.sess().opts.debuginfo != DebugInfo::None {
1140 debuginfo::finalize(&cx);
1143 cx.stats.into_inner()
1146 (stats, ModuleCodegen {
1147 name: cgu_name.to_string(),
1148 module_llvm: llvm_module,
1149 kind: ModuleKind::Regular,
1154 pub fn provide_both(providers: &mut Providers) {
1155 providers.dllimport_foreign_items = |tcx, krate| {
1156 let module_map = tcx.foreign_modules(krate);
1157 let module_map = module_map.iter()
1158 .map(|lib| (lib.def_id, lib))
1159 .collect::<FxHashMap<_, _>>();
1161 let dllimports = tcx.native_libraries(krate)
1164 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
1167 let cfg = match lib.cfg {
1168 Some(ref cfg) => cfg,
1169 None => return true,
1171 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
1173 .filter_map(|lib| lib.foreign_module)
1174 .map(|id| &module_map[&id])
1175 .flat_map(|module| module.foreign_items.iter().cloned())
1177 Lrc::new(dllimports)
1180 providers.is_dllimport_foreign_item = |tcx, def_id| {
1181 tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
1185 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1187 Linkage::External => llvm::Linkage::ExternalLinkage,
1188 Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1189 Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1190 Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1191 Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1192 Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1193 Linkage::Appending => llvm::Linkage::AppendingLinkage,
1194 Linkage::Internal => llvm::Linkage::InternalLinkage,
1195 Linkage::Private => llvm::Linkage::PrivateLinkage,
1196 Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1197 Linkage::Common => llvm::Linkage::CommonLinkage,
1201 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1203 Visibility::Default => llvm::Visibility::Default,
1204 Visibility::Hidden => llvm::Visibility::Hidden,
1205 Visibility::Protected => llvm::Visibility::Protected,
1209 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1210 // the HashStable trait. Normally DepGraph::with_task() calls are
1211 // hidden behind queries, but CGU creation is a special case in two
1212 // ways: (1) it's not a query and (2) CGU are output nodes, so their
1213 // Fingerprints are not actually needed. It remains to be clarified
1214 // how exactly this case will be handled in the red/green system but
1215 // for now we content ourselves with providing a no-op HashStable
1216 // implementation for CGUs.
1217 mod temp_stable_hash_impls {
1218 use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1222 impl<HCX> HashStable<HCX> for ModuleCodegen {
1223 fn hash_stable<W: StableHasherResult>(&self,
1225 _: &mut StableHasher<W>) {