1 //! Codegen the completed AST to the LLVM IR.
3 //! Some functions here, such as codegen_block and codegen_expr, return a value --
4 //! the result of the codegen to LLVM -- while others, such as codegen_fn
5 //! and mono_item, are called only for the side effect of adding a
6 //! particular definition to the LLVM IR output we're producing.
8 //! Hopefully useful general knowledge about codegen:
10 //! * There's no way to find out the `Ty` type of a Value. Doing so
11 //! would be "trying to get the eggs out of an omelette" (credit:
12 //! pcwalton). You can, instead, find out its `llvm::Type` by calling `val_ty`,
13 //! but one `llvm::Type` corresponds to many `Ty`s; for instance, `tup(int, int,
14 //! int)` and `rec(x=int, y=int, z=int)` will have the same `llvm::Type`.
16 use crate::{ModuleCodegen, ModuleKind, CachedModuleCodegen};
18 use rustc::dep_graph::cgu_reuse_tracker::CguReuse;
19 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
20 use rustc::middle::cstore::EncodedMetadata;
21 use rustc::middle::lang_items::StartFnLangItem;
22 use rustc::middle::weak_lang_items;
23 use rustc::mir::mono::{CodegenUnitNameBuilder, CodegenUnit, MonoItem};
24 use rustc::ty::{self, Ty, TyCtxt, Instance};
25 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf, VariantIdx, HasTyCtxt};
26 use rustc::ty::query::Providers;
27 use rustc::middle::cstore::{self, LinkagePreference};
28 use rustc::util::common::{time, print_time_passes_entry, set_time_depth, time_depth};
29 use rustc::session::config::{self, EntryFnType, Lto};
30 use rustc::session::Session;
31 use rustc::util::nodemap::FxHashMap;
32 use rustc_data_structures::indexed_vec::Idx;
33 use rustc_codegen_utils::{symbol_names_test, check_for_rustc_errors_attr};
34 use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
35 use crate::mir::place::PlaceRef;
36 use crate::back::write::{OngoingCodegen, start_async_codegen, submit_pre_lto_module_to_llvm,
37 submit_post_lto_module_to_llvm};
38 use crate::{MemFlags, CrateInfo};
40 use crate::common::{RealPredicate, TypeKind, IntPredicate};
48 use std::ops::{Deref, DerefMut};
49 use std::time::{Instant, Duration};
55 use crate::mir::operand::OperandValue;
57 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind,
61 hir::BinOpKind::Eq => IntPredicate::IntEQ,
62 hir::BinOpKind::Ne => IntPredicate::IntNE,
63 hir::BinOpKind::Lt => if signed { IntPredicate::IntSLT } else { IntPredicate::IntULT },
64 hir::BinOpKind::Le => if signed { IntPredicate::IntSLE } else { IntPredicate::IntULE },
65 hir::BinOpKind::Gt => if signed { IntPredicate::IntSGT } else { IntPredicate::IntUGT },
66 hir::BinOpKind::Ge => if signed { IntPredicate::IntSGE } else { IntPredicate::IntUGE },
68 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
75 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> RealPredicate {
77 hir::BinOpKind::Eq => RealPredicate::RealOEQ,
78 hir::BinOpKind::Ne => RealPredicate::RealUNE,
79 hir::BinOpKind::Lt => RealPredicate::RealOLT,
80 hir::BinOpKind::Le => RealPredicate::RealOLE,
81 hir::BinOpKind::Gt => RealPredicate::RealOGT,
82 hir::BinOpKind::Ge => RealPredicate::RealOGE,
84 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
91 pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
99 let signed = match t.sty {
101 let cmp = bin_op_to_fcmp_predicate(op);
102 let cmp = bx.fcmp(cmp, lhs, rhs);
103 return bx.sext(cmp, ret_ty);
105 ty::Uint(_) => false,
107 _ => bug!("compare_simd_types: invalid SIMD type"),
110 let cmp = bin_op_to_icmp_predicate(op, signed);
111 let cmp = bx.icmp(cmp, lhs, rhs);
112 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
113 // to get the correctly sized type. This will compile to a single instruction
114 // once the IR is converted to assembly if the SIMD instruction is supported
115 // by the target architecture.
119 /// Retrieves the information we are losing (making dynamic) in an unsizing
122 /// The `old_info` argument is a bit funny. It is intended for use
123 /// in an upcast, where the new vtable for an object will be derived
124 /// from the old one.
125 pub fn unsized_info<'tcx, Cx: CodegenMethods<'tcx>>(
129 old_info: Option<Cx::Value>,
131 let (source, target) =
132 cx.tcx().struct_lockstep_tails_erasing_lifetimes(source, target, cx.param_env());
133 match (&source.sty, &target.sty) {
134 (&ty::Array(_, len), &ty::Slice(_)) => {
135 cx.const_usize(len.unwrap_usize(cx.tcx()))
137 (&ty::Dynamic(..), &ty::Dynamic(..)) => {
138 // For now, upcasts are limited to changes in marker
139 // traits, and hence never actually require an actual
140 // change to the vtable.
141 old_info.expect("unsized_info: missing old info for trait upcast")
143 (_, &ty::Dynamic(ref data, ..)) => {
144 let vtable_ptr = cx.layout_of(cx.tcx().mk_mut_ptr(target))
145 .field(cx, FAT_PTR_EXTRA);
146 cx.const_ptrcast(meth::get_vtable(cx, source, data.principal()),
147 cx.backend_type(vtable_ptr))
149 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
155 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
156 pub fn unsize_thin_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
161 ) -> (Bx::Value, Bx::Value) {
162 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
163 match (&src_ty.sty, &dst_ty.sty) {
167 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) |
168 (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }),
169 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
170 assert!(bx.cx().type_is_sized(a));
171 let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
172 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
174 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
175 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
176 assert!(bx.cx().type_is_sized(a));
177 let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
178 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
180 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
181 assert_eq!(def_a, def_b);
183 let src_layout = bx.cx().layout_of(src_ty);
184 let dst_layout = bx.cx().layout_of(dst_ty);
185 let mut result = None;
186 for i in 0..src_layout.fields.count() {
187 let src_f = src_layout.field(bx.cx(), i);
188 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
189 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
193 assert_eq!(src_layout.size, src_f.size);
195 let dst_f = dst_layout.field(bx.cx(), i);
196 assert_ne!(src_f.ty, dst_f.ty);
197 assert_eq!(result, None);
198 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
200 let (lldata, llextra) = result.unwrap();
201 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
202 (bx.bitcast(lldata, bx.cx().scalar_pair_element_backend_type(dst_layout, 0, true)),
203 bx.bitcast(llextra, bx.cx().scalar_pair_element_backend_type(dst_layout, 1, true)))
205 _ => bug!("unsize_thin_ptr: called on bad types"),
209 /// Coerce `src`, which is a reference to a value of type `src_ty`,
210 /// to a value of type `dst_ty` and store the result in `dst`
211 pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
213 src: PlaceRef<'tcx, Bx::Value>,
214 dst: PlaceRef<'tcx, Bx::Value>,
216 let src_ty = src.layout.ty;
217 let dst_ty = dst.layout.ty;
218 let mut coerce_ptr = || {
219 let (base, info) = match bx.load_operand(src).val {
220 OperandValue::Pair(base, info) => {
221 // fat-ptr to fat-ptr unsize preserves the vtable
222 // i.e., &'a fmt::Debug+Send => &'a fmt::Debug
223 // So we need to pointercast the base to ensure
224 // the types match up.
225 let thin_ptr = dst.layout.field(bx.cx(), FAT_PTR_ADDR);
226 (bx.pointercast(base, bx.cx().backend_type(thin_ptr)), info)
228 OperandValue::Immediate(base) => {
229 unsize_thin_ptr(bx, base, src_ty, dst_ty)
231 OperandValue::Ref(..) => bug!()
233 OperandValue::Pair(base, info).store(bx, dst);
235 match (&src_ty.sty, &dst_ty.sty) {
236 (&ty::Ref(..), &ty::Ref(..)) |
237 (&ty::Ref(..), &ty::RawPtr(..)) |
238 (&ty::RawPtr(..), &ty::RawPtr(..)) => {
241 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
245 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
246 assert_eq!(def_a, def_b);
248 for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
249 let src_f = src.project_field(bx, i);
250 let dst_f = dst.project_field(bx, i);
252 if dst_f.layout.is_zst() {
256 if src_f.layout.ty == dst_f.layout.ty {
257 memcpy_ty(bx, dst_f.llval, dst_f.align, src_f.llval, src_f.align,
258 src_f.layout, MemFlags::empty());
260 coerce_unsized_into(bx, src_f, dst_f);
264 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
270 pub fn cast_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
276 cast_shift_rhs(bx, op, lhs, rhs)
279 fn cast_shift_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
285 // Shifts may have any size int on the rhs
287 let mut rhs_llty = bx.cx().val_ty(rhs);
288 let mut lhs_llty = bx.cx().val_ty(lhs);
289 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
290 rhs_llty = bx.cx().element_type(rhs_llty)
292 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
293 lhs_llty = bx.cx().element_type(lhs_llty)
295 let rhs_sz = bx.cx().int_width(rhs_llty);
296 let lhs_sz = bx.cx().int_width(lhs_llty);
298 bx.trunc(rhs, lhs_llty)
299 } else if lhs_sz > rhs_sz {
300 // FIXME (#1877: If in the future shifting by negative
301 // values is no longer undefined then this is wrong.
302 bx.zext(rhs, lhs_llty)
311 /// Returns `true` if this session's target will use SEH-based unwinding.
313 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
314 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
315 /// 64-bit MinGW) instead of "full SEH".
316 pub fn wants_msvc_seh(sess: &Session) -> bool {
317 sess.target.target.options.is_like_msvc
320 pub fn from_immediate<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
324 if bx.cx().val_ty(val) == bx.cx().type_i1() {
325 bx.zext(val, bx.cx().type_i8())
331 pub fn to_immediate<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
334 layout: layout::TyLayout<'_>,
336 if let layout::Abi::Scalar(ref scalar) = layout.abi {
337 return to_immediate_scalar(bx, val, scalar);
342 pub fn to_immediate_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
345 scalar: &layout::Scalar,
347 if scalar.is_bool() {
348 return bx.trunc(val, bx.cx().type_i1());
353 pub fn memcpy_ty<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
359 layout: TyLayout<'tcx>,
362 let size = layout.size.bytes();
367 bx.memcpy(dst, dst_align, src, src_align, bx.cx().const_usize(size), flags);
370 pub fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
371 cx: &'a Bx::CodegenCx,
372 instance: Instance<'tcx>,
374 // this is an info! to allow collecting monomorphization statistics
375 // and to allow finding the last function before LLVM aborts from
377 info!("codegen_instance({})", instance);
379 let sig = instance.fn_sig(cx.tcx());
380 let sig = cx.tcx().normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
382 let lldecl = cx.instances().borrow().get(&instance).cloned().unwrap_or_else(||
383 bug!("Instance `{:?}` not already declared", instance));
385 let mir = cx.tcx().instance_mir(instance.def);
386 mir::codegen_mir::<Bx>(cx, lldecl, &mir, instance, sig);
389 /// Creates the `main` function which will initialize the rust runtime and call
390 /// users main function.
391 pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(cx: &'a Bx::CodegenCx) {
392 let (main_def_id, span) = match cx.tcx().entry_fn(LOCAL_CRATE) {
393 Some((def_id, _)) => { (def_id, cx.tcx().def_span(def_id)) },
397 let instance = Instance::mono(cx.tcx(), main_def_id);
399 if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
400 // We want to create the wrapper in the same codegen unit as Rust's main
405 let main_llfn = cx.get_fn(instance);
407 let et = cx.tcx().entry_fn(LOCAL_CRATE).map(|e| e.1);
409 Some(EntryFnType::Main) => create_entry_fn::<Bx>(cx, span, main_llfn, main_def_id, true),
410 Some(EntryFnType::Start) => create_entry_fn::<Bx>(cx, span, main_llfn, main_def_id, false),
411 None => {} // Do nothing.
414 fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
415 cx: &'a Bx::CodegenCx,
417 rust_main: Bx::Value,
418 rust_main_def_id: DefId,
419 use_start_lang_item: bool,
422 cx.type_func(&[cx.type_int(), cx.type_ptr_to(cx.type_i8p())], cx.type_int());
424 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).output();
425 // Given that `main()` has no arguments,
426 // then its return type cannot have
427 // late-bound regions, since late-bound
428 // regions must appear in the argument
430 let main_ret_ty = cx.tcx().erase_regions(
431 &main_ret_ty.no_bound_vars().unwrap(),
434 if cx.get_defined_value("main").is_some() {
435 // FIXME: We should be smart and show a better diagnostic here.
436 cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
437 .help("did you use `#[no_mangle]` on `fn main`? Use `#[start]` instead")
439 cx.sess().abort_if_errors();
442 let llfn = cx.declare_cfn("main", llfty);
444 // `main` should respect same config for frame pointer elimination as rest of code
445 cx.set_frame_pointer_elimination(llfn);
446 cx.apply_target_cpu_attr(llfn);
448 let mut bx = Bx::new_block(&cx, llfn, "top");
450 bx.insert_reference_to_gdb_debug_scripts_section_global();
452 // Params from native main() used as args for rust start function
453 let param_argc = bx.get_param(0);
454 let param_argv = bx.get_param(1);
455 let arg_argc = bx.intcast(param_argc, cx.type_isize(), true);
456 let arg_argv = param_argv;
458 let (start_fn, args) = if use_start_lang_item {
459 let start_def_id = cx.tcx().require_lang_item(StartFnLangItem);
460 let start_fn = callee::resolve_and_get_fn(
463 cx.tcx().intern_substs(&[main_ret_ty.into()]),
465 (start_fn, vec![bx.pointercast(rust_main, cx.type_ptr_to(cx.type_i8p())),
468 debug!("using user-defined start fn");
469 (rust_main, vec![arg_argc, arg_argv])
472 let result = bx.call(start_fn, &args, None);
473 let cast = bx.intcast(result, cx.type_int(), true);
478 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
480 pub fn codegen_crate<B: ExtraBackendMethods>(
483 metadata: EncodedMetadata,
484 need_metadata_module: bool,
485 rx: mpsc::Receiver<Box<dyn Any + Send>>,
486 ) -> OngoingCodegen<B> {
487 check_for_rustc_errors_attr(tcx);
489 // Skip crate items and just output metadata in -Z no-codegen mode.
490 if tcx.sess.opts.debugging_opts.no_codegen ||
491 !tcx.sess.opts.output_types.should_codegen() {
492 let ongoing_codegen = start_async_codegen(
499 ongoing_codegen.codegen_finished(tcx);
501 assert_and_save_dep_graph(tcx);
503 ongoing_codegen.check_for_errors(tcx.sess);
505 return ongoing_codegen;
508 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
510 // Run the monomorphization collector and partition the collected items into
512 let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
513 let codegen_units = (*codegen_units).clone();
515 // Force all codegen_unit queries so they are already either red or green
516 // when compile_codegen_unit accesses them. We are not able to re-execute
517 // the codegen_unit query from just the DepNode, so an unknown color would
518 // lead to having to re-execute compile_codegen_unit, possibly
520 if tcx.dep_graph.is_fully_enabled() {
521 for cgu in &codegen_units {
522 tcx.codegen_unit(cgu.name().clone());
526 let ongoing_codegen = start_async_codegen(
531 codegen_units.len());
532 let ongoing_codegen = AbortCodegenOnDrop::<B>(Some(ongoing_codegen));
534 // Codegen an allocator shim, if necessary.
536 // If the crate doesn't have an `allocator_kind` set then there's definitely
537 // no shim to generate. Otherwise we also check our dependency graph for all
538 // our output crate types. If anything there looks like its a `Dynamic`
539 // linkage, then it's already got an allocator shim and we'll be using that
540 // one instead. If nothing exists then it's our job to generate the
542 let any_dynamic_crate = tcx.sess.dependency_formats.borrow()
545 use rustc::middle::dependency_format::Linkage;
546 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
548 let allocator_module = if any_dynamic_crate {
550 } else if let Some(kind) = *tcx.sess.allocator_kind.get() {
551 let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
553 Some("allocator")).as_str()
555 let mut modules = backend.new_metadata(tcx, &llmod_id);
556 time(tcx.sess, "write allocator module", || {
557 backend.codegen_allocator(tcx, &mut modules, kind)
562 module_llvm: modules,
563 kind: ModuleKind::Allocator,
569 if let Some(allocator_module) = allocator_module {
570 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
573 if need_metadata_module {
574 // Codegen the encoded metadata.
575 tcx.sess.profiler(|p| p.start_activity("codegen crate metadata"));
577 let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
579 Some("metadata")).as_str()
581 let mut metadata_llvm_module = backend.new_metadata(tcx, &metadata_cgu_name);
582 time(tcx.sess, "write compressed metadata", || {
583 backend.write_compressed_metadata(tcx, &ongoing_codegen.metadata,
584 &mut metadata_llvm_module);
586 tcx.sess.profiler(|p| p.end_activity("codegen crate metadata"));
588 let metadata_module = ModuleCodegen {
589 name: metadata_cgu_name,
590 module_llvm: metadata_llvm_module,
591 kind: ModuleKind::Metadata,
593 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
596 // We sort the codegen units by size. This way we can schedule work for LLVM
597 // a bit more efficiently.
598 let codegen_units = {
599 let mut codegen_units = codegen_units;
600 codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
604 let mut total_codegen_time = Duration::new(0, 0);
606 for cgu in codegen_units.into_iter() {
607 ongoing_codegen.wait_for_signal_to_codegen_item();
608 ongoing_codegen.check_for_errors(tcx.sess);
610 let cgu_reuse = determine_cgu_reuse(tcx, &cgu);
611 tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
615 tcx.sess.profiler(|p| p.start_activity(format!("codegen {}", cgu.name())));
616 let start_time = Instant::now();
617 backend.compile_codegen_unit(tcx, *cgu.name());
618 total_codegen_time += start_time.elapsed();
619 tcx.sess.profiler(|p| p.end_activity(format!("codegen {}", cgu.name())));
622 CguReuse::PreLto => {
623 submit_pre_lto_module_to_llvm(&backend, tcx, CachedModuleCodegen {
624 name: cgu.name().to_string(),
625 source: cgu.work_product(tcx),
629 CguReuse::PostLto => {
630 submit_post_lto_module_to_llvm(&backend, tcx, CachedModuleCodegen {
631 name: cgu.name().to_string(),
632 source: cgu.work_product(tcx),
639 ongoing_codegen.codegen_finished(tcx);
641 // Since the main thread is sometimes blocked during codegen, we keep track
642 // -Ztime-passes output manually.
643 let time_depth = time_depth();
644 set_time_depth(time_depth + 1);
645 print_time_passes_entry(tcx.sess.time_passes(),
646 "codegen to LLVM IR",
648 set_time_depth(time_depth);
650 ::rustc_incremental::assert_module_sources::assert_module_sources(tcx);
652 symbol_names_test::report_symbol_names(tcx);
654 ongoing_codegen.check_for_errors(tcx.sess);
656 assert_and_save_dep_graph(tcx);
657 ongoing_codegen.into_inner()
660 /// A curious wrapper structure whose only purpose is to call `codegen_aborted`
661 /// when it's dropped abnormally.
663 /// In the process of working on rust-lang/rust#55238 a mysterious segfault was
664 /// stumbled upon. The segfault was never reproduced locally, but it was
665 /// suspected to be related to the fact that codegen worker threads were
666 /// sticking around by the time the main thread was exiting, causing issues.
668 /// This structure is an attempt to fix that issue where the `codegen_aborted`
669 /// message will block until all workers have finished. This should ensure that
670 /// even if the main codegen thread panics we'll wait for pending work to
671 /// complete before returning from the main thread, hopefully avoiding
674 /// If you see this comment in the code, then it means that this workaround
675 /// worked! We may yet one day track down the mysterious cause of that
677 struct AbortCodegenOnDrop<B: ExtraBackendMethods>(Option<OngoingCodegen<B>>);
679 impl<B: ExtraBackendMethods> AbortCodegenOnDrop<B> {
680 fn into_inner(mut self) -> OngoingCodegen<B> {
681 self.0.take().unwrap()
685 impl<B: ExtraBackendMethods> Deref for AbortCodegenOnDrop<B> {
686 type Target = OngoingCodegen<B>;
688 fn deref(&self) -> &OngoingCodegen<B> {
689 self.0.as_ref().unwrap()
693 impl<B: ExtraBackendMethods> DerefMut for AbortCodegenOnDrop<B> {
694 fn deref_mut(&mut self) -> &mut OngoingCodegen<B> {
695 self.0.as_mut().unwrap()
699 impl<B: ExtraBackendMethods> Drop for AbortCodegenOnDrop<B> {
701 if let Some(codegen) = self.0.take() {
702 codegen.codegen_aborted();
707 fn assert_and_save_dep_graph(tcx: TyCtxt<'_>) {
710 || ::rustc_incremental::assert_dep_graph(tcx));
713 "serialize dep graph",
714 || ::rustc_incremental::save_dep_graph(tcx));
718 pub fn new(tcx: TyCtxt<'_>) -> CrateInfo {
719 let mut info = CrateInfo {
721 compiler_builtins: None,
722 profiler_runtime: None,
723 sanitizer_runtime: None,
724 is_no_builtins: Default::default(),
725 native_libraries: Default::default(),
726 used_libraries: tcx.native_libraries(LOCAL_CRATE),
727 link_args: tcx.link_args(LOCAL_CRATE),
728 crate_name: Default::default(),
729 used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
730 used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
731 used_crate_source: Default::default(),
732 lang_item_to_crate: Default::default(),
733 missing_lang_items: Default::default(),
735 let lang_items = tcx.lang_items();
737 let crates = tcx.crates();
739 let n_crates = crates.len();
740 info.native_libraries.reserve(n_crates);
741 info.crate_name.reserve(n_crates);
742 info.used_crate_source.reserve(n_crates);
743 info.missing_lang_items.reserve(n_crates);
745 for &cnum in crates.iter() {
746 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
747 info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
748 info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
749 if tcx.is_panic_runtime(cnum) {
750 info.panic_runtime = Some(cnum);
752 if tcx.is_compiler_builtins(cnum) {
753 info.compiler_builtins = Some(cnum);
755 if tcx.is_profiler_runtime(cnum) {
756 info.profiler_runtime = Some(cnum);
758 if tcx.is_sanitizer_runtime(cnum) {
759 info.sanitizer_runtime = Some(cnum);
761 if tcx.is_no_builtins(cnum) {
762 info.is_no_builtins.insert(cnum);
764 let missing = tcx.missing_lang_items(cnum);
765 for &item in missing.iter() {
766 if let Ok(id) = lang_items.require(item) {
767 info.lang_item_to_crate.insert(item, id.krate);
771 // No need to look for lang items that are whitelisted and don't
772 // actually need to exist.
773 let missing = missing.iter()
775 .filter(|&l| !weak_lang_items::whitelisted(tcx, l))
777 info.missing_lang_items.insert(cnum, missing);
784 fn is_codegened_item(tcx: TyCtxt<'_>, id: DefId) -> bool {
785 let (all_mono_items, _) =
786 tcx.collect_and_partition_mono_items(LOCAL_CRATE);
787 all_mono_items.contains(&id)
790 pub fn provide_both(providers: &mut Providers<'_>) {
791 providers.backend_optimization_level = |tcx, cratenum| {
792 let for_speed = match tcx.sess.opts.optimize {
793 // If globally no optimisation is done, #[optimize] has no effect.
795 // This is done because if we ended up "upgrading" to `-O2` here, we’d populate the
796 // pass manager and it is likely that some module-wide passes (such as inliner or
797 // cross-function constant propagation) would ignore the `optnone` annotation we put
798 // on the functions, thus necessarily involving these functions into optimisations.
799 config::OptLevel::No => return config::OptLevel::No,
800 // If globally optimise-speed is already specified, just use that level.
801 config::OptLevel::Less => return config::OptLevel::Less,
802 config::OptLevel::Default => return config::OptLevel::Default,
803 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
804 // If globally optimize-for-size has been requested, use -O2 instead (if optimize(size)
806 config::OptLevel::Size => config::OptLevel::Default,
807 config::OptLevel::SizeMin => config::OptLevel::Default,
810 let (defids, _) = tcx.collect_and_partition_mono_items(cratenum);
812 let hir::CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
814 attr::OptimizeAttr::None => continue,
815 attr::OptimizeAttr::Size => continue,
816 attr::OptimizeAttr::Speed => {
821 return tcx.sess.opts.optimize;
824 providers.dllimport_foreign_items = |tcx, krate| {
825 let module_map = tcx.foreign_modules(krate);
826 let module_map = module_map.iter()
827 .map(|lib| (lib.def_id, lib))
828 .collect::<FxHashMap<_, _>>();
830 let dllimports = tcx.native_libraries(krate)
833 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
836 let cfg = match lib.cfg {
837 Some(ref cfg) => cfg,
840 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
842 .filter_map(|lib| lib.foreign_module)
843 .map(|id| &module_map[&id])
844 .flat_map(|module| module.foreign_items.iter().cloned())
846 tcx.arena.alloc(dllimports)
849 providers.is_dllimport_foreign_item = |tcx, def_id| {
850 tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
854 fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
855 if !tcx.dep_graph.is_fully_enabled() {
859 let work_product_id = &cgu.work_product_id();
860 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
861 // We don't have anything cached for this CGU. This can happen
862 // if the CGU did not exist in the previous session.
866 // Try to mark the CGU as green. If it we can do so, it means that nothing
867 // affecting the LLVM module has changed and we can re-use a cached version.
868 // If we compile with any kind of LTO, this means we can re-use the bitcode
869 // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
870 // know that later). If we are not doing LTO, there is only one optimized
871 // version of each module, so we re-use that.
872 let dep_node = cgu.codegen_dep_node(tcx);
873 assert!(!tcx.dep_graph.dep_node_exists(&dep_node),
874 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
877 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
878 // We can re-use either the pre- or the post-thinlto state
879 if tcx.sess.lto() != Lto::No {