1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Translate the completed AST to the LLVM IR.
13 //! Some functions here, such as trans_block and trans_expr, return a value --
14 //! the result of the translation to LLVM -- while others, such as trans_fn
15 //! and trans_item, are called only for the side effect of adding a
16 //! particular definition to the LLVM IR output we're producing.
18 //! Hopefully useful general knowledge about trans:
20 //! * There's no way to find out the Ty type of a ValueRef. Doing so
21 //! would be "trying to get the eggs out of an omelette" (credit:
22 //! pcwalton). You can, instead, find out its TypeRef by calling val_ty,
23 //! but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
24 //! int) and rec(x=int, y=int, z=int) will have the same TypeRef.
26 #![allow(non_camel_case_types)]
28 use super::CrateTranslation;
29 use super::ModuleLlvm;
30 use super::ModuleSource;
31 use super::ModuleTranslation;
33 use assert_module_sources;
35 use back::linker::LinkerInfo;
36 use llvm::{BasicBlockRef, Linkage, ValueRef, Vector, get_param};
39 use rustc::hir::def_id::DefId;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use rustc::hir::pat_util::simple_name;
42 use rustc::ty::subst::{self, Substs};
44 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
45 use rustc::ty::adjustment::CustomCoerceUnsized;
46 use rustc::dep_graph::{DepNode, WorkProduct};
47 use rustc::hir::map as hir_map;
48 use rustc::util::common::time;
49 use rustc::mir::mir_map::MirMap;
50 use rustc_data_structures::graph::OUTGOING;
51 use session::config::{self, NoDebugInfo, FullDebugInfo};
54 use abi::{self, Abi, FnType};
58 use builder::{Builder, noname};
59 use callee::{Callee, CallArgs, ArgExprs, ArgVals};
60 use cleanup::{self, CleanupMethods, DropHint};
62 use common::{Block, C_bool, C_bytes_in_context, C_i32, C_int, C_uint, C_integral};
63 use collector::{self, TransItemCollectionMode};
64 use common::{C_null, C_struct_in_context, C_u64, C_u8, C_undef};
65 use common::{CrateContext, DropFlagHintsMap, Field, FunctionContext};
66 use common::{Result, NodeIdAndSpan, VariantInfo};
67 use common::{node_id_type, fulfill_obligation};
68 use common::{type_is_immediate, type_is_zero_size, val_ty};
71 use context::{SharedCrateContext, CrateContextList};
74 use debuginfo::{self, DebugLoc, ToDebugLoc};
80 use machine::{llalign_of_min, llsize_of};
83 use monomorphize::{self, Instance};
84 use partitioning::{self, PartitioningStrategy, CodegenUnit};
85 use symbol_map::SymbolMap;
86 use symbol_names_test;
87 use trans_item::TransItem;
93 use util::common::indenter;
94 use util::sha2::Sha256;
95 use util::nodemap::{NodeMap, NodeSet, FnvHashSet};
97 use arena::TypedArena;
99 use std::ffi::{CStr, CString};
100 use std::borrow::Cow;
101 use std::cell::{Cell, RefCell};
102 use std::collections::HashMap;
106 use std::{i8, i16, i32, i64};
107 use syntax_pos::{Span, DUMMY_SP};
108 use syntax::parse::token::InternedString;
109 use syntax::attr::AttrMetaMethods;
111 use rustc::hir::intravisit::{self, Visitor};
116 static TASK_LOCAL_INSN_KEY: RefCell<Option<Vec<&'static str>>> = {
121 pub fn with_insn_ctxt<F>(blk: F)
122 where F: FnOnce(&[&'static str])
124 TASK_LOCAL_INSN_KEY.with(move |slot| {
125 slot.borrow().as_ref().map(move |s| blk(s));
129 pub fn init_insn_ctxt() {
130 TASK_LOCAL_INSN_KEY.with(|slot| {
131 *slot.borrow_mut() = Some(Vec::new());
135 pub struct _InsnCtxt {
136 _cannot_construct_outside_of_this_module: (),
139 impl Drop for _InsnCtxt {
141 TASK_LOCAL_INSN_KEY.with(|slot| {
142 if let Some(ctx) = slot.borrow_mut().as_mut() {
149 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
150 debug!("new InsnCtxt: {}", s);
151 TASK_LOCAL_INSN_KEY.with(|slot| {
152 if let Some(ctx) = slot.borrow_mut().as_mut() {
157 _cannot_construct_outside_of_this_module: (),
161 pub struct StatRecorder<'a, 'tcx: 'a> {
162 ccx: &'a CrateContext<'a, 'tcx>,
163 name: Option<String>,
167 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
168 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
169 let istart = ccx.stats().n_llvm_insns.get();
178 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
180 if self.ccx.sess().trans_stats() {
181 let iend = self.ccx.stats().n_llvm_insns.get();
186 .push((self.name.take().unwrap(), iend - self.istart));
187 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
188 // Reset LLVM insn count to avoid compound costs.
189 self.ccx.stats().n_llvm_insns.set(self.istart);
194 pub fn kind_for_closure(ccx: &CrateContext, closure_id: DefId) -> ty::ClosureKind {
195 *ccx.tcx().tables.borrow().closure_kinds.get(&closure_id).unwrap()
198 fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, info_ty: Ty<'tcx>, it: LangItem) -> DefId {
199 match bcx.tcx().lang_items.require(it) {
202 bcx.sess().fatal(&format!("allocation of `{}` {}", info_ty, s));
207 // The following malloc_raw_dyn* functions allocate a box to contain
208 // a given type, but with a potentially dynamic size.
210 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
216 -> Result<'blk, 'tcx> {
217 let _icx = push_ctxt("malloc_raw_exchange");
220 let def_id = require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem);
221 let r = Callee::def(bcx.ccx(), def_id, bcx.tcx().mk_substs(Substs::empty()))
222 .call(bcx, debug_loc, ArgVals(&[size, align]), None);
224 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
228 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
230 -> llvm::IntPredicate {
232 hir::BiEq => llvm::IntEQ,
233 hir::BiNe => llvm::IntNE,
234 hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
235 hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
236 hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
237 hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
239 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
246 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
248 hir::BiEq => llvm::RealOEQ,
249 hir::BiNe => llvm::RealUNE,
250 hir::BiLt => llvm::RealOLT,
251 hir::BiLe => llvm::RealOLE,
252 hir::BiGt => llvm::RealOGT,
253 hir::BiGe => llvm::RealOGE,
255 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
262 pub fn compare_fat_ptrs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
273 let addr_eq = ICmp(bcx, llvm::IntEQ, lhs_addr, rhs_addr, debug_loc);
274 let extra_eq = ICmp(bcx, llvm::IntEQ, lhs_extra, rhs_extra, debug_loc);
275 And(bcx, addr_eq, extra_eq, debug_loc)
278 let addr_eq = ICmp(bcx, llvm::IntNE, lhs_addr, rhs_addr, debug_loc);
279 let extra_eq = ICmp(bcx, llvm::IntNE, lhs_extra, rhs_extra, debug_loc);
280 Or(bcx, addr_eq, extra_eq, debug_loc)
282 hir::BiLe | hir::BiLt | hir::BiGe | hir::BiGt => {
283 // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
284 let (op, strict_op) = match op {
285 hir::BiLt => (llvm::IntULT, llvm::IntULT),
286 hir::BiLe => (llvm::IntULE, llvm::IntULT),
287 hir::BiGt => (llvm::IntUGT, llvm::IntUGT),
288 hir::BiGe => (llvm::IntUGE, llvm::IntUGT),
292 let addr_eq = ICmp(bcx, llvm::IntEQ, lhs_addr, rhs_addr, debug_loc);
293 let extra_op = ICmp(bcx, op, lhs_extra, rhs_extra, debug_loc);
294 let addr_eq_extra_op = And(bcx, addr_eq, extra_op, debug_loc);
296 let addr_strict = ICmp(bcx, strict_op, lhs_addr, rhs_addr, debug_loc);
297 Or(bcx, addr_strict, addr_eq_extra_op, debug_loc)
300 bug!("unexpected fat ptr binop");
305 pub fn compare_scalar_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
313 ty::TyTuple(ref tys) if tys.is_empty() => {
314 // We don't need to do actual comparisons for nil.
315 // () == () holds but () < () does not.
317 hir::BiEq | hir::BiLe | hir::BiGe => return C_bool(bcx.ccx(), true),
318 hir::BiNe | hir::BiLt | hir::BiGt => return C_bool(bcx.ccx(), false),
319 // refinements would be nice
320 _ => bug!("compare_scalar_types: must be a comparison operator"),
323 ty::TyFnDef(..) | ty::TyFnPtr(_) | ty::TyBool | ty::TyUint(_) | ty::TyChar => {
325 bin_op_to_icmp_predicate(op, false),
330 ty::TyRawPtr(mt) if common::type_is_sized(bcx.tcx(), mt.ty) => {
332 bin_op_to_icmp_predicate(op, false),
338 let lhs_addr = Load(bcx, GEPi(bcx, lhs, &[0, abi::FAT_PTR_ADDR]));
339 let lhs_extra = Load(bcx, GEPi(bcx, lhs, &[0, abi::FAT_PTR_EXTRA]));
341 let rhs_addr = Load(bcx, GEPi(bcx, rhs, &[0, abi::FAT_PTR_ADDR]));
342 let rhs_extra = Load(bcx, GEPi(bcx, rhs, &[0, abi::FAT_PTR_EXTRA]));
343 compare_fat_ptrs(bcx,
354 bin_op_to_icmp_predicate(op, true),
361 bin_op_to_fcmp_predicate(op),
366 // Should never get here, because t is scalar.
367 _ => bug!("non-scalar type passed to compare_scalar_types"),
371 pub fn compare_simd_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
379 let signed = match t.sty {
381 let cmp = bin_op_to_fcmp_predicate(op);
382 return SExt(bcx, FCmp(bcx, cmp, lhs, rhs, debug_loc), ret_ty);
384 ty::TyUint(_) => false,
385 ty::TyInt(_) => true,
386 _ => bug!("compare_simd_types: invalid SIMD type"),
389 let cmp = bin_op_to_icmp_predicate(op, signed);
390 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
391 // to get the correctly sized type. This will compile to a single instruction
392 // once the IR is converted to assembly if the SIMD instruction is supported
393 // by the target architecture.
394 SExt(bcx, ICmp(bcx, cmp, lhs, rhs, debug_loc), ret_ty)
397 // Iterates through the elements of a structural type.
398 pub fn iter_structural_ty<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
403 where F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>
405 let _icx = push_ctxt("iter_structural_ty");
407 fn iter_variant<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
408 repr: &adt::Repr<'tcx>,
409 av: adt::MaybeSizedValue,
410 variant: ty::VariantDef<'tcx>,
411 substs: &Substs<'tcx>,
414 where F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>
416 let _icx = push_ctxt("iter_variant");
420 for (i, field) in variant.fields.iter().enumerate() {
421 let arg = monomorphize::field_ty(tcx, substs, field);
423 adt::trans_field_ptr(cx, repr, av, Disr::from(variant.disr_val), i),
429 let value = if common::type_is_sized(cx.tcx(), t) {
430 adt::MaybeSizedValue::sized(av)
432 let data = Load(cx, expr::get_dataptr(cx, av));
433 let info = Load(cx, expr::get_meta(cx, av));
434 adt::MaybeSizedValue::unsized_(data, info)
439 ty::TyStruct(..) => {
440 let repr = adt::represent_type(cx.ccx(), t);
441 let VariantInfo { fields, discr } = VariantInfo::from_ty(cx.tcx(), t, None);
442 for (i, &Field(_, field_ty)) in fields.iter().enumerate() {
443 let llfld_a = adt::trans_field_ptr(cx, &repr, value, Disr::from(discr), i);
445 let val = if common::type_is_sized(cx.tcx(), field_ty) {
448 let scratch = datum::rvalue_scratch_datum(cx, field_ty, "__fat_ptr_iter");
449 Store(cx, llfld_a, expr::get_dataptr(cx, scratch.val));
450 Store(cx, value.meta, expr::get_meta(cx, scratch.val));
453 cx = f(cx, val, field_ty);
456 ty::TyClosure(_, ref substs) => {
457 let repr = adt::represent_type(cx.ccx(), t);
458 for (i, upvar_ty) in substs.upvar_tys.iter().enumerate() {
459 let llupvar = adt::trans_field_ptr(cx, &repr, value, Disr(0), i);
460 cx = f(cx, llupvar, upvar_ty);
463 ty::TyArray(_, n) => {
464 let (base, len) = tvec::get_fixed_base_and_len(cx, value.value, n);
465 let unit_ty = t.sequence_element_type(cx.tcx());
466 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
468 ty::TySlice(_) | ty::TyStr => {
469 let unit_ty = t.sequence_element_type(cx.tcx());
470 cx = tvec::iter_vec_raw(cx, value.value, unit_ty, value.meta, f);
472 ty::TyTuple(ref args) => {
473 let repr = adt::represent_type(cx.ccx(), t);
474 for (i, arg) in args.iter().enumerate() {
475 let llfld_a = adt::trans_field_ptr(cx, &repr, value, Disr(0), i);
476 cx = f(cx, llfld_a, *arg);
479 ty::TyEnum(en, substs) => {
483 let repr = adt::represent_type(ccx, t);
484 let n_variants = en.variants.len();
486 // NB: we must hit the discriminant first so that structural
487 // comparison know not to proceed when the discriminants differ.
489 match adt::trans_switch(cx, &repr, av, false) {
490 (_match::Single, None) => {
492 assert!(n_variants == 1);
493 cx = iter_variant(cx, &repr, adt::MaybeSizedValue::sized(av),
494 &en.variants[0], substs, &mut f);
497 (_match::Switch, Some(lldiscrim_a)) => {
498 cx = f(cx, lldiscrim_a, cx.tcx().types.isize);
500 // Create a fall-through basic block for the "else" case of
501 // the switch instruction we're about to generate. Note that
502 // we do **not** use an Unreachable instruction here, even
503 // though most of the time this basic block will never be hit.
505 // When an enum is dropped it's contents are currently
506 // overwritten to DTOR_DONE, which means the discriminant
507 // could have changed value to something not within the actual
508 // range of the discriminant. Currently this function is only
509 // used for drop glue so in this case we just return quickly
510 // from the outer function, and any other use case will only
511 // call this for an already-valid enum in which case the `ret
512 // void` will never be hit.
513 let ret_void_cx = fcx.new_temp_block("enum-iter-ret-void");
514 RetVoid(ret_void_cx, DebugLoc::None);
515 let llswitch = Switch(cx, lldiscrim_a, ret_void_cx.llbb, n_variants);
516 let next_cx = fcx.new_temp_block("enum-iter-next");
518 for variant in &en.variants {
519 let variant_cx = fcx.new_temp_block(&format!("enum-iter-variant-{}",
522 let case_val = adt::trans_case(cx, &repr, Disr::from(variant.disr_val));
523 AddCase(llswitch, case_val, variant_cx.llbb);
524 let variant_cx = iter_variant(variant_cx,
530 Br(variant_cx, next_cx.llbb, DebugLoc::None);
534 _ => ccx.sess().unimpl("value from adt::trans_switch in iter_structural_ty"),
538 cx.sess().unimpl(&format!("type in iter_structural_ty: {}", t))
545 /// Retrieve the information we are losing (making dynamic) in an unsizing
548 /// The `old_info` argument is a bit funny. It is intended for use
549 /// in an upcast, where the new vtable for an object will be drived
550 /// from the old one.
551 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
554 old_info: Option<ValueRef>)
556 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
557 match (&source.sty, &target.sty) {
558 (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
559 (&ty::TyTrait(_), &ty::TyTrait(_)) => {
560 // For now, upcasts are limited to changes in marker
561 // traits, and hence never actually require an actual
562 // change to the vtable.
563 old_info.expect("unsized_info: missing old info for trait upcast")
565 (_, &ty::TyTrait(box ty::TraitTy { ref principal, .. })) => {
566 // Note that we preserve binding levels here:
567 let substs = principal.0.substs.with_self_ty(source).erase_regions();
568 let substs = ccx.tcx().mk_substs(substs);
569 let trait_ref = ty::Binder(ty::TraitRef {
570 def_id: principal.def_id(),
573 consts::ptrcast(meth::get_vtable(ccx, trait_ref),
574 Type::vtable_ptr(ccx))
576 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
582 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
583 pub fn unsize_thin_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
587 -> (ValueRef, ValueRef) {
588 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
589 match (&src_ty.sty, &dst_ty.sty) {
590 (&ty::TyBox(a), &ty::TyBox(b)) |
591 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
592 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
593 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
594 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
595 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
596 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
597 assert!(common::type_is_sized(bcx.tcx(), a));
598 let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), b).ptr_to();
599 (PointerCast(bcx, src, ptr_ty),
600 unsized_info(bcx.ccx(), a, b, None))
602 _ => bug!("unsize_thin_ptr: called on bad types"),
606 /// Coerce `src`, which is a reference to a value of type `src_ty`,
607 /// to a value of type `dst_ty` and store the result in `dst`
608 pub fn coerce_unsized_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
613 match (&src_ty.sty, &dst_ty.sty) {
614 (&ty::TyBox(..), &ty::TyBox(..)) |
615 (&ty::TyRef(..), &ty::TyRef(..)) |
616 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
617 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
618 let (base, info) = if common::type_is_fat_ptr(bcx.tcx(), src_ty) {
619 // fat-ptr to fat-ptr unsize preserves the vtable
620 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
621 // So we need to pointercast the base to ensure
622 // the types match up.
623 let (base, info) = load_fat_ptr(bcx, src, src_ty);
624 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx(), dst_ty);
625 let base = PointerCast(bcx, base, llcast_ty);
628 let base = load_ty(bcx, src, src_ty);
629 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
631 store_fat_ptr(bcx, base, info, dst, dst_ty);
634 // This can be extended to enums and tuples in the future.
635 // (&ty::TyEnum(def_id_a, _), &ty::TyEnum(def_id_b, _)) |
636 (&ty::TyStruct(def_a, _), &ty::TyStruct(def_b, _)) => {
637 assert_eq!(def_a, def_b);
639 let src_repr = adt::represent_type(bcx.ccx(), src_ty);
640 let src_fields = match &*src_repr {
641 &adt::Repr::Univariant(ref s, _) => &s.fields,
642 _ => bug!("struct has non-univariant repr"),
644 let dst_repr = adt::represent_type(bcx.ccx(), dst_ty);
645 let dst_fields = match &*dst_repr {
646 &adt::Repr::Univariant(ref s, _) => &s.fields,
647 _ => bug!("struct has non-univariant repr"),
650 let src = adt::MaybeSizedValue::sized(src);
651 let dst = adt::MaybeSizedValue::sized(dst);
653 let iter = src_fields.iter().zip(dst_fields).enumerate();
654 for (i, (src_fty, dst_fty)) in iter {
655 if type_is_zero_size(bcx.ccx(), dst_fty) {
659 let src_f = adt::trans_field_ptr(bcx, &src_repr, src, Disr(0), i);
660 let dst_f = adt::trans_field_ptr(bcx, &dst_repr, dst, Disr(0), i);
661 if src_fty == dst_fty {
662 memcpy_ty(bcx, dst_f, src_f, src_fty);
664 coerce_unsized_into(bcx, src_f, src_fty, dst_f, dst_fty);
668 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
674 pub fn custom_coerce_unsize_info<'scx, 'tcx>(scx: &SharedCrateContext<'scx, 'tcx>,
677 -> CustomCoerceUnsized {
678 let trait_substs = Substs::new(subst::VecPerParamSpace::new(vec![target_ty],
681 subst::VecPerParamSpace::empty());
683 let trait_ref = ty::Binder(ty::TraitRef {
684 def_id: scx.tcx().lang_items.coerce_unsized_trait().unwrap(),
685 substs: scx.tcx().mk_substs(trait_substs)
688 match fulfill_obligation(scx, DUMMY_SP, trait_ref) {
689 traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
690 scx.tcx().custom_coerce_unsized_kind(impl_def_id)
693 bug!("invalid CoerceUnsized vtable: {:?}", vtable);
698 pub fn cast_shift_expr_rhs(cx: Block, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
699 cast_shift_rhs(op, lhs, rhs, |a, b| Trunc(cx, a, b), |a, b| ZExt(cx, a, b))
702 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
706 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
707 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
710 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
716 where F: FnOnce(ValueRef, Type) -> ValueRef,
717 G: FnOnce(ValueRef, Type) -> ValueRef
719 // Shifts may have any size int on the rhs
721 let mut rhs_llty = val_ty(rhs);
722 let mut lhs_llty = val_ty(lhs);
723 if rhs_llty.kind() == Vector {
724 rhs_llty = rhs_llty.element_type()
726 if lhs_llty.kind() == Vector {
727 lhs_llty = lhs_llty.element_type()
729 let rhs_sz = rhs_llty.int_width();
730 let lhs_sz = lhs_llty.int_width();
733 } else if lhs_sz > rhs_sz {
734 // FIXME (#1877: If shifting by negative
735 // values becomes not undefined then this is wrong.
745 pub fn llty_and_min_for_signed_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
750 let llty = Type::int_from_ty(cx.ccx(), t);
752 ast::IntTy::Is if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
753 ast::IntTy::Is => i64::MIN as u64,
754 ast::IntTy::I8 => i8::MIN as u64,
755 ast::IntTy::I16 => i16::MIN as u64,
756 ast::IntTy::I32 => i32::MIN as u64,
757 ast::IntTy::I64 => i64::MIN as u64,
765 pub fn fail_if_zero_or_overflows<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
766 call_info: NodeIdAndSpan,
771 -> Block<'blk, 'tcx> {
772 use rustc_const_math::{ConstMathErr, Op};
774 let (zero_err, overflow_err) = if divrem.node == hir::BiDiv {
775 (ConstMathErr::DivisionByZero, ConstMathErr::Overflow(Op::Div))
777 (ConstMathErr::RemainderByZero, ConstMathErr::Overflow(Op::Rem))
779 let debug_loc = call_info.debug_loc();
781 let (is_zero, is_signed) = match rhs_t.sty {
783 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0, false);
784 (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), true)
787 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0, false);
788 (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), false)
790 ty::TyStruct(def, _) if def.is_simd() => {
791 let mut res = C_bool(cx.ccx(), false);
792 for i in 0..rhs_t.simd_size(cx.tcx()) {
795 IsNull(cx, ExtractElement(cx, rhs, C_int(cx.ccx(), i as i64))),
801 bug!("fail-if-zero on unexpected type: {}", rhs_t);
804 let bcx = with_cond(cx, is_zero, |bcx| {
805 controlflow::trans_fail(bcx, call_info, InternedString::new(zero_err.description()))
808 // To quote LLVM's documentation for the sdiv instruction:
810 // Division by zero leads to undefined behavior. Overflow also leads
811 // to undefined behavior; this is a rare case, but can occur, for
812 // example, by doing a 32-bit division of -2147483648 by -1.
814 // In order to avoid undefined behavior, we perform runtime checks for
815 // signed division/remainder which would trigger overflow. For unsigned
816 // integers, no action beyond checking for zero need be taken.
818 let (llty, min) = llty_and_min_for_signed_ty(cx, rhs_t);
819 let minus_one = ICmp(bcx,
822 C_integral(llty, !0, false),
824 with_cond(bcx, minus_one, |bcx| {
825 let is_min = ICmp(bcx,
828 C_integral(llty, min, true),
830 with_cond(bcx, is_min, |bcx| {
831 controlflow::trans_fail(bcx, call_info,
832 InternedString::new(overflow_err.description()))
840 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
844 -> (ValueRef, Block<'blk, 'tcx>) {
845 let _icx = push_ctxt("invoke_");
846 if bcx.unreachable.get() {
847 return (C_null(Type::i8(bcx.ccx())), bcx);
850 match bcx.opt_node_id {
852 debug!("invoke at ???");
855 debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
859 if need_invoke(bcx) {
860 debug!("invoking {:?} at {:?}", Value(llfn), bcx.llbb);
861 for &llarg in llargs {
862 debug!("arg: {:?}", Value(llarg));
864 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
865 let landing_pad = bcx.fcx.get_landing_pad();
867 let llresult = Invoke(bcx,
873 return (llresult, normal_bcx);
875 debug!("calling {:?} at {:?}", Value(llfn), bcx.llbb);
876 for &llarg in llargs {
877 debug!("arg: {:?}", Value(llarg));
880 let llresult = Call(bcx, llfn, &llargs[..], debug_loc);
881 return (llresult, bcx);
885 /// Returns whether this session's target will use SEH-based unwinding.
887 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
888 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
889 /// 64-bit MinGW) instead of "full SEH".
890 pub fn wants_msvc_seh(sess: &Session) -> bool {
891 sess.target.target.options.is_like_msvc
894 pub fn avoid_invoke(bcx: Block) -> bool {
895 bcx.sess().no_landing_pads() || bcx.lpad().is_some()
898 pub fn need_invoke(bcx: Block) -> bool {
899 if avoid_invoke(bcx) {
902 bcx.fcx.needs_invoke()
906 pub fn load_if_immediate<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, t: Ty<'tcx>) -> ValueRef {
907 let _icx = push_ctxt("load_if_immediate");
908 if type_is_immediate(cx.ccx(), t) {
909 return load_ty(cx, v, t);
914 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
915 /// differs from the type used for SSA values. Also handles various special cases where the type
916 /// gives us better information about what we are loading.
917 pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
918 if cx.unreachable.get() {
919 return C_undef(type_of::type_of(cx.ccx(), t));
921 load_ty_builder(&B(cx), ptr, t)
924 pub fn load_ty_builder<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
926 if type_is_zero_size(ccx, t) {
927 return C_undef(type_of::type_of(ccx, t));
931 let global = llvm::LLVMIsAGlobalVariable(ptr);
932 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
933 let val = llvm::LLVMGetInitializer(global);
936 return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
944 b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False), Type::i1(ccx))
945 } else if t.is_char() {
946 // a char is a Unicode codepoint, and so takes values from 0
947 // to 0x10FFFF inclusive only.
948 b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False)
949 } else if (t.is_region_ptr() || t.is_unique()) &&
950 !common::type_is_fat_ptr(ccx.tcx(), t) {
957 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
958 /// differs from the type used for SSA values.
959 pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
960 if cx.unreachable.get() {
964 debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
966 if common::type_is_fat_ptr(cx.tcx(), t) {
968 ExtractValue(cx, v, abi::FAT_PTR_ADDR),
969 expr::get_dataptr(cx, dst));
971 ExtractValue(cx, v, abi::FAT_PTR_EXTRA),
972 expr::get_meta(cx, dst));
974 Store(cx, from_immediate(cx, v), dst);
978 pub fn store_fat_ptr<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
983 // FIXME: emit metadata
984 Store(cx, data, expr::get_dataptr(cx, dst));
985 Store(cx, extra, expr::get_meta(cx, dst));
988 pub fn load_fat_ptr<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
991 -> (ValueRef, ValueRef) {
992 // FIXME: emit metadata
993 (Load(cx, expr::get_dataptr(cx, src)),
994 Load(cx, expr::get_meta(cx, src)))
997 pub fn from_immediate(bcx: Block, val: ValueRef) -> ValueRef {
998 if val_ty(val) == Type::i1(bcx.ccx()) {
999 ZExt(bcx, val, Type::i8(bcx.ccx()))
1005 pub fn to_immediate(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
1007 Trunc(bcx, val, Type::i1(bcx.ccx()))
1013 pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &hir::Local) -> Block<'blk, 'tcx> {
1014 debug!("init_local(bcx={}, local.id={})", bcx.to_str(), local.id);
1015 let _indenter = indenter();
1016 let _icx = push_ctxt("init_local");
1017 _match::store_local(bcx, local)
1020 pub fn raw_block<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1021 llbb: BasicBlockRef)
1022 -> Block<'blk, 'tcx> {
1023 common::BlockS::new(llbb, None, fcx)
1026 pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>, val: ValueRef, f: F) -> Block<'blk, 'tcx>
1027 where F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>
1029 let _icx = push_ctxt("with_cond");
1031 if bcx.unreachable.get() || common::const_to_opt_uint(val) == Some(0) {
1036 let next_cx = fcx.new_temp_block("next");
1037 let cond_cx = fcx.new_temp_block("cond");
1038 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb, DebugLoc::None);
1039 let after_cx = f(cond_cx);
1040 if !after_cx.terminated.get() {
1041 Br(after_cx, next_cx.llbb, DebugLoc::None);
1046 pub enum Lifetime { Start, End }
1048 // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
1049 // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
1050 // and the intrinsic for `lt` and passes them to `emit`, which is in
1051 // charge of generating code to call the passed intrinsic on whatever
1052 // block of generated code is targetted for the intrinsic.
1054 // If LLVM lifetime intrinsic support is disabled (i.e. optimizations
1055 // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
1056 fn core_lifetime_emit<'blk, 'tcx, F>(ccx: &'blk CrateContext<'blk, 'tcx>,
1060 where F: FnOnce(&'blk CrateContext<'blk, 'tcx>, machine::llsize, ValueRef)
1062 if ccx.sess().opts.optimize == config::OptLevel::No {
1066 let _icx = push_ctxt(match lt {
1067 Lifetime::Start => "lifetime_start",
1068 Lifetime::End => "lifetime_end"
1071 let size = machine::llsize_of_alloc(ccx, val_ty(ptr).element_type());
1076 let lifetime_intrinsic = ccx.get_intrinsic(match lt {
1077 Lifetime::Start => "llvm.lifetime.start",
1078 Lifetime::End => "llvm.lifetime.end"
1080 emit(ccx, size, lifetime_intrinsic)
1084 pub fn call(self, b: &Builder, ptr: ValueRef) {
1085 core_lifetime_emit(b.ccx, ptr, self, |ccx, size, lifetime_intrinsic| {
1086 let ptr = b.pointercast(ptr, Type::i8p(ccx));
1087 b.call(lifetime_intrinsic, &[C_u64(ccx, size), ptr], None);
1092 pub fn call_lifetime_start(bcx: Block, ptr: ValueRef) {
1093 if !bcx.unreachable.get() {
1094 Lifetime::Start.call(&bcx.build(), ptr);
1098 pub fn call_lifetime_end(bcx: Block, ptr: ValueRef) {
1099 if !bcx.unreachable.get() {
1100 Lifetime::End.call(&bcx.build(), ptr);
1104 // Generates code for resumption of unwind at the end of a landing pad.
1105 pub fn trans_unwind_resume(bcx: Block, lpval: ValueRef) {
1106 if !bcx.sess().target.target.options.custom_unwind_resume {
1109 let exc_ptr = ExtractValue(bcx, lpval, 0);
1110 bcx.fcx.eh_unwind_resume()
1111 .call(bcx, DebugLoc::None, ArgVals(&[exc_ptr]), None);
1115 pub fn call_memcpy<'bcx, 'tcx>(b: &Builder<'bcx, 'tcx>,
1120 let _icx = push_ctxt("call_memcpy");
1122 let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
1123 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
1124 let memcpy = ccx.get_intrinsic(&key);
1125 let src_ptr = b.pointercast(src, Type::i8p(ccx));
1126 let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
1127 let size = b.intcast(n_bytes, ccx.int_type());
1128 let align = C_i32(ccx, align as i32);
1129 let volatile = C_bool(ccx, false);
1130 b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
1133 pub fn memcpy_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, dst: ValueRef, src: ValueRef, t: Ty<'tcx>) {
1134 let _icx = push_ctxt("memcpy_ty");
1135 let ccx = bcx.ccx();
1137 if type_is_zero_size(ccx, t) || bcx.unreachable.get() {
1141 if t.is_structural() {
1142 let llty = type_of::type_of(ccx, t);
1143 let llsz = llsize_of(ccx, llty);
1144 let llalign = type_of::align_of(ccx, t);
1145 call_memcpy(&B(bcx), dst, src, llsz, llalign as u32);
1146 } else if common::type_is_fat_ptr(bcx.tcx(), t) {
1147 let (data, extra) = load_fat_ptr(bcx, src, t);
1148 store_fat_ptr(bcx, data, extra, dst, t);
1150 store_ty(bcx, load_ty(bcx, src, t), dst, t);
1154 pub fn drop_done_fill_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
1155 if cx.unreachable.get() {
1158 let _icx = push_ctxt("drop_done_fill_mem");
1160 memfill(&B(bcx), llptr, t, adt::DTOR_DONE);
1163 pub fn init_zero_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
1164 if cx.unreachable.get() {
1167 let _icx = push_ctxt("init_zero_mem");
1169 memfill(&B(bcx), llptr, t, 0);
1172 // Always use this function instead of storing a constant byte to the memory
1173 // in question. e.g. if you store a zero constant, LLVM will drown in vreg
1174 // allocation for large data structures, and the generated code will be
1175 // awful. (A telltale sign of this is large quantities of
1176 // `mov [byte ptr foo],0` in the generated code.)
1177 fn memfill<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>, byte: u8) {
1178 let _icx = push_ctxt("memfill");
1180 let llty = type_of::type_of(ccx, ty);
1181 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1182 let llzeroval = C_u8(ccx, byte);
1183 let size = machine::llsize_of(ccx, llty);
1184 let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
1185 call_memset(b, llptr, llzeroval, size, align, false);
1188 pub fn call_memset<'bcx, 'tcx>(b: &Builder<'bcx, 'tcx>,
1190 fill_byte: ValueRef,
1195 let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
1196 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
1197 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1198 let volatile = C_bool(ccx, volatile);
1199 b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None);
1203 /// In general, when we create an scratch value in an alloca, the
1204 /// creator may not know if the block (that initializes the scratch
1205 /// with the desired value) actually dominates the cleanup associated
1206 /// with the scratch value.
1208 /// To deal with this, when we do an alloca (at the *start* of whole
1209 /// function body), we optionally can also set the associated
1210 /// dropped-flag state of the alloca to "dropped."
1211 #[derive(Copy, Clone, Debug)]
1212 pub enum InitAlloca {
1213 /// Indicates that the state should have its associated drop flag
1214 /// set to "dropped" at the point of allocation.
1216 /// Indicates the value of the associated drop flag is irrelevant.
1217 /// The embedded string literal is a programmer provided argument
1218 /// for why. This is a safeguard forcing compiler devs to
1219 /// document; it might be a good idea to also emit this as a
1220 /// comment with the alloca itself when emitting LLVM output.ll.
1221 Uninit(&'static str),
1225 pub fn alloc_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1227 name: &str) -> ValueRef {
1228 // pnkfelix: I do not know why alloc_ty meets the assumptions for
1229 // passing Uninit, but it was never needed (even back when we had
1230 // the original boolean `zero` flag on `lvalue_scratch_datum`).
1231 alloc_ty_init(bcx, t, InitAlloca::Uninit("all alloc_ty are uninit"), name)
1234 /// This variant of `fn alloc_ty` does not necessarily assume that the
1235 /// alloca should be created with no initial value. Instead the caller
1236 /// controls that assumption via the `init` flag.
1238 /// Note that if the alloca *is* initialized via `init`, then we will
1239 /// also inject an `llvm.lifetime.start` before that initialization
1240 /// occurs, and thus callers should not call_lifetime_start
1241 /// themselves. But if `init` says "uninitialized", then callers are
1242 /// in charge of choosing where to call_lifetime_start and
1243 /// subsequently populate the alloca.
1245 /// (See related discussion on PR #30823.)
1246 pub fn alloc_ty_init<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1249 name: &str) -> ValueRef {
1250 let _icx = push_ctxt("alloc_ty");
1251 let ccx = bcx.ccx();
1252 let ty = type_of::type_of(ccx, t);
1253 assert!(!t.has_param_types());
1255 InitAlloca::Dropped => alloca_dropped(bcx, t, name),
1256 InitAlloca::Uninit(_) => alloca(bcx, ty, name),
1260 pub fn alloca_dropped<'blk, 'tcx>(cx: Block<'blk, 'tcx>, ty: Ty<'tcx>, name: &str) -> ValueRef {
1261 let _icx = push_ctxt("alloca_dropped");
1262 let llty = type_of::type_of(cx.ccx(), ty);
1263 if cx.unreachable.get() {
1264 unsafe { return llvm::LLVMGetUndef(llty.ptr_to().to_ref()); }
1266 let p = alloca(cx, llty, name);
1267 let b = cx.fcx.ccx.builder();
1268 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1270 // This is just like `call_lifetime_start` (but latter expects a
1271 // Block, which we do not have for `alloca_insert_pt`).
1272 core_lifetime_emit(cx.ccx(), p, Lifetime::Start, |ccx, size, lifetime_start| {
1273 let ptr = b.pointercast(p, Type::i8p(ccx));
1274 b.call(lifetime_start, &[C_u64(ccx, size), ptr], None);
1276 memfill(&b, p, ty, adt::DTOR_DONE);
1280 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
1281 let _icx = push_ctxt("alloca");
1282 if cx.unreachable.get() {
1284 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1287 DebugLoc::None.apply(cx.fcx);
1288 Alloca(cx, ty, name)
1291 pub fn set_value_name(val: ValueRef, name: &str) {
1293 let name = CString::new(name).unwrap();
1294 llvm::LLVMSetValueName(val, name.as_ptr());
1298 struct FindNestedReturn {
1302 impl FindNestedReturn {
1303 fn new() -> FindNestedReturn {
1310 impl<'v> Visitor<'v> for FindNestedReturn {
1311 fn visit_expr(&mut self, e: &hir::Expr) {
1313 hir::ExprRet(..) => {
1316 _ => intravisit::walk_expr(self, e),
1321 fn build_cfg<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1323 -> (ast::NodeId, Option<cfg::CFG>) {
1324 let blk = match tcx.map.find(id) {
1325 Some(hir_map::NodeItem(i)) => {
1327 hir::ItemFn(_, _, _, _, _, ref blk) => {
1330 _ => bug!("unexpected item variant in has_nested_returns"),
1333 Some(hir_map::NodeTraitItem(trait_item)) => {
1334 match trait_item.node {
1335 hir::MethodTraitItem(_, Some(ref body)) => body,
1337 bug!("unexpected variant: trait item other than a provided method in \
1338 has_nested_returns")
1342 Some(hir_map::NodeImplItem(impl_item)) => {
1343 match impl_item.node {
1344 hir::ImplItemKind::Method(_, ref body) => body,
1346 bug!("unexpected variant: non-method impl item in has_nested_returns")
1350 Some(hir_map::NodeExpr(e)) => {
1352 hir::ExprClosure(_, _, ref blk, _) => blk,
1353 _ => bug!("unexpected expr variant in has_nested_returns"),
1356 Some(hir_map::NodeVariant(..)) |
1357 Some(hir_map::NodeStructCtor(..)) => return (ast::DUMMY_NODE_ID, None),
1360 None if id == ast::DUMMY_NODE_ID => return (ast::DUMMY_NODE_ID, None),
1362 _ => bug!("unexpected variant in has_nested_returns: {}",
1363 tcx.node_path_str(id)),
1366 (blk.id, Some(cfg::CFG::new(tcx, blk)))
1369 // Checks for the presence of "nested returns" in a function.
1370 // Nested returns are when the inner expression of a return expression
1371 // (the 'expr' in 'return expr') contains a return expression. Only cases
1372 // where the outer return is actually reachable are considered. Implicit
1373 // returns from the end of blocks are considered as well.
1375 // This check is needed to handle the case where the inner expression is
1376 // part of a larger expression that may have already partially-filled the
1377 // return slot alloca. This can cause errors related to clean-up due to
1378 // the clobbering of the existing value in the return slot.
1379 fn has_nested_returns(tcx: TyCtxt, cfg: &cfg::CFG, blk_id: ast::NodeId) -> bool {
1380 for index in cfg.graph.depth_traverse(cfg.entry, OUTGOING) {
1381 let n = cfg.graph.node_data(index);
1382 match tcx.map.find(n.id()) {
1383 Some(hir_map::NodeExpr(ex)) => {
1384 if let hir::ExprRet(Some(ref ret_expr)) = ex.node {
1385 let mut visitor = FindNestedReturn::new();
1386 intravisit::walk_expr(&mut visitor, &ret_expr);
1392 Some(hir_map::NodeBlock(blk)) if blk.id == blk_id => {
1393 let mut visitor = FindNestedReturn::new();
1394 walk_list!(&mut visitor, visit_expr, &blk.expr);
1406 impl<'blk, 'tcx> FunctionContext<'blk, 'tcx> {
1407 /// Create a function context for the given function.
1408 /// Beware that you must call `fcx.init` or `fcx.bind_args`
1409 /// before doing anything with the returned function context.
1410 pub fn new(ccx: &'blk CrateContext<'blk, 'tcx>,
1413 definition: Option<(Instance<'tcx>, &ty::FnSig<'tcx>, Abi, ast::NodeId)>,
1414 block_arena: &'blk TypedArena<common::BlockS<'blk, 'tcx>>)
1415 -> FunctionContext<'blk, 'tcx> {
1416 let (param_substs, def_id, inlined_id) = match definition {
1417 Some((instance, _, _, inlined_id)) => {
1418 common::validate_substs(instance.substs);
1419 (instance.substs, Some(instance.def), Some(inlined_id))
1421 None => (ccx.tcx().mk_substs(Substs::empty()), None, None)
1424 let local_id = def_id.and_then(|id| ccx.tcx().map.as_local_node_id(id));
1426 debug!("FunctionContext::new({})",
1427 definition.map_or(String::new(), |d| d.0.to_string()));
1429 let cfg = inlined_id.map(|id| build_cfg(ccx.tcx(), id));
1430 let nested_returns = if let Some((blk_id, Some(ref cfg))) = cfg {
1431 has_nested_returns(ccx.tcx(), cfg, blk_id)
1436 let check_attrs = |attrs: &[ast::Attribute]| {
1437 let default_to_mir = ccx.sess().opts.debugging_opts.orbit;
1438 let invert = if default_to_mir { "rustc_no_mir" } else { "rustc_mir" };
1439 (default_to_mir ^ attrs.iter().any(|item| item.check_name(invert)),
1440 attrs.iter().any(|item| item.check_name("no_debug")))
1443 let (use_mir, no_debug) = if let Some(id) = local_id {
1444 check_attrs(ccx.tcx().map.attrs(id))
1445 } else if let Some(def_id) = def_id {
1446 check_attrs(&ccx.sess().cstore.item_attrs(def_id))
1451 let mir = if use_mir {
1452 def_id.and_then(|id| ccx.get_mir(id))
1457 let debug_context = if let (false, Some(definition)) = (no_debug, definition) {
1458 let (instance, sig, abi, _) = definition;
1459 debuginfo::create_function_debug_context(ccx, instance, sig, abi, llfndecl)
1461 debuginfo::empty_function_debug_context(ccx)
1465 needs_ret_allocas: nested_returns && mir.is_none(),
1468 llretslotptr: Cell::new(None),
1469 param_env: ccx.tcx().empty_parameter_environment(),
1470 alloca_insert_pt: Cell::new(None),
1471 llreturn: Cell::new(None),
1472 landingpad_alloca: Cell::new(None),
1473 lllocals: RefCell::new(NodeMap()),
1474 llupvars: RefCell::new(NodeMap()),
1475 lldropflag_hints: RefCell::new(DropFlagHintsMap::new()),
1477 param_substs: param_substs,
1478 span: inlined_id.and_then(|id| ccx.tcx().map.opt_span(id)),
1479 block_arena: block_arena,
1480 lpad_arena: TypedArena::new(),
1482 debug_context: debug_context,
1483 scopes: RefCell::new(Vec::new()),
1484 cfg: cfg.and_then(|(_, cfg)| cfg)
1488 /// Performs setup on a newly created function, creating the entry
1489 /// scope block and allocating space for the return pointer.
1490 pub fn init(&'blk self, skip_retptr: bool, fn_did: Option<DefId>)
1491 -> Block<'blk, 'tcx> {
1492 let entry_bcx = self.new_temp_block("entry-block");
1494 // Use a dummy instruction as the insertion point for all allocas.
1495 // This is later removed in FunctionContext::cleanup.
1496 self.alloca_insert_pt.set(Some(unsafe {
1497 Load(entry_bcx, C_null(Type::i8p(self.ccx)));
1498 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1501 if !self.fn_ty.ret.is_ignore() && !skip_retptr {
1502 // We normally allocate the llretslotptr, unless we
1503 // have been instructed to skip it for immediate return
1504 // values, or there is nothing to return at all.
1506 // We create an alloca to hold a pointer of type `ret.original_ty`
1507 // which will hold the pointer to the right alloca which has the
1509 let llty = self.fn_ty.ret.memory_ty(self.ccx);
1510 let slot = if self.needs_ret_allocas {
1511 // Let's create the stack slot
1512 let slot = AllocaFcx(self, llty.ptr_to(), "llretslotptr");
1514 // and if we're using an out pointer, then store that in our newly made slot
1515 if self.fn_ty.ret.is_indirect() {
1516 let outptr = get_param(self.llfn, 0);
1518 let b = self.ccx.builder();
1519 b.position_before(self.alloca_insert_pt.get().unwrap());
1520 b.store(outptr, slot);
1525 // But if there are no nested returns, we skip the indirection
1526 // and have a single retslot
1527 if self.fn_ty.ret.is_indirect() {
1528 get_param(self.llfn, 0)
1530 AllocaFcx(self, llty, "sret_slot")
1534 self.llretslotptr.set(Some(slot));
1537 // Create the drop-flag hints for every unfragmented path in the function.
1538 let tcx = self.ccx.tcx();
1539 let tables = tcx.tables.borrow();
1540 let mut hints = self.lldropflag_hints.borrow_mut();
1541 let fragment_infos = tcx.fragment_infos.borrow();
1543 // Intern table for drop-flag hint datums.
1544 let mut seen = HashMap::new();
1546 let fragment_infos = fn_did.and_then(|did| fragment_infos.get(&did));
1547 if let Some(fragment_infos) = fragment_infos {
1548 for &info in fragment_infos {
1550 let make_datum = |id| {
1551 let init_val = C_u8(self.ccx, adt::DTOR_NEEDED_HINT);
1552 let llname = &format!("dropflag_hint_{}", id);
1553 debug!("adding hint {}", llname);
1554 let ty = tcx.types.u8;
1555 let ptr = alloc_ty(entry_bcx, ty, llname);
1556 Store(entry_bcx, init_val, ptr);
1557 let flag = datum::Lvalue::new_dropflag_hint("FunctionContext::init");
1558 datum::Datum::new(ptr, ty, flag)
1561 let (var, datum) = match info {
1562 ty::FragmentInfo::Moved { var, .. } |
1563 ty::FragmentInfo::Assigned { var, .. } => {
1564 let opt_datum = seen.get(&var).cloned().unwrap_or_else(|| {
1565 let ty = tables.node_types[&var];
1566 if self.type_needs_drop(ty) {
1567 let datum = make_datum(var);
1568 seen.insert(var, Some(datum.clone()));
1571 // No drop call needed, so we don't need a dropflag hint
1575 if let Some(datum) = opt_datum {
1583 ty::FragmentInfo::Moved { move_expr: expr_id, .. } => {
1584 debug!("FragmentInfo::Moved insert drop hint for {}", expr_id);
1585 hints.insert(expr_id, DropHint::new(var, datum));
1587 ty::FragmentInfo::Assigned { assignee_id: expr_id, .. } => {
1588 debug!("FragmentInfo::Assigned insert drop hint for {}", expr_id);
1589 hints.insert(expr_id, DropHint::new(var, datum));
1598 /// Creates lvalue datums for each of the incoming function arguments,
1599 /// matches all argument patterns against them to produce bindings,
1600 /// and returns the entry block (see FunctionContext::init).
1601 fn bind_args(&'blk self,
1605 closure_env: closure::ClosureEnv,
1606 arg_scope: cleanup::CustomScopeIndex)
1607 -> Block<'blk, 'tcx> {
1608 let _icx = push_ctxt("FunctionContext::bind_args");
1609 let fn_did = self.ccx.tcx().map.local_def_id(id);
1610 let mut bcx = self.init(false, Some(fn_did));
1611 let arg_scope_id = cleanup::CustomScope(arg_scope);
1614 let mut llarg_idx = self.fn_ty.ret.is_indirect() as usize;
1616 let has_tupled_arg = match closure_env {
1617 closure::ClosureEnv::NotClosure => abi == Abi::RustCall,
1618 closure::ClosureEnv::Closure(..) => {
1619 closure_env.load(bcx, arg_scope_id);
1620 let env_arg = &self.fn_ty.args[idx];
1622 if env_arg.pad.is_some() {
1625 if !env_arg.is_ignore() {
1631 let tupled_arg_id = if has_tupled_arg {
1632 args[args.len() - 1].id
1637 // Return an array wrapping the ValueRefs that we get from `get_param` for
1638 // each argument into datums.
1640 // For certain mode/type combinations, the raw llarg values are passed
1641 // by value. However, within the fn body itself, we want to always
1642 // have all locals and arguments be by-ref so that we can cancel the
1643 // cleanup and for better interaction with LLVM's debug info. So, if
1644 // the argument would be passed by value, we store it into an alloca.
1645 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1646 // the event it's not truly needed.
1647 let uninit_reason = InitAlloca::Uninit("fn_arg populate dominates dtor");
1648 for hir_arg in args {
1649 let arg_ty = node_id_type(bcx, hir_arg.id);
1650 let arg_datum = if hir_arg.id != tupled_arg_id {
1651 let arg = &self.fn_ty.args[idx];
1653 if arg.is_indirect() && bcx.sess().opts.debuginfo != FullDebugInfo {
1654 // Don't copy an indirect argument to an alloca, the caller
1655 // already put it in a temporary alloca and gave it up, unless
1656 // we emit extra-debug-info, which requires local allocas :(.
1657 let llarg = get_param(self.llfn, llarg_idx as c_uint);
1659 self.schedule_lifetime_end(arg_scope_id, llarg);
1660 self.schedule_drop_mem(arg_scope_id, llarg, arg_ty, None);
1662 datum::Datum::new(llarg,
1664 datum::Lvalue::new("FunctionContext::bind_args"))
1666 unpack_datum!(bcx, datum::lvalue_scratch_datum(bcx, arg_ty, "",
1668 arg_scope_id, |bcx, dst| {
1669 debug!("FunctionContext::bind_args: {:?}: {:?}", hir_arg, arg_ty);
1670 let b = &bcx.build();
1671 if common::type_is_fat_ptr(bcx.tcx(), arg_ty) {
1672 let meta = &self.fn_ty.args[idx];
1674 arg.store_fn_arg(b, &mut llarg_idx, expr::get_dataptr(bcx, dst));
1675 meta.store_fn_arg(b, &mut llarg_idx, expr::get_meta(bcx, dst));
1677 arg.store_fn_arg(b, &mut llarg_idx, dst);
1683 // FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1684 let tupled_arg_tys = match arg_ty.sty {
1685 ty::TyTuple(ref tys) => tys,
1686 _ => bug!("last argument of `rust-call` fn isn't a tuple?!")
1689 unpack_datum!(bcx, datum::lvalue_scratch_datum(bcx,
1695 debug!("FunctionContext::bind_args: tupled {:?}: {:?}", hir_arg, arg_ty);
1696 for (j, &tupled_arg_ty) in tupled_arg_tys.iter().enumerate() {
1697 let dst = StructGEP(bcx, llval, j);
1698 let arg = &self.fn_ty.args[idx];
1700 let b = &bcx.build();
1701 if common::type_is_fat_ptr(bcx.tcx(), tupled_arg_ty) {
1702 let meta = &self.fn_ty.args[idx];
1704 arg.store_fn_arg(b, &mut llarg_idx, expr::get_dataptr(bcx, dst));
1705 meta.store_fn_arg(b, &mut llarg_idx, expr::get_meta(bcx, dst));
1707 arg.store_fn_arg(b, &mut llarg_idx, dst);
1714 let pat = &hir_arg.pat;
1715 bcx = if let Some(name) = simple_name(pat) {
1716 // Generate nicer LLVM for the common case of fn a pattern
1718 set_value_name(arg_datum.val, &bcx.name(name));
1719 self.lllocals.borrow_mut().insert(pat.id, arg_datum);
1722 // General path. Copy out the values that are used in the
1724 _match::bind_irrefutable_pat(bcx, pat, arg_datum.match_input(), arg_scope_id)
1726 debuginfo::create_argument_metadata(bcx, hir_arg);
1732 /// Ties up the llstaticallocas -> llloadenv -> lltop edges,
1733 /// and builds the return block.
1734 pub fn finish(&'blk self, last_bcx: Block<'blk, 'tcx>,
1735 ret_debug_loc: DebugLoc) {
1736 let _icx = push_ctxt("FunctionContext::finish");
1738 let ret_cx = match self.llreturn.get() {
1740 if !last_bcx.terminated.get() {
1741 Br(last_bcx, llreturn, DebugLoc::None);
1743 raw_block(self, llreturn)
1748 self.build_return_block(ret_cx, ret_debug_loc);
1750 DebugLoc::None.apply(self);
1754 // Builds the return block for a function.
1755 pub fn build_return_block(&self, ret_cx: Block<'blk, 'tcx>,
1756 ret_debug_location: DebugLoc) {
1757 if self.llretslotptr.get().is_none() ||
1758 ret_cx.unreachable.get() ||
1759 (!self.needs_ret_allocas && self.fn_ty.ret.is_indirect()) {
1760 return RetVoid(ret_cx, ret_debug_location);
1763 let retslot = if self.needs_ret_allocas {
1764 Load(ret_cx, self.llretslotptr.get().unwrap())
1766 self.llretslotptr.get().unwrap()
1768 let retptr = Value(retslot);
1769 let llty = self.fn_ty.ret.original_ty;
1770 match (retptr.get_dominating_store(ret_cx), self.fn_ty.ret.cast) {
1771 // If there's only a single store to the ret slot, we can directly return
1772 // the value that was stored and omit the store and the alloca.
1773 // However, we only want to do this when there is no cast needed.
1774 (Some(s), None) => {
1775 let mut retval = s.get_operand(0).unwrap().get();
1776 s.erase_from_parent();
1778 if retptr.has_no_uses() {
1779 retptr.erase_from_parent();
1782 if self.fn_ty.ret.is_indirect() {
1783 Store(ret_cx, retval, get_param(self.llfn, 0));
1784 RetVoid(ret_cx, ret_debug_location)
1786 if llty == Type::i1(self.ccx) {
1787 retval = Trunc(ret_cx, retval, llty);
1789 Ret(ret_cx, retval, ret_debug_location)
1792 (_, cast_ty) if self.fn_ty.ret.is_indirect() => {
1793 // Otherwise, copy the return value to the ret slot.
1794 assert_eq!(cast_ty, None);
1795 let llsz = llsize_of(self.ccx, self.fn_ty.ret.ty);
1796 let llalign = llalign_of_min(self.ccx, self.fn_ty.ret.ty);
1797 call_memcpy(&B(ret_cx), get_param(self.llfn, 0),
1798 retslot, llsz, llalign as u32);
1799 RetVoid(ret_cx, ret_debug_location)
1801 (_, Some(cast_ty)) => {
1802 let load = Load(ret_cx, PointerCast(ret_cx, retslot, cast_ty.ptr_to()));
1803 let llalign = llalign_of_min(self.ccx, self.fn_ty.ret.ty);
1805 llvm::LLVMSetAlignment(load, llalign);
1807 Ret(ret_cx, load, ret_debug_location)
1810 let retval = if llty == Type::i1(self.ccx) {
1811 let val = LoadRangeAssert(ret_cx, retslot, 0, 2, llvm::False);
1812 Trunc(ret_cx, val, llty)
1814 Load(ret_cx, retslot)
1816 Ret(ret_cx, retval, ret_debug_location)
1822 /// Builds an LLVM function out of a source function.
1824 /// If the function closes over its environment a closure will be returned.
1825 pub fn trans_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1829 instance: Instance<'tcx>,
1830 inlined_id: ast::NodeId,
1831 sig: &ty::FnSig<'tcx>,
1833 closure_env: closure::ClosureEnv) {
1834 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1836 let _icx = push_ctxt("trans_closure");
1837 if !ccx.sess().no_landing_pads() {
1838 attributes::emit_uwtable(llfndecl, true);
1841 // this is an info! to allow collecting monomorphization statistics
1842 // and to allow finding the last function before LLVM aborts from
1844 info!("trans_closure(..., {})", instance);
1846 let fn_ty = FnType::new(ccx, abi, sig, &[]);
1848 let (arena, fcx): (TypedArena<_>, FunctionContext);
1849 arena = TypedArena::new();
1850 fcx = FunctionContext::new(ccx,
1853 Some((instance, sig, abi, inlined_id)),
1856 if fcx.mir.is_some() {
1857 return mir::trans_mir(&fcx);
1860 debuginfo::fill_scope_map_for_function(&fcx, decl, body, inlined_id);
1862 // cleanup scope for the incoming arguments
1863 let fn_cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(
1864 ccx, inlined_id, body.span, true);
1865 let arg_scope = fcx.push_custom_cleanup_scope_with_debug_loc(fn_cleanup_debug_loc);
1867 // Set up arguments to the function.
1868 debug!("trans_closure: function: {:?}", Value(fcx.llfn));
1869 let bcx = fcx.bind_args(&decl.inputs, abi, inlined_id, closure_env, arg_scope);
1871 // Up until here, IR instructions for this function have explicitly not been annotated with
1872 // source code location, so we don't step into call setup code. From here on, source location
1873 // emitting should be enabled.
1874 debuginfo::start_emitting_source_locations(&fcx);
1876 let dest = if fcx.fn_ty.ret.is_ignore() {
1879 expr::SaveIn(fcx.get_ret_slot(bcx, "iret_slot"))
1882 // This call to trans_block is the place where we bridge between
1883 // translation calls that don't have a return value (trans_crate,
1884 // trans_mod, trans_item, et cetera) and those that do
1885 // (trans_block, trans_expr, et cetera).
1886 let mut bcx = controlflow::trans_block(bcx, body, dest);
1889 expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1890 Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1895 match fcx.llreturn.get() {
1897 Br(bcx, fcx.return_exit_block(), DebugLoc::None);
1898 fcx.pop_custom_cleanup_scope(arg_scope);
1901 // Microoptimization writ large: avoid creating a separate
1902 // llreturn basic block
1903 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1907 // Put return block after all other blocks.
1908 // This somewhat improves single-stepping experience in debugger.
1910 let llreturn = fcx.llreturn.get();
1911 if let Some(llreturn) = llreturn {
1912 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1916 // Insert the mandatory first few basic blocks before lltop.
1917 fcx.finish(bcx, fn_cleanup_debug_loc.debug_loc());
1920 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
1921 let local_instance = inline::maybe_inline_instance(ccx, instance);
1923 let fn_node_id = ccx.tcx().map.as_local_node_id(local_instance.def).unwrap();
1925 let _s = StatRecorder::new(ccx, ccx.tcx().node_path_str(fn_node_id));
1926 debug!("trans_instance(instance={:?})", instance);
1927 let _icx = push_ctxt("trans_instance");
1929 let item = ccx.tcx().map.find(fn_node_id).unwrap();
1931 let fn_ty = ccx.tcx().lookup_item_type(instance.def).ty;
1932 let fn_ty = ccx.tcx().erase_regions(&fn_ty);
1933 let fn_ty = monomorphize::apply_param_substs(ccx.tcx(), instance.substs, &fn_ty);
1935 let sig = ccx.tcx().erase_late_bound_regions(fn_ty.fn_sig());
1936 let sig = ccx.tcx().normalize_associated_type(&sig);
1937 let abi = fn_ty.fn_abi();
1939 let lldecl = match ccx.instances().borrow().get(&local_instance) {
1941 None => bug!("Instance `{:?}` not already declared", instance)
1945 hir_map::NodeItem(&hir::Item {
1946 node: hir::ItemFn(ref decl, _, _, _, _, ref body), ..
1948 hir_map::NodeTraitItem(&hir::TraitItem {
1949 node: hir::MethodTraitItem(
1950 hir::MethodSig { ref decl, .. }, Some(ref body)), ..
1952 hir_map::NodeImplItem(&hir::ImplItem {
1953 node: hir::ImplItemKind::Method(
1954 hir::MethodSig { ref decl, .. }, ref body), ..
1956 trans_closure(ccx, decl, body, lldecl, instance,
1957 fn_node_id, &sig, abi, closure::ClosureEnv::NotClosure);
1959 _ => bug!("Instance is a {:?}?", item)
1963 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1968 debug_loc: DebugLoc)
1969 -> Result<'blk, 'tcx> {
1971 let ccx = bcx.fcx.ccx;
1973 let sig = ccx.tcx().erase_late_bound_regions(&ctor_ty.fn_sig());
1974 let sig = ccx.tcx().normalize_associated_type(&sig);
1975 let result_ty = sig.output;
1977 // Get location to store the result. If the user does not care about
1978 // the result, just make a stack slot
1979 let llresult = match dest {
1980 expr::SaveIn(d) => d,
1982 if !type_is_zero_size(ccx, result_ty) {
1983 let llresult = alloc_ty(bcx, result_ty, "constructor_result");
1984 call_lifetime_start(bcx, llresult);
1987 C_undef(type_of::type_of(ccx, result_ty).ptr_to())
1992 if !type_is_zero_size(ccx, result_ty) {
1994 ArgExprs(exprs) => {
1995 let fields = exprs.iter().map(|x| &**x).enumerate().collect::<Vec<_>>();
1996 bcx = expr::trans_adt(bcx,
2001 expr::SaveIn(llresult),
2004 _ => bug!("expected expr as arguments for variant/struct tuple constructor"),
2007 // Just eval all the expressions (if any). Since expressions in Rust can have arbitrary
2008 // contents, there could be side-effects we need from them.
2010 ArgExprs(exprs) => {
2012 bcx = expr::trans_into(bcx, expr, expr::Ignore);
2019 // If the caller doesn't care about the result
2020 // drop the temporary we made
2021 let bcx = match dest {
2022 expr::SaveIn(_) => bcx,
2024 let bcx = glue::drop_ty(bcx, llresult, result_ty, debug_loc);
2025 if !type_is_zero_size(ccx, result_ty) {
2026 call_lifetime_end(bcx, llresult);
2032 Result::new(bcx, llresult)
2035 pub fn trans_ctor_shim<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2036 ctor_id: ast::NodeId,
2038 param_substs: &'tcx Substs<'tcx>,
2039 llfndecl: ValueRef) {
2040 let ctor_ty = ccx.tcx().node_id_to_type(ctor_id);
2041 let ctor_ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &ctor_ty);
2043 let sig = ccx.tcx().erase_late_bound_regions(&ctor_ty.fn_sig());
2044 let sig = ccx.tcx().normalize_associated_type(&sig);
2045 let fn_ty = FnType::new(ccx, Abi::Rust, &sig, &[]);
2047 let (arena, fcx): (TypedArena<_>, FunctionContext);
2048 arena = TypedArena::new();
2049 fcx = FunctionContext::new(ccx, llfndecl, fn_ty, None, &arena);
2050 let bcx = fcx.init(false, None);
2052 assert!(!fcx.needs_ret_allocas);
2054 if !fcx.fn_ty.ret.is_ignore() {
2055 let dest = fcx.get_ret_slot(bcx, "eret_slot");
2056 let dest_val = adt::MaybeSizedValue::sized(dest); // Can return unsized value
2057 let repr = adt::represent_type(ccx, sig.output);
2058 let mut llarg_idx = fcx.fn_ty.ret.is_indirect() as usize;
2059 let mut arg_idx = 0;
2060 for (i, arg_ty) in sig.inputs.into_iter().enumerate() {
2061 let lldestptr = adt::trans_field_ptr(bcx, &repr, dest_val, Disr::from(disr), i);
2062 let arg = &fcx.fn_ty.args[arg_idx];
2064 let b = &bcx.build();
2065 if common::type_is_fat_ptr(bcx.tcx(), arg_ty) {
2066 let meta = &fcx.fn_ty.args[arg_idx];
2068 arg.store_fn_arg(b, &mut llarg_idx, expr::get_dataptr(bcx, lldestptr));
2069 meta.store_fn_arg(b, &mut llarg_idx, expr::get_meta(bcx, lldestptr));
2071 arg.store_fn_arg(b, &mut llarg_idx, lldestptr);
2074 adt::trans_set_discr(bcx, &repr, dest, disr);
2077 fcx.finish(bcx, DebugLoc::None);
2080 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
2081 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2082 // applicable to variable declarations and may not really make sense for
2083 // Rust code in the first place but whitelist them anyway and trust that
2084 // the user knows what s/he's doing. Who knows, unanticipated use cases
2085 // may pop up in the future.
2087 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2088 // and don't have to be, LLVM treats them as no-ops.
2090 "appending" => Some(llvm::AppendingLinkage),
2091 "available_externally" => Some(llvm::AvailableExternallyLinkage),
2092 "common" => Some(llvm::CommonLinkage),
2093 "extern_weak" => Some(llvm::ExternalWeakLinkage),
2094 "external" => Some(llvm::ExternalLinkage),
2095 "internal" => Some(llvm::InternalLinkage),
2096 "linkonce" => Some(llvm::LinkOnceAnyLinkage),
2097 "linkonce_odr" => Some(llvm::LinkOnceODRLinkage),
2098 "private" => Some(llvm::PrivateLinkage),
2099 "weak" => Some(llvm::WeakAnyLinkage),
2100 "weak_odr" => Some(llvm::WeakODRLinkage),
2105 pub fn set_link_section(ccx: &CrateContext,
2107 attrs: &[ast::Attribute]) {
2108 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
2109 if contains_null(§) {
2110 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
2113 let buf = CString::new(sect.as_bytes()).unwrap();
2114 llvm::LLVMSetSection(llval, buf.as_ptr());
2119 /// Create the `main` function which will initialise the rust runtime and call
2120 /// users’ main function.
2121 pub fn maybe_create_entry_wrapper(ccx: &CrateContext) {
2122 let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
2123 Some((id, span)) => {
2124 (ccx.tcx().map.local_def_id(id), span)
2129 // check for the #[rustc_error] annotation, which forces an
2130 // error in trans. This is used to write compile-fail tests
2131 // that actually test that compilation succeeds without
2132 // reporting an error.
2133 if ccx.tcx().has_attr(main_def_id, "rustc_error") {
2134 ccx.tcx().sess.span_fatal(span, "compilation successful");
2137 let instance = Instance::mono(ccx.shared(), main_def_id);
2139 if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
2140 // We want to create the wrapper in the same codegen unit as Rust's main
2145 let main_llfn = Callee::def(ccx, main_def_id, instance.substs).reify(ccx).val;
2147 let et = ccx.sess().entry_type.get().unwrap();
2149 config::EntryMain => {
2150 create_entry_fn(ccx, span, main_llfn, true);
2152 config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
2153 config::EntryNone => {} // Do nothing.
2156 fn create_entry_fn(ccx: &CrateContext,
2158 rust_main: ValueRef,
2159 use_start_lang_item: bool) {
2160 let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
2162 if declare::get_defined_value(ccx, "main").is_some() {
2163 // FIXME: We should be smart and show a better diagnostic here.
2164 ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
2165 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
2167 ccx.sess().abort_if_errors();
2170 let llfn = declare::declare_cfn(ccx, "main", llfty);
2173 llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn, "top\0".as_ptr() as *const _)
2175 let bld = ccx.raw_builder();
2177 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2179 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx);
2181 let (start_fn, args) = if use_start_lang_item {
2182 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2184 Err(s) => ccx.sess().fatal(&s)
2186 let empty_substs = ccx.tcx().mk_substs(Substs::empty());
2187 let start_fn = Callee::def(ccx, start_def_id, empty_substs).reify(ccx).val;
2189 let opaque_rust_main =
2190 llvm::LLVMBuildPointerCast(bld,
2192 Type::i8p(ccx).to_ref(),
2193 "rust_main\0".as_ptr() as *const _);
2195 vec![opaque_rust_main, get_param(llfn, 0), get_param(llfn, 1)]
2199 debug!("using user-defined start fn");
2200 let args = vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)];
2205 let result = llvm::LLVMRustBuildCall(bld,
2208 args.len() as c_uint,
2212 llvm::LLVMBuildRet(bld, result);
2217 fn contains_null(s: &str) -> bool {
2218 s.bytes().any(|b| b == 0)
2221 fn write_metadata(cx: &SharedCrateContext,
2222 reachable_ids: &NodeSet) -> Vec<u8> {
2225 let any_library = cx.sess()
2229 .any(|ty| *ty != config::CrateTypeExecutable);
2234 let cstore = &cx.tcx().sess.cstore;
2235 let metadata = cstore.encode_metadata(cx.tcx(),
2240 cx.tcx().map.krate());
2241 let mut compressed = cstore.metadata_encoding_version().to_vec();
2242 compressed.extend_from_slice(&flate::deflate_bytes(&metadata));
2244 let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
2245 let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
2246 let name = cx.metadata_symbol_name();
2247 let buf = CString::new(name).unwrap();
2248 let llglobal = unsafe {
2249 llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf.as_ptr())
2252 llvm::LLVMSetInitializer(llglobal, llconst);
2254 cx.tcx().sess.cstore.metadata_section_name(&cx.sess().target.target);
2255 let name = CString::new(section_name).unwrap();
2256 llvm::LLVMSetSection(llglobal, name.as_ptr());
2258 // Also generate a .section directive to force no
2259 // flags, at least for ELF outputs, so that the
2260 // metadata doesn't get loaded into memory.
2261 let directive = format!(".section {}", section_name);
2262 let directive = CString::new(directive).unwrap();
2263 llvm::LLVMSetModuleInlineAsm(cx.metadata_llmod(), directive.as_ptr())
2268 /// Find any symbols that are defined in one compilation unit, but not declared
2269 /// in any other compilation unit. Give these symbols internal linkage.
2270 fn internalize_symbols<'a, 'tcx>(sess: &Session,
2271 ccxs: &CrateContextList<'a, 'tcx>,
2272 symbol_map: &SymbolMap<'tcx>,
2273 reachable: &FnvHashSet<&str>) {
2274 let scx = ccxs.shared();
2275 let tcx = scx.tcx();
2277 // In incr. comp. mode, we can't necessarily see all refs since we
2278 // don't generate LLVM IR for reused modules, so skip this
2279 // step. Later we should get smarter.
2280 if sess.opts.debugging_opts.incremental.is_some() {
2284 // 'unsafe' because we are holding on to CStr's from the LLVM module within
2287 let mut referenced_somewhere = FnvHashSet();
2289 // Collect all symbols that need to stay externally visible because they
2290 // are referenced via a declaration in some other codegen unit.
2291 for ccx in ccxs.iter_need_trans() {
2292 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2293 let linkage = llvm::LLVMGetLinkage(val);
2294 // We only care about external declarations (not definitions)
2295 // and available_externally definitions.
2296 let is_available_externally = linkage == llvm::AvailableExternallyLinkage as c_uint;
2297 let is_decl = llvm::LLVMIsDeclaration(val) != 0;
2299 if is_decl || is_available_externally {
2300 let symbol_name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2301 referenced_somewhere.insert(symbol_name);
2306 // Also collect all symbols for which we cannot adjust linkage, because
2307 // it is fixed by some directive in the source code (e.g. #[no_mangle]).
2308 let linkage_fixed_explicitly: FnvHashSet<_> = scx
2309 .translation_items()
2313 .filter(|trans_item|{
2314 let def_id = match *trans_item {
2315 TransItem::DropGlue(..) => {
2318 TransItem::Fn(ref instance) => {
2321 TransItem::Static(node_id) => {
2322 tcx.map.local_def_id(node_id)
2326 trans_item.explicit_linkage(tcx).is_some() ||
2327 attr::contains_extern_indicator(tcx.sess.diagnostic(),
2328 &tcx.get_attrs(def_id))
2330 .map(|trans_item| symbol_map.get_or_compute(scx, trans_item))
2333 // Examine each external definition. If the definition is not used in
2334 // any other compilation unit, and is not reachable from other crates,
2335 // then give it internal linkage.
2336 for ccx in ccxs.iter_need_trans() {
2337 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2338 let linkage = llvm::LLVMGetLinkage(val);
2340 let is_externally_visible = (linkage == llvm::ExternalLinkage as c_uint) ||
2341 (linkage == llvm::LinkOnceODRLinkage as c_uint) ||
2342 (linkage == llvm::WeakODRLinkage as c_uint);
2343 let is_definition = llvm::LLVMIsDeclaration(val) == 0;
2345 // If this is a definition (as opposed to just a declaration)
2346 // and externally visible, check if we can internalize it
2347 if is_definition && is_externally_visible {
2348 let name_cstr = CStr::from_ptr(llvm::LLVMGetValueName(val));
2349 let name_str = name_cstr.to_str().unwrap();
2350 let name_cow = Cow::Borrowed(name_str);
2352 let is_referenced_somewhere = referenced_somewhere.contains(&name_cstr);
2353 let is_reachable = reachable.contains(&name_str);
2354 let has_fixed_linkage = linkage_fixed_explicitly.contains(&name_cow);
2356 if !is_referenced_somewhere && !is_reachable && !has_fixed_linkage {
2357 llvm::LLVMSetLinkage(val, llvm::InternalLinkage);
2358 llvm::LLVMSetDLLStorageClass(val,
2359 llvm::DLLStorageClass::Default);
2360 llvm::UnsetComdat(val);
2368 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2369 // This is required to satisfy `dllimport` references to static data in .rlibs
2370 // when using MSVC linker. We do this only for data, as linker can fix up
2371 // code references on its own.
2372 // See #26591, #27438
2373 fn create_imps(cx: &CrateContextList) {
2374 // The x86 ABI seems to require that leading underscores are added to symbol
2375 // names, so we need an extra underscore on 32-bit. There's also a leading
2376 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2377 // underscores added in front).
2378 let prefix = if cx.shared().sess().target.target.target_pointer_width == "32" {
2384 for ccx in cx.iter_need_trans() {
2385 let exported: Vec<_> = iter_globals(ccx.llmod())
2387 llvm::LLVMGetLinkage(val) ==
2388 llvm::ExternalLinkage as c_uint &&
2389 llvm::LLVMIsDeclaration(val) == 0
2393 let i8p_ty = Type::i8p(&ccx);
2394 for val in exported {
2395 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2396 let mut imp_name = prefix.as_bytes().to_vec();
2397 imp_name.extend(name.to_bytes());
2398 let imp_name = CString::new(imp_name).unwrap();
2399 let imp = llvm::LLVMAddGlobal(ccx.llmod(),
2401 imp_name.as_ptr() as *const _);
2402 let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
2403 llvm::LLVMSetInitializer(imp, init);
2404 llvm::LLVMSetLinkage(imp, llvm::ExternalLinkage);
2412 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
2415 impl Iterator for ValueIter {
2416 type Item = ValueRef;
2418 fn next(&mut self) -> Option<ValueRef> {
2421 self.cur = unsafe { (self.step)(old) };
2429 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
2432 cur: llvm::LLVMGetFirstGlobal(llmod),
2433 step: llvm::LLVMGetNextGlobal,
2438 fn iter_functions(llmod: llvm::ModuleRef) -> ValueIter {
2441 cur: llvm::LLVMGetFirstFunction(llmod),
2442 step: llvm::LLVMGetNextFunction,
2447 /// The context provided lists a set of reachable ids as calculated by
2448 /// middle::reachable, but this contains far more ids and symbols than we're
2449 /// actually exposing from the object file. This function will filter the set in
2450 /// the context to the set of ids which correspond to symbols that are exposed
2451 /// from the object file being generated.
2453 /// This list is later used by linkers to determine the set of symbols needed to
2454 /// be exposed from a dynamic library and it's also encoded into the metadata.
2455 pub fn filter_reachable_ids(tcx: TyCtxt, reachable: NodeSet) -> NodeSet {
2456 reachable.into_iter().filter(|&id| {
2457 // Next, we want to ignore some FFI functions that are not exposed from
2458 // this crate. Reachable FFI functions can be lumped into two
2461 // 1. Those that are included statically via a static library
2462 // 2. Those included otherwise (e.g. dynamically or via a framework)
2464 // Although our LLVM module is not literally emitting code for the
2465 // statically included symbols, it's an export of our library which
2466 // needs to be passed on to the linker and encoded in the metadata.
2468 // As a result, if this id is an FFI item (foreign item) then we only
2469 // let it through if it's included statically.
2470 match tcx.map.get(id) {
2471 hir_map::NodeForeignItem(..) => {
2472 tcx.sess.cstore.is_statically_included_foreign_item(id)
2475 // Only consider nodes that actually have exported symbols.
2476 hir_map::NodeItem(&hir::Item {
2477 node: hir::ItemStatic(..), .. }) |
2478 hir_map::NodeItem(&hir::Item {
2479 node: hir::ItemFn(..), .. }) |
2480 hir_map::NodeImplItem(&hir::ImplItem {
2481 node: hir::ImplItemKind::Method(..), .. }) => {
2482 let def_id = tcx.map.local_def_id(id);
2483 let scheme = tcx.lookup_item_type(def_id);
2484 scheme.generics.types.is_empty()
2492 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
2493 mir_map: &MirMap<'tcx>,
2494 analysis: ty::CrateAnalysis)
2495 -> CrateTranslation {
2496 let _task = tcx.dep_graph.in_task(DepNode::TransCrate);
2498 // Be careful with this krate: obviously it gives access to the
2499 // entire contents of the krate. So if you push any subtasks of
2500 // `TransCrate`, you need to be careful to register "reads" of the
2501 // particular items that will be processed.
2502 let krate = tcx.map.krate();
2504 let ty::CrateAnalysis { export_map, reachable, name, .. } = analysis;
2505 let reachable = filter_reachable_ids(tcx, reachable);
2507 let check_overflow = if let Some(v) = tcx.sess.opts.debugging_opts.force_overflow_checks {
2510 tcx.sess.opts.debug_assertions
2513 let check_dropflag = if let Some(v) = tcx.sess.opts.debugging_opts.force_dropflag_checks {
2516 tcx.sess.opts.debug_assertions
2519 let link_meta = link::build_link_meta(tcx, name);
2521 let shared_ccx = SharedCrateContext::new(tcx,
2529 // Translate the metadata.
2530 let metadata = time(tcx.sess.time_passes(), "write metadata", || {
2531 write_metadata(&shared_ccx, shared_ccx.reachable())
2534 let metadata_module = ModuleTranslation {
2535 name: "metadata".to_string(),
2536 symbol_name_hash: 0, // we always rebuild metadata, at least for now
2537 source: ModuleSource::Translated(ModuleLlvm {
2538 llcx: shared_ccx.metadata_llcx(),
2539 llmod: shared_ccx.metadata_llmod(),
2542 let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
2544 // Run the translation item collector and partition the collected items into
2546 let (codegen_units, symbol_map) = collect_and_partition_translation_items(&shared_ccx);
2548 let symbol_map = Rc::new(symbol_map);
2550 let previous_work_products = trans_reuse_previous_work_products(tcx,
2554 let crate_context_list = CrateContextList::new(&shared_ccx,
2556 previous_work_products,
2557 symbol_map.clone());
2558 let modules: Vec<_> = crate_context_list.iter_all()
2560 let source = match ccx.previous_work_product() {
2561 Some(buf) => ModuleSource::Preexisting(buf.clone()),
2562 None => ModuleSource::Translated(ModuleLlvm {
2569 name: String::from(ccx.codegen_unit().name()),
2570 symbol_name_hash: ccx.codegen_unit().compute_symbol_name_hash(tcx, &symbol_map),
2576 assert_module_sources::assert_module_sources(tcx, &modules);
2578 // Skip crate items and just output metadata in -Z no-trans mode.
2579 if tcx.sess.opts.debugging_opts.no_trans {
2580 let linker_info = LinkerInfo::new(&shared_ccx, &[]);
2581 return CrateTranslation {
2583 metadata_module: metadata_module,
2587 no_builtins: no_builtins,
2588 linker_info: linker_info
2592 // Instantiate translation items without filling out definitions yet...
2593 for ccx in crate_context_list.iter_need_trans() {
2594 let cgu = ccx.codegen_unit();
2595 let trans_items = cgu.items_in_deterministic_order(tcx, &symbol_map);
2597 tcx.dep_graph.with_task(cgu.work_product_dep_node(), || {
2598 for (trans_item, linkage) in trans_items {
2599 trans_item.predefine(&ccx, linkage);
2604 // ... and now that we have everything pre-defined, fill out those definitions.
2605 for ccx in crate_context_list.iter_need_trans() {
2606 let cgu = ccx.codegen_unit();
2607 let trans_items = cgu.items_in_deterministic_order(tcx, &symbol_map);
2608 tcx.dep_graph.with_task(cgu.work_product_dep_node(), || {
2609 for (trans_item, _) in trans_items {
2610 trans_item.define(&ccx);
2613 // If this codegen unit contains the main function, also create the
2615 maybe_create_entry_wrapper(&ccx);
2617 // Run replace-all-uses-with for statics that need it
2618 for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
2620 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
2621 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
2622 llvm::LLVMDeleteGlobal(old_g);
2626 // Finalize debuginfo
2627 if ccx.sess().opts.debuginfo != NoDebugInfo {
2628 debuginfo::finalize(&ccx);
2633 symbol_names_test::report_symbol_names(&shared_ccx);
2635 if shared_ccx.sess().trans_stats() {
2636 let stats = shared_ccx.stats();
2637 println!("--- trans stats ---");
2638 println!("n_glues_created: {}", stats.n_glues_created.get());
2639 println!("n_null_glues: {}", stats.n_null_glues.get());
2640 println!("n_real_glues: {}", stats.n_real_glues.get());
2642 println!("n_fallback_instantiations: {}", stats.n_fallback_instantiations.get());
2644 println!("n_fns: {}", stats.n_fns.get());
2645 println!("n_monos: {}", stats.n_monos.get());
2646 println!("n_inlines: {}", stats.n_inlines.get());
2647 println!("n_closures: {}", stats.n_closures.get());
2648 println!("fn stats:");
2649 stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
2650 insns_b.cmp(&insns_a)
2652 for tuple in stats.fn_stats.borrow().iter() {
2654 (ref name, insns) => {
2655 println!("{} insns, {}", insns, *name);
2661 if shared_ccx.sess().count_llvm_insns() {
2662 for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
2663 println!("{:7} {}", *v, *k);
2667 let sess = shared_ccx.sess();
2668 let mut reachable_symbols = shared_ccx.reachable().iter().map(|&id| {
2669 let def_id = shared_ccx.tcx().map.local_def_id(id);
2670 symbol_for_def_id(def_id, &shared_ccx, &symbol_map)
2671 }).collect::<Vec<_>>();
2673 if sess.entry_fn.borrow().is_some() {
2674 reachable_symbols.push("main".to_string());
2677 if sess.crate_types.borrow().contains(&config::CrateTypeDylib) {
2678 reachable_symbols.push(shared_ccx.metadata_symbol_name());
2681 // For the purposes of LTO or when creating a cdylib, we add to the
2682 // reachable set all of the upstream reachable extern fns. These functions
2683 // are all part of the public ABI of the final product, so we need to
2686 // Note that this happens even if LTO isn't requested or we're not creating
2687 // a cdylib. In those cases, though, we're not even reading the
2688 // `reachable_symbols` list later on so it should be ok.
2689 for cnum in sess.cstore.crates() {
2690 let syms = sess.cstore.reachable_ids(cnum);
2691 reachable_symbols.extend(syms.into_iter().filter(|did| {
2692 sess.cstore.is_extern_item(shared_ccx.tcx(), *did)
2694 symbol_for_def_id(did, &shared_ccx, &symbol_map)
2698 time(shared_ccx.sess().time_passes(), "internalize symbols", || {
2699 internalize_symbols(sess,
2700 &crate_context_list,
2702 &reachable_symbols.iter()
2707 if sess.target.target.options.is_like_msvc &&
2708 sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
2709 create_imps(&crate_context_list);
2712 let linker_info = LinkerInfo::new(&shared_ccx, &reachable_symbols);
2716 metadata_module: metadata_module,
2719 reachable: reachable_symbols,
2720 no_builtins: no_builtins,
2721 linker_info: linker_info
2725 /// For each CGU, identify if we can reuse an existing object file (or
2726 /// maybe other context).
2727 fn trans_reuse_previous_work_products(tcx: TyCtxt,
2728 codegen_units: &[CodegenUnit],
2729 symbol_map: &SymbolMap)
2730 -> Vec<Option<WorkProduct>> {
2731 debug!("trans_reuse_previous_work_products()");
2735 let id = cgu.work_product_id();
2737 let hash = cgu.compute_symbol_name_hash(tcx, symbol_map);
2739 debug!("trans_reuse_previous_work_products: id={:?} hash={}", id, hash);
2741 if let Some(work_product) = tcx.dep_graph.previous_work_product(&id) {
2742 if work_product.input_hash == hash {
2743 debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
2744 return Some(work_product);
2746 debug!("trans_reuse_previous_work_products: \
2747 not reusing {:?} because hash changed to {:?}",
2748 work_product, hash);
2757 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>)
2758 -> (Vec<CodegenUnit<'tcx>>, SymbolMap<'tcx>) {
2759 let time_passes = scx.sess().time_passes();
2761 let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
2763 let mode_string = s.to_lowercase();
2764 let mode_string = mode_string.trim();
2765 if mode_string == "eager" {
2766 TransItemCollectionMode::Eager
2768 if mode_string != "lazy" {
2769 let message = format!("Unknown codegen-item collection mode '{}'. \
2770 Falling back to 'lazy' mode.",
2772 scx.sess().warn(&message);
2775 TransItemCollectionMode::Lazy
2778 None => TransItemCollectionMode::Lazy
2781 let (items, inlining_map) =
2782 time(time_passes, "translation item collection", || {
2783 collector::collect_crate_translation_items(&scx, collection_mode)
2786 let symbol_map = SymbolMap::build(scx, items.iter().cloned());
2788 let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
2789 PartitioningStrategy::PerModule
2791 PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
2794 let codegen_units = time(time_passes, "codegen unit partitioning", || {
2795 partitioning::partition(scx.tcx(),
2796 items.iter().cloned(),
2802 assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
2803 scx.tcx().sess.opts.debugging_opts.incremental.is_some());
2806 let mut ccx_map = scx.translation_items().borrow_mut();
2808 for trans_item in items.iter().cloned() {
2809 ccx_map.insert(trans_item);
2813 if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
2814 let mut item_to_cgus = HashMap::new();
2816 for cgu in &codegen_units {
2817 for (&trans_item, &linkage) in cgu.items() {
2818 item_to_cgus.entry(trans_item)
2819 .or_insert(Vec::new())
2820 .push((cgu.name().clone(), linkage));
2824 let mut item_keys: Vec<_> = items
2827 let mut output = i.to_string(scx.tcx());
2828 output.push_str(" @@");
2829 let mut empty = Vec::new();
2830 let mut cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
2831 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
2833 for &(ref cgu_name, linkage) in cgus.iter() {
2834 output.push_str(" ");
2835 output.push_str(&cgu_name[..]);
2837 let linkage_abbrev = match linkage {
2838 llvm::ExternalLinkage => "External",
2839 llvm::AvailableExternallyLinkage => "Available",
2840 llvm::LinkOnceAnyLinkage => "OnceAny",
2841 llvm::LinkOnceODRLinkage => "OnceODR",
2842 llvm::WeakAnyLinkage => "WeakAny",
2843 llvm::WeakODRLinkage => "WeakODR",
2844 llvm::AppendingLinkage => "Appending",
2845 llvm::InternalLinkage => "Internal",
2846 llvm::PrivateLinkage => "Private",
2847 llvm::ExternalWeakLinkage => "ExternalWeak",
2848 llvm::CommonLinkage => "Common",
2851 output.push_str("[");
2852 output.push_str(linkage_abbrev);
2853 output.push_str("]");
2861 for item in item_keys {
2862 println!("TRANS_ITEM {}", item);
2866 (codegen_units, symbol_map)
2869 fn symbol_for_def_id<'a, 'tcx>(def_id: DefId,
2870 scx: &SharedCrateContext<'a, 'tcx>,
2871 symbol_map: &SymbolMap<'tcx>)
2873 // Just try to look things up in the symbol map. If nothing's there, we
2875 if let Some(node_id) = scx.tcx().map.as_local_node_id(def_id) {
2876 if let Some(sym) = symbol_map.get(TransItem::Static(node_id)) {
2877 return sym.to_owned();
2881 let instance = Instance::mono(scx, def_id);
2883 symbol_map.get(TransItem::Fn(instance))
2885 .unwrap_or_else(|| instance.symbol_name(scx))