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.
10 //! Translate the completed AST to the LLVM IR.
12 //! Some functions here, such as trans_block and trans_expr, return a value --
13 //! the result of the translation to LLVM -- while others, such as trans_fn,
14 //! trans_impl, and trans_item, are called only for the side effect of adding a
15 //! particular definition to the LLVM IR output we're producing.
17 //! Hopefully useful general knowledge about trans:
19 //! * There's no way to find out the Ty type of a ValueRef. Doing so
20 //! would be "trying to get the eggs out of an omelette" (credit:
21 //! pcwalton). You can, instead, find out its TypeRef by calling val_ty,
22 //! but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
23 //! int) and rec(x=int, y=int, z=int) will have the same TypeRef.
25 #![allow(non_camel_case_types)]
27 pub use self::ValueOrigin::*;
29 use super::CrateTranslation;
30 use super::ModuleTranslation;
32 use back::link::mangle_exported_name;
33 use back::{link, abi};
35 use llvm::{BasicBlockRef, Linkage, ValueRef, Vector, get_param};
37 use metadata::{csearch, encoder, loader};
38 use middle::astencode;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::weak_lang_items;
42 use middle::subst::Substs;
43 use middle::ty::{self, Ty, ClosureTyper, type_is_simd, simd_size};
44 use session::config::{self, NoDebugInfo};
48 use trans::attributes;
50 use trans::builder::{Builder, noname};
52 use trans::cleanup::CleanupMethods;
55 use trans::common::{Block, C_bool, C_bytes_in_context, C_i32, C_int, C_integral};
56 use trans::common::{C_null, C_struct_in_context, C_u64, C_u8, C_undef};
57 use trans::common::{CrateContext, FunctionContext};
58 use trans::common::{Result, NodeIdAndSpan};
59 use trans::common::{node_id_type, return_type_is_void};
60 use trans::common::{type_is_immediate, type_is_zero_size, val_ty};
63 use trans::context::SharedCrateContext;
64 use trans::controlflow;
66 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
73 use trans::machine::{llsize_of, llsize_of_real};
75 use trans::monomorphize;
77 use trans::type_::Type;
79 use trans::type_of::*;
80 use trans::value::Value;
81 use util::common::indenter;
82 use util::ppaux::{Repr, ty_to_string};
83 use util::sha2::Sha256;
84 use util::nodemap::NodeMap;
86 use arena::TypedArena;
88 use std::ffi::{CStr, CString};
89 use std::cell::{Cell, RefCell};
90 use std::collections::HashSet;
93 use std::{i8, i16, i32, i64};
94 use syntax::abi::{Rust, RustCall, RustIntrinsic, Abi};
95 use syntax::ast_util::local_def;
96 use syntax::attr::AttrMetaMethods;
98 use syntax::codemap::Span;
99 use syntax::parse::token::InternedString;
100 use syntax::visit::Visitor;
102 use syntax::{ast, ast_util, ast_map};
105 static TASK_LOCAL_INSN_KEY: RefCell<Option<Vec<&'static str>>> = {
110 pub fn with_insn_ctxt<F>(blk: F) where
111 F: FnOnce(&[&'static str]),
113 TASK_LOCAL_INSN_KEY.with(move |slot| {
114 slot.borrow().as_ref().map(move |s| blk(s));
118 pub fn init_insn_ctxt() {
119 TASK_LOCAL_INSN_KEY.with(|slot| {
120 *slot.borrow_mut() = Some(Vec::new());
124 pub struct _InsnCtxt {
125 _cannot_construct_outside_of_this_module: ()
128 impl Drop for _InsnCtxt {
130 TASK_LOCAL_INSN_KEY.with(|slot| {
131 match slot.borrow_mut().as_mut() {
132 Some(ctx) => { ctx.pop(); }
139 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
140 debug!("new InsnCtxt: {}", s);
141 TASK_LOCAL_INSN_KEY.with(|slot| {
142 match slot.borrow_mut().as_mut() {
143 Some(ctx) => ctx.push(s),
147 _InsnCtxt { _cannot_construct_outside_of_this_module: () }
150 pub struct StatRecorder<'a, 'tcx: 'a> {
151 ccx: &'a CrateContext<'a, 'tcx>,
152 name: Option<String>,
156 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
157 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String)
158 -> StatRecorder<'a, 'tcx> {
159 let istart = ccx.stats().n_llvm_insns.get();
168 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
170 if self.ccx.sess().trans_stats() {
171 let iend = self.ccx.stats().n_llvm_insns.get();
172 self.ccx.stats().fn_stats.borrow_mut().push((self.name.take().unwrap(),
173 iend - self.istart));
174 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
175 // Reset LLVM insn count to avoid compound costs.
176 self.ccx.stats().n_llvm_insns.set(self.istart);
181 fn get_extern_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty: Ty<'tcx>,
182 name: &str, did: ast::DefId) -> ValueRef {
183 match ccx.externs().borrow().get(name) {
184 Some(n) => return *n,
188 let f = declare::declare_rust_fn(ccx, name, fn_ty);
190 let attrs = csearch::get_item_attrs(&ccx.sess().cstore, did);
191 attributes::from_fn_attrs(ccx, &attrs[..], f);
193 ccx.externs().borrow_mut().insert(name.to_string(), f);
197 pub fn self_type_for_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
198 closure_id: ast::DefId,
202 let closure_kind = ccx.tcx().closure_kind(closure_id);
204 ty::FnClosureKind => {
205 ty::mk_imm_rptr(ccx.tcx(), ccx.tcx().mk_region(ty::ReStatic), fn_ty)
207 ty::FnMutClosureKind => {
208 ty::mk_mut_rptr(ccx.tcx(), ccx.tcx().mk_region(ty::ReStatic), fn_ty)
210 ty::FnOnceClosureKind => fn_ty
214 pub fn kind_for_closure(ccx: &CrateContext, closure_id: ast::DefId) -> ty::ClosureKind {
215 *ccx.tcx().closure_kinds.borrow().get(&closure_id).unwrap()
218 pub fn get_extern_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId,
219 t: Ty<'tcx>) -> ValueRef {
220 let name = csearch::get_symbol(&ccx.sess().cstore, did);
221 let ty = type_of(ccx, t);
222 match ccx.externs().borrow_mut().get(&name) {
223 Some(n) => return *n,
226 // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
227 // FIXME(nagisa): investigate whether it can be changed into define_global
228 let c = declare::declare_global(ccx, &name[..], ty);
229 // Thread-local statics in some other crate need to *always* be linked
230 // against in a thread-local fashion, so we need to be sure to apply the
231 // thread-local attribute locally if it was present remotely. If we
232 // don't do this then linker errors can be generated where the linker
233 // complains that one object files has a thread local version of the
234 // symbol and another one doesn't.
235 for attr in &*ty::get_attrs(ccx.tcx(), did) {
236 if attr.check_name("thread_local") {
237 llvm::set_thread_local(c, true);
240 ccx.externs().borrow_mut().insert(name.to_string(), c);
244 fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
245 info_ty: Ty<'tcx>, it: LangItem) -> ast::DefId {
246 match bcx.tcx().lang_items.require(it) {
249 bcx.sess().fatal(&format!("allocation of `{}` {}",
250 bcx.ty_to_string(info_ty),
256 // The following malloc_raw_dyn* functions allocate a box to contain
257 // a given type, but with a potentially dynamic size.
259 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
265 -> Result<'blk, 'tcx> {
266 let _icx = push_ctxt("malloc_raw_exchange");
269 let r = callee::trans_lang_call(bcx,
270 require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem),
275 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
279 pub fn bin_op_to_icmp_predicate(ccx: &CrateContext, op: ast::BinOp_, signed: bool)
280 -> llvm::IntPredicate {
282 ast::BiEq => llvm::IntEQ,
283 ast::BiNe => llvm::IntNE,
284 ast::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
285 ast::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
286 ast::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
287 ast::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
289 ccx.sess().bug(&format!("comparison_op_to_icmp_predicate: expected \
290 comparison operator, found {:?}", op));
295 pub fn bin_op_to_fcmp_predicate(ccx: &CrateContext, op: ast::BinOp_)
296 -> llvm::RealPredicate {
298 ast::BiEq => llvm::RealOEQ,
299 ast::BiNe => llvm::RealUNE,
300 ast::BiLt => llvm::RealOLT,
301 ast::BiLe => llvm::RealOLE,
302 ast::BiGt => llvm::RealOGT,
303 ast::BiGe => llvm::RealOGE,
305 ccx.sess().bug(&format!("comparison_op_to_fcmp_predicate: expected \
306 comparison operator, found {:?}", op));
311 pub fn compare_scalar_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
319 ty::ty_tup(ref tys) if tys.is_empty() => {
320 // We don't need to do actual comparisons for nil.
321 // () == () holds but () < () does not.
323 ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(bcx.ccx(), true),
324 ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(bcx.ccx(), false),
325 // refinements would be nice
326 _ => bcx.sess().bug("compare_scalar_types: must be a comparison operator")
329 ty::ty_bare_fn(..) | ty::ty_bool | ty::ty_uint(_) | ty::ty_char => {
330 ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, false), lhs, rhs, debug_loc)
332 ty::ty_ptr(mt) if common::type_is_sized(bcx.tcx(), mt.ty) => {
333 ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, false), lhs, rhs, debug_loc)
336 ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, true), lhs, rhs, debug_loc)
339 FCmp(bcx, bin_op_to_fcmp_predicate(bcx.ccx(), op), lhs, rhs, debug_loc)
341 // Should never get here, because t is scalar.
342 _ => bcx.sess().bug("non-scalar type passed to compare_scalar_types")
346 pub fn compare_simd_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
353 let signed = match t.sty {
355 // The comparison operators for floating point vectors are challenging.
356 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
357 // then bitcast to a floating point vector, the result will be `-NaN`
358 // for each truth value. Because of this they are unsupported.
359 bcx.sess().bug("compare_simd_types: comparison operators \
360 not supported for floating point SIMD types")
362 ty::ty_uint(_) => false,
363 ty::ty_int(_) => true,
364 _ => bcx.sess().bug("compare_simd_types: invalid SIMD type"),
367 let cmp = bin_op_to_icmp_predicate(bcx.ccx(), op, signed);
368 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
369 // to get the correctly sized type. This will compile to a single instruction
370 // once the IR is converted to assembly if the SIMD instruction is supported
371 // by the target architecture.
372 SExt(bcx, ICmp(bcx, cmp, lhs, rhs, debug_loc), val_ty(lhs))
375 // Iterates through the elements of a structural type.
376 pub fn iter_structural_ty<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
380 -> Block<'blk, 'tcx> where
381 F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
383 let _icx = push_ctxt("iter_structural_ty");
385 fn iter_variant<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
386 repr: &adt::Repr<'tcx>,
388 variant: &ty::VariantInfo<'tcx>,
389 substs: &Substs<'tcx>,
391 -> Block<'blk, 'tcx> where
392 F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
394 let _icx = push_ctxt("iter_variant");
398 for (i, &arg) in variant.args.iter().enumerate() {
399 let arg = monomorphize::apply_param_substs(tcx, substs, &arg);
400 cx = f(cx, adt::trans_field_ptr(cx, repr, av, variant.disr_val, i), arg);
405 let (data_ptr, info) = if common::type_is_sized(cx.tcx(), t) {
408 let data = GEPi(cx, av, &[0, abi::FAT_PTR_ADDR]);
409 let info = GEPi(cx, av, &[0, abi::FAT_PTR_EXTRA]);
410 (Load(cx, data), Some(Load(cx, info)))
415 ty::ty_struct(..) => {
416 let repr = adt::represent_type(cx.ccx(), t);
417 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
418 for (i, field_ty) in field_tys.iter().enumerate() {
419 let field_ty = field_ty.mt.ty;
420 let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, discr, i);
422 let val = if common::type_is_sized(cx.tcx(), field_ty) {
425 let scratch = datum::rvalue_scratch_datum(cx, field_ty, "__fat_ptr_iter");
426 Store(cx, llfld_a, GEPi(cx, scratch.val, &[0, abi::FAT_PTR_ADDR]));
427 Store(cx, info.unwrap(), GEPi(cx, scratch.val, &[0, abi::FAT_PTR_EXTRA]));
430 cx = f(cx, val, field_ty);
434 ty::ty_closure(def_id, substs) => {
435 let repr = adt::represent_type(cx.ccx(), t);
436 let typer = common::NormalizingClosureTyper::new(cx.tcx());
437 let upvars = typer.closure_upvars(def_id, substs).unwrap();
438 for (i, upvar) in upvars.iter().enumerate() {
439 let llupvar = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
440 cx = f(cx, llupvar, upvar.ty);
443 ty::ty_vec(_, Some(n)) => {
444 let (base, len) = tvec::get_fixed_base_and_len(cx, data_ptr, n);
445 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
446 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
448 ty::ty_vec(_, None) | ty::ty_str => {
449 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
450 cx = tvec::iter_vec_raw(cx, data_ptr, unit_ty, info.unwrap(), f);
452 ty::ty_tup(ref args) => {
453 let repr = adt::represent_type(cx.ccx(), t);
454 for (i, arg) in args.iter().enumerate() {
455 let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
456 cx = f(cx, llfld_a, *arg);
459 ty::ty_enum(tid, substs) => {
463 let repr = adt::represent_type(ccx, t);
464 let variants = ty::enum_variants(ccx.tcx(), tid);
465 let n_variants = (*variants).len();
467 // NB: we must hit the discriminant first so that structural
468 // comparison know not to proceed when the discriminants differ.
470 match adt::trans_switch(cx, &*repr, av) {
471 (_match::Single, None) => {
473 assert!(n_variants == 1);
474 cx = iter_variant(cx, &*repr, av, &*(*variants)[0],
478 (_match::Switch, Some(lldiscrim_a)) => {
479 cx = f(cx, lldiscrim_a, cx.tcx().types.isize);
480 let unr_cx = fcx.new_temp_block("enum-iter-unr");
482 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
484 let next_cx = fcx.new_temp_block("enum-iter-next");
486 for variant in &(*variants) {
489 &format!("enum-iter-variant-{}",
490 &variant.disr_val.to_string())
492 match adt::trans_case(cx, &*repr, variant.disr_val) {
493 _match::SingleResult(r) => {
494 AddCase(llswitch, r.val, variant_cx.llbb)
496 _ => ccx.sess().unimpl("value from adt::trans_case \
497 in iter_structural_ty")
500 iter_variant(variant_cx,
506 Br(variant_cx, next_cx.llbb, DebugLoc::None);
510 _ => ccx.sess().unimpl("value from adt::trans_switch \
511 in iter_structural_ty")
515 cx.sess().unimpl(&format!("type in iter_structural_ty: {}",
516 ty_to_string(cx.tcx(), t)))
522 pub fn cast_shift_expr_rhs(cx: Block,
527 cast_shift_rhs(op, lhs, rhs,
528 |a,b| Trunc(cx, a, b),
529 |a,b| ZExt(cx, a, b))
532 pub fn cast_shift_const_rhs(op: ast::BinOp_,
533 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
534 cast_shift_rhs(op, lhs, rhs,
535 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
536 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
539 fn cast_shift_rhs<F, G>(op: ast::BinOp_,
545 F: FnOnce(ValueRef, Type) -> ValueRef,
546 G: FnOnce(ValueRef, Type) -> ValueRef,
548 // Shifts may have any size int on the rhs
549 if ast_util::is_shift_binop(op) {
550 let mut rhs_llty = val_ty(rhs);
551 let mut lhs_llty = val_ty(lhs);
552 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
553 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
554 let rhs_sz = rhs_llty.int_width();
555 let lhs_sz = lhs_llty.int_width();
558 } else if lhs_sz > rhs_sz {
559 // FIXME (#1877: If shifting by negative
560 // values becomes not undefined then this is wrong.
570 pub fn llty_and_min_for_signed_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
571 val_t: Ty<'tcx>) -> (Type, u64) {
574 let llty = Type::int_from_ty(cx.ccx(), t);
576 ast::TyIs if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
577 ast::TyIs => i64::MIN as u64,
578 ast::TyI8 => i8::MIN as u64,
579 ast::TyI16 => i16::MIN as u64,
580 ast::TyI32 => i32::MIN as u64,
581 ast::TyI64 => i64::MIN as u64,
589 pub fn fail_if_zero_or_overflows<'blk, 'tcx>(
590 cx: Block<'blk, 'tcx>,
591 call_info: NodeIdAndSpan,
596 -> Block<'blk, 'tcx> {
597 let (zero_text, overflow_text) = if divrem.node == ast::BiDiv {
598 ("attempted to divide by zero",
599 "attempted to divide with overflow")
601 ("attempted remainder with a divisor of zero",
602 "attempted remainder with overflow")
604 let debug_loc = call_info.debug_loc();
606 let (is_zero, is_signed) = match rhs_t.sty {
608 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0, false);
609 (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), true)
612 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0, false);
613 (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), false)
615 ty::ty_struct(_, _) if type_is_simd(cx.tcx(), rhs_t) => {
616 let mut res = C_bool(cx.ccx(), false);
617 for i in 0 .. simd_size(cx.tcx(), rhs_t) {
620 ExtractElement(cx, rhs, C_int(cx.ccx(), i as i64))), debug_loc);
625 cx.sess().bug(&format!("fail-if-zero on unexpected type: {}",
626 ty_to_string(cx.tcx(), rhs_t)));
629 let bcx = with_cond(cx, is_zero, |bcx| {
630 controlflow::trans_fail(bcx, call_info, InternedString::new(zero_text))
633 // To quote LLVM's documentation for the sdiv instruction:
635 // Division by zero leads to undefined behavior. Overflow also leads
636 // to undefined behavior; this is a rare case, but can occur, for
637 // example, by doing a 32-bit division of -2147483648 by -1.
639 // In order to avoid undefined behavior, we perform runtime checks for
640 // signed division/remainder which would trigger overflow. For unsigned
641 // integers, no action beyond checking for zero need be taken.
643 let (llty, min) = llty_and_min_for_signed_ty(cx, rhs_t);
644 let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
645 C_integral(llty, !0, false), debug_loc);
646 with_cond(bcx, minus_one, |bcx| {
647 let is_min = ICmp(bcx, llvm::IntEQ, lhs,
648 C_integral(llty, min, true), debug_loc);
649 with_cond(bcx, is_min, |bcx| {
650 controlflow::trans_fail(bcx,
652 InternedString::new(overflow_text))
660 pub fn trans_external_path<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
661 did: ast::DefId, t: Ty<'tcx>) -> ValueRef {
662 let name = csearch::get_symbol(&ccx.sess().cstore, did);
664 ty::ty_bare_fn(_, ref fn_ty) => {
665 match ccx.sess().target.target.adjust_abi(fn_ty.abi) {
667 get_extern_rust_fn(ccx, t, &name[..], did)
670 ccx.sess().bug("unexpected intrinsic in trans_external_path")
673 let llfn = foreign::register_foreign_item_fn(ccx, fn_ty.abi,
675 let attrs = csearch::get_item_attrs(&ccx.sess().cstore, did);
676 attributes::from_fn_attrs(ccx, &attrs, llfn);
682 get_extern_const(ccx, did, t)
687 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
692 -> (ValueRef, Block<'blk, 'tcx>) {
693 let _icx = push_ctxt("invoke_");
694 if bcx.unreachable.get() {
695 return (C_null(Type::i8(bcx.ccx())), bcx);
698 let attributes = attributes::from_fn_type(bcx.ccx(), fn_ty);
700 match bcx.opt_node_id {
702 debug!("invoke at ???");
705 debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
709 if need_invoke(bcx) {
710 debug!("invoking {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
711 for &llarg in llargs {
712 debug!("arg: {}", bcx.val_to_string(llarg));
714 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
715 let landing_pad = bcx.fcx.get_landing_pad();
717 let llresult = Invoke(bcx,
724 return (llresult, normal_bcx);
726 debug!("calling {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
727 for &llarg in llargs {
728 debug!("arg: {}", bcx.val_to_string(llarg));
731 let llresult = Call(bcx,
736 return (llresult, bcx);
740 pub fn need_invoke(bcx: Block) -> bool {
741 if bcx.sess().no_landing_pads() {
745 // Avoid using invoke if we are already inside a landing pad.
750 bcx.fcx.needs_invoke()
753 pub fn load_if_immediate<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
754 v: ValueRef, t: Ty<'tcx>) -> ValueRef {
755 let _icx = push_ctxt("load_if_immediate");
756 if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
760 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
761 /// differs from the type used for SSA values. Also handles various special cases where the type
762 /// gives us better information about what we are loading.
763 pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
764 ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
765 if cx.unreachable.get() || type_is_zero_size(cx.ccx(), t) {
766 return C_undef(type_of::type_of(cx.ccx(), t));
769 let ptr = to_arg_ty_ptr(cx, ptr, t);
770 let align = type_of::align_of(cx.ccx(), t);
772 if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
773 let load = Load(cx, ptr);
775 llvm::LLVMSetAlignment(load, align);
781 let global = llvm::LLVMIsAGlobalVariable(ptr);
782 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
783 let val = llvm::LLVMGetInitializer(global);
785 return from_arg_ty(cx, val, t);
790 let val = if ty::type_is_bool(t) {
791 LoadRangeAssert(cx, ptr, 0, 2, llvm::False)
792 } else if ty::type_is_char(t) {
793 // a char is a Unicode codepoint, and so takes values from 0
794 // to 0x10FFFF inclusive only.
795 LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
796 } else if (ty::type_is_region_ptr(t) || ty::type_is_unique(t))
797 && !common::type_is_fat_ptr(cx.tcx(), t) {
804 llvm::LLVMSetAlignment(val, align);
807 from_arg_ty(cx, val, t)
810 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
811 /// differs from the type used for SSA values.
812 pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
813 if cx.unreachable.get() {
817 let store = Store(cx, to_arg_ty(cx, v, t), to_arg_ty_ptr(cx, dst, t));
819 llvm::LLVMSetAlignment(store, type_of::align_of(cx.ccx(), t));
823 pub fn to_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
824 if ty::type_is_bool(ty) {
825 ZExt(bcx, val, Type::i8(bcx.ccx()))
831 pub fn from_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
832 if ty::type_is_bool(ty) {
833 Trunc(bcx, val, Type::i1(bcx.ccx()))
839 pub fn to_arg_ty_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef, ty: Ty<'tcx>) -> ValueRef {
840 if type_is_immediate(bcx.ccx(), ty) && type_of::type_of(bcx.ccx(), ty).is_aggregate() {
841 // We want to pass small aggregates as immediate values, but using an aggregate LLVM type
842 // for this leads to bad optimizations, so its arg type is an appropriately sized integer
843 // and we have to convert it
844 BitCast(bcx, ptr, type_of::arg_type_of(bcx.ccx(), ty).ptr_to())
850 pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &ast::Local)
851 -> Block<'blk, 'tcx> {
852 debug!("init_local(bcx={}, local.id={})", bcx.to_str(), local.id);
853 let _indenter = indenter();
854 let _icx = push_ctxt("init_local");
855 _match::store_local(bcx, local)
858 pub fn raw_block<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
861 -> Block<'blk, 'tcx> {
862 common::BlockS::new(llbb, is_lpad, None, fcx)
865 pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
868 -> Block<'blk, 'tcx> where
869 F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>,
871 let _icx = push_ctxt("with_cond");
873 if bcx.unreachable.get() ||
874 (common::is_const(val) && common::const_to_uint(val) == 0) {
879 let next_cx = fcx.new_temp_block("next");
880 let cond_cx = fcx.new_temp_block("cond");
881 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb, DebugLoc::None);
882 let after_cx = f(cond_cx);
883 if !after_cx.terminated.get() {
884 Br(after_cx, next_cx.llbb, DebugLoc::None);
889 pub fn call_lifetime_start(cx: Block, ptr: ValueRef) {
890 if cx.sess().opts.optimize == config::No {
894 let _icx = push_ctxt("lifetime_start");
897 let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
898 let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
899 let lifetime_start = ccx.get_intrinsic(&"llvm.lifetime.start");
900 Call(cx, lifetime_start, &[llsize, ptr], None, DebugLoc::None);
903 pub fn call_lifetime_end(cx: Block, ptr: ValueRef) {
904 if cx.sess().opts.optimize == config::No {
908 let _icx = push_ctxt("lifetime_end");
911 let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
912 let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
913 let lifetime_end = ccx.get_intrinsic(&"llvm.lifetime.end");
914 Call(cx, lifetime_end, &[llsize, ptr], None, DebugLoc::None);
917 pub fn call_memcpy(cx: Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
918 let _icx = push_ctxt("call_memcpy");
920 let key = match &ccx.sess().target.target.target_pointer_width[..] {
921 "32" => "llvm.memcpy.p0i8.p0i8.i32",
922 "64" => "llvm.memcpy.p0i8.p0i8.i64",
923 tws => panic!("Unsupported target word size for memcpy: {}", tws),
925 let memcpy = ccx.get_intrinsic(&key);
926 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
927 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
928 let size = IntCast(cx, n_bytes, ccx.int_type());
929 let align = C_i32(ccx, align as i32);
930 let volatile = C_bool(ccx, false);
931 Call(cx, memcpy, &[dst_ptr, src_ptr, size, align, volatile], None, DebugLoc::None);
934 pub fn memcpy_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
935 dst: ValueRef, src: ValueRef,
937 let _icx = push_ctxt("memcpy_ty");
939 if ty::type_is_structural(t) {
940 let llty = type_of::type_of(ccx, t);
941 let llsz = llsize_of(ccx, llty);
942 let llalign = type_of::align_of(ccx, t);
943 call_memcpy(bcx, dst, src, llsz, llalign as u32);
945 store_ty(bcx, load_ty(bcx, src, t), dst, t);
949 pub fn drop_done_fill_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
950 if cx.unreachable.get() { return; }
951 let _icx = push_ctxt("drop_done_fill_mem");
953 memfill(&B(bcx), llptr, t, adt::DTOR_DONE);
956 pub fn init_zero_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
957 if cx.unreachable.get() { return; }
958 let _icx = push_ctxt("init_zero_mem");
960 memfill(&B(bcx), llptr, t, 0);
963 // Always use this function instead of storing a constant byte to the memory
964 // in question. e.g. if you store a zero constant, LLVM will drown in vreg
965 // allocation for large data structures, and the generated code will be
966 // awful. (A telltale sign of this is large quantities of
967 // `mov [byte ptr foo],0` in the generated code.)
968 fn memfill<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>, byte: u8) {
969 let _icx = push_ctxt("memfill");
972 let llty = type_of::type_of(ccx, ty);
974 let intrinsic_key = match &ccx.sess().target.target.target_pointer_width[..] {
975 "32" => "llvm.memset.p0i8.i32",
976 "64" => "llvm.memset.p0i8.i64",
977 tws => panic!("Unsupported target word size for memset: {}", tws),
980 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
981 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
982 let llzeroval = C_u8(ccx, byte as usize);
983 let size = machine::llsize_of(ccx, llty);
984 let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
985 let volatile = C_bool(ccx, false);
986 b.call(llintrinsicfn, &[llptr, llzeroval, size, align, volatile], None);
989 pub fn alloc_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, name: &str) -> ValueRef {
990 let _icx = push_ctxt("alloc_ty");
992 let ty = type_of::type_of(ccx, t);
993 assert!(!ty::type_has_params(t));
994 let val = alloca(bcx, ty, name);
998 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
999 let p = alloca_no_lifetime(cx, ty, name);
1000 call_lifetime_start(cx, p);
1004 pub fn alloca_no_lifetime(cx: Block, ty: Type, name: &str) -> ValueRef {
1005 let _icx = push_ctxt("alloca");
1006 if cx.unreachable.get() {
1008 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1011 debuginfo::clear_source_location(cx.fcx);
1012 Alloca(cx, ty, name)
1015 // Creates the alloca slot which holds the pointer to the slot for the final return value
1016 pub fn make_return_slot_pointer<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1017 output_type: Ty<'tcx>) -> ValueRef {
1018 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1020 // We create an alloca to hold a pointer of type `output_type`
1021 // which will hold the pointer to the right alloca which has the
1023 if fcx.needs_ret_allocas {
1024 // Let's create the stack slot
1025 let slot = AllocaFcx(fcx, lloutputtype.ptr_to(), "llretslotptr");
1027 // and if we're using an out pointer, then store that in our newly made slot
1028 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1029 let outptr = get_param(fcx.llfn, 0);
1031 let b = fcx.ccx.builder();
1032 b.position_before(fcx.alloca_insert_pt.get().unwrap());
1033 b.store(outptr, slot);
1038 // But if there are no nested returns, we skip the indirection and have a single
1041 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1042 get_param(fcx.llfn, 0)
1044 AllocaFcx(fcx, lloutputtype, "sret_slot")
1049 struct FindNestedReturn {
1053 impl FindNestedReturn {
1054 fn new() -> FindNestedReturn {
1055 FindNestedReturn { found: false }
1059 impl<'v> Visitor<'v> for FindNestedReturn {
1060 fn visit_expr(&mut self, e: &ast::Expr) {
1062 ast::ExprRet(..) => {
1065 _ => visit::walk_expr(self, e)
1070 fn build_cfg(tcx: &ty::ctxt, id: ast::NodeId) -> (ast::NodeId, Option<cfg::CFG>) {
1071 let blk = match tcx.map.find(id) {
1072 Some(ast_map::NodeItem(i)) => {
1074 ast::ItemFn(_, _, _, _, ref blk) => {
1077 _ => tcx.sess.bug("unexpected item variant in has_nested_returns")
1080 Some(ast_map::NodeTraitItem(trait_item)) => {
1081 match trait_item.node {
1082 ast::MethodTraitItem(_, Some(ref body)) => body,
1084 tcx.sess.bug("unexpected variant: trait item other than a \
1085 provided method in has_nested_returns")
1089 Some(ast_map::NodeImplItem(impl_item)) => {
1090 match impl_item.node {
1091 ast::MethodImplItem(_, ref body) => body,
1093 tcx.sess.bug("unexpected variant: non-method impl item in \
1094 has_nested_returns")
1098 Some(ast_map::NodeExpr(e)) => {
1100 ast::ExprClosure(_, _, ref blk) => blk,
1101 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns")
1104 Some(ast_map::NodeVariant(..)) |
1105 Some(ast_map::NodeStructCtor(..)) => return (ast::DUMMY_NODE_ID, None),
1108 None if id == ast::DUMMY_NODE_ID => return (ast::DUMMY_NODE_ID, None),
1110 _ => tcx.sess.bug(&format!("unexpected variant in has_nested_returns: {}",
1111 tcx.map.path_to_string(id)))
1114 (blk.id, Some(cfg::CFG::new(tcx, blk)))
1117 // Checks for the presence of "nested returns" in a function.
1118 // Nested returns are when the inner expression of a return expression
1119 // (the 'expr' in 'return expr') contains a return expression. Only cases
1120 // where the outer return is actually reachable are considered. Implicit
1121 // returns from the end of blocks are considered as well.
1123 // This check is needed to handle the case where the inner expression is
1124 // part of a larger expression that may have already partially-filled the
1125 // return slot alloca. This can cause errors related to clean-up due to
1126 // the clobbering of the existing value in the return slot.
1127 fn has_nested_returns(tcx: &ty::ctxt, cfg: &cfg::CFG, blk_id: ast::NodeId) -> bool {
1128 for n in cfg.graph.depth_traverse(cfg.entry) {
1129 match tcx.map.find(n.id()) {
1130 Some(ast_map::NodeExpr(ex)) => {
1131 if let ast::ExprRet(Some(ref ret_expr)) = ex.node {
1132 let mut visitor = FindNestedReturn::new();
1133 visit::walk_expr(&mut visitor, &**ret_expr);
1139 Some(ast_map::NodeBlock(blk)) if blk.id == blk_id => {
1140 let mut visitor = FindNestedReturn::new();
1141 visit::walk_expr_opt(&mut visitor, &blk.expr);
1153 // NB: must keep 4 fns in sync:
1156 // - create_datums_for_fn_args.
1160 // Be warned! You must call `init_function` before doing anything with the
1161 // returned function context.
1162 pub fn new_fn_ctxt<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
1166 output_type: ty::FnOutput<'tcx>,
1167 param_substs: &'tcx Substs<'tcx>,
1169 block_arena: &'a TypedArena<common::BlockS<'a, 'tcx>>)
1170 -> FunctionContext<'a, 'tcx> {
1171 common::validate_substs(param_substs);
1173 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1177 ccx.tcx().map.path_to_string(id).to_string()
1179 id, param_substs.repr(ccx.tcx()));
1181 let uses_outptr = match output_type {
1182 ty::FnConverging(output_type) => {
1183 let substd_output_type =
1184 monomorphize::apply_param_substs(ccx.tcx(), param_substs, &output_type);
1185 type_of::return_uses_outptr(ccx, substd_output_type)
1187 ty::FnDiverging => false
1189 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1190 let (blk_id, cfg) = build_cfg(ccx.tcx(), id);
1191 let nested_returns = if let Some(ref cfg) = cfg {
1192 has_nested_returns(ccx.tcx(), cfg, blk_id)
1197 let mut fcx = FunctionContext {
1200 llretslotptr: Cell::new(None),
1201 param_env: ty::empty_parameter_environment(ccx.tcx()),
1202 alloca_insert_pt: Cell::new(None),
1203 llreturn: Cell::new(None),
1204 needs_ret_allocas: nested_returns,
1205 personality: Cell::new(None),
1206 caller_expects_out_pointer: uses_outptr,
1207 lllocals: RefCell::new(NodeMap()),
1208 llupvars: RefCell::new(NodeMap()),
1210 param_substs: param_substs,
1212 block_arena: block_arena,
1214 debug_context: debug_context,
1215 scopes: RefCell::new(Vec::new()),
1220 fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1226 /// Performs setup on a newly created function, creating the entry scope block
1227 /// and allocating space for the return pointer.
1228 pub fn init_function<'a, 'tcx>(fcx: &'a FunctionContext<'a, 'tcx>,
1230 output: ty::FnOutput<'tcx>)
1231 -> Block<'a, 'tcx> {
1232 let entry_bcx = fcx.new_temp_block("entry-block");
1234 // Use a dummy instruction as the insertion point for all allocas.
1235 // This is later removed in FunctionContext::cleanup.
1236 fcx.alloca_insert_pt.set(Some(unsafe {
1237 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1238 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1241 if let ty::FnConverging(output_type) = output {
1242 // This shouldn't need to recompute the return type,
1243 // as new_fn_ctxt did it already.
1244 let substd_output_type = fcx.monomorphize(&output_type);
1245 if !return_type_is_void(fcx.ccx, substd_output_type) {
1246 // If the function returns nil/bot, there is no real return
1247 // value, so do not set `llretslotptr`.
1248 if !skip_retptr || fcx.caller_expects_out_pointer {
1249 // Otherwise, we normally allocate the llretslotptr, unless we
1250 // have been instructed to skip it for immediate return
1252 fcx.llretslotptr.set(Some(make_return_slot_pointer(fcx, substd_output_type)));
1260 // NB: must keep 4 fns in sync:
1263 // - create_datums_for_fn_args.
1267 pub fn arg_kind<'a, 'tcx>(cx: &FunctionContext<'a, 'tcx>, t: Ty<'tcx>)
1269 use trans::datum::{ByRef, ByValue};
1272 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1276 // work around bizarre resolve errors
1277 pub type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
1279 // create_datums_for_fn_args: creates rvalue datums for each of the
1280 // incoming function arguments. These will later be stored into
1281 // appropriate lvalue datums.
1282 pub fn create_datums_for_fn_args<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1283 arg_tys: &[Ty<'tcx>])
1284 -> Vec<RvalueDatum<'tcx>> {
1285 let _icx = push_ctxt("create_datums_for_fn_args");
1287 // Return an array wrapping the ValueRefs that we get from `get_param` for
1288 // each argument into datums.
1289 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1290 let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1291 datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1295 /// Creates rvalue datums for each of the incoming function arguments and
1296 /// tuples the arguments. These will later be stored into appropriate lvalue
1299 /// FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1300 fn create_datums_for_fn_args_under_call_abi<'blk, 'tcx>(
1301 mut bcx: Block<'blk, 'tcx>,
1302 arg_scope: cleanup::CustomScopeIndex,
1303 arg_tys: &[Ty<'tcx>])
1304 -> Vec<RvalueDatum<'tcx>> {
1305 let mut result = Vec::new();
1306 for (i, &arg_ty) in arg_tys.iter().enumerate() {
1307 if i < arg_tys.len() - 1 {
1308 // Regular argument.
1309 let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1310 result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1315 // This is the last argument. Tuple it.
1317 ty::ty_tup(ref tupled_arg_tys) => {
1318 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1321 datum::lvalue_scratch_datum(bcx,
1324 tuple_args_scope_id,
1329 for (j, &tupled_arg_ty) in
1330 tupled_arg_tys.iter().enumerate() {
1332 get_param(bcx.fcx.llfn,
1333 bcx.fcx.arg_pos(i + j) as c_uint);
1334 let lldest = GEPi(bcx, llval, &[0, j]);
1335 let datum = datum::Datum::new(
1338 arg_kind(bcx.fcx, tupled_arg_ty));
1339 bcx = datum.store_to(bcx, lldest);
1343 let tuple = unpack_datum!(bcx,
1344 tuple.to_expr_datum()
1345 .to_rvalue_datum(bcx,
1350 bcx.tcx().sess.bug("last argument of a function with \
1351 `rust-call` ABI isn't a tuple?!")
1360 fn copy_args_to_allocas<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1361 arg_scope: cleanup::CustomScopeIndex,
1363 arg_datums: Vec<RvalueDatum<'tcx>>)
1364 -> Block<'blk, 'tcx> {
1365 debug!("copy_args_to_allocas");
1367 let _icx = push_ctxt("copy_args_to_allocas");
1370 let arg_scope_id = cleanup::CustomScope(arg_scope);
1372 for (i, arg_datum) in arg_datums.into_iter().enumerate() {
1373 // For certain mode/type combinations, the raw llarg values are passed
1374 // by value. However, within the fn body itself, we want to always
1375 // have all locals and arguments be by-ref so that we can cancel the
1376 // cleanup and for better interaction with LLVM's debug info. So, if
1377 // the argument would be passed by value, we store it into an alloca.
1378 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1379 // the event it's not truly needed.
1381 bcx = _match::store_arg(bcx, &*args[i].pat, arg_datum, arg_scope_id);
1382 debuginfo::create_argument_metadata(bcx, &args[i]);
1388 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1389 // and builds the return block.
1390 pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1391 last_bcx: Block<'blk, 'tcx>,
1392 retty: ty::FnOutput<'tcx>,
1393 ret_debug_loc: DebugLoc) {
1394 let _icx = push_ctxt("finish_fn");
1396 let ret_cx = match fcx.llreturn.get() {
1398 if !last_bcx.terminated.get() {
1399 Br(last_bcx, llreturn, DebugLoc::None);
1401 raw_block(fcx, false, llreturn)
1406 // This shouldn't need to recompute the return type,
1407 // as new_fn_ctxt did it already.
1408 let substd_retty = fcx.monomorphize(&retty);
1409 build_return_block(fcx, ret_cx, substd_retty, ret_debug_loc);
1411 debuginfo::clear_source_location(fcx);
1415 // Builds the return block for a function.
1416 pub fn build_return_block<'blk, 'tcx>(fcx: &FunctionContext<'blk, 'tcx>,
1417 ret_cx: Block<'blk, 'tcx>,
1418 retty: ty::FnOutput<'tcx>,
1419 ret_debug_location: DebugLoc) {
1420 if fcx.llretslotptr.get().is_none() ||
1421 (!fcx.needs_ret_allocas && fcx.caller_expects_out_pointer) {
1422 return RetVoid(ret_cx, ret_debug_location);
1425 let retslot = if fcx.needs_ret_allocas {
1426 Load(ret_cx, fcx.llretslotptr.get().unwrap())
1428 fcx.llretslotptr.get().unwrap()
1430 let retptr = Value(retslot);
1431 match retptr.get_dominating_store(ret_cx) {
1432 // If there's only a single store to the ret slot, we can directly return
1433 // the value that was stored and omit the store and the alloca
1435 let retval = s.get_operand(0).unwrap().get();
1436 s.erase_from_parent();
1438 if retptr.has_no_uses() {
1439 retptr.erase_from_parent();
1442 let retval = if retty == ty::FnConverging(fcx.ccx.tcx().types.bool) {
1443 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1448 if fcx.caller_expects_out_pointer {
1449 if let ty::FnConverging(retty) = retty {
1450 store_ty(ret_cx, retval, get_param(fcx.llfn, 0), retty);
1452 RetVoid(ret_cx, ret_debug_location)
1454 Ret(ret_cx, retval, ret_debug_location)
1457 // Otherwise, copy the return value to the ret slot
1458 None => match retty {
1459 ty::FnConverging(retty) => {
1460 if fcx.caller_expects_out_pointer {
1461 memcpy_ty(ret_cx, get_param(fcx.llfn, 0), retslot, retty);
1462 RetVoid(ret_cx, ret_debug_location)
1464 Ret(ret_cx, load_ty(ret_cx, retslot, retty), ret_debug_location)
1467 ty::FnDiverging => {
1468 if fcx.caller_expects_out_pointer {
1469 RetVoid(ret_cx, ret_debug_location)
1471 Ret(ret_cx, C_undef(Type::nil(fcx.ccx)), ret_debug_location)
1478 /// Builds an LLVM function out of a source function.
1480 /// If the function closes over its environment a closure will be returned.
1481 pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1485 param_substs: &'tcx Substs<'tcx>,
1486 fn_ast_id: ast::NodeId,
1487 _attributes: &[ast::Attribute],
1488 output_type: ty::FnOutput<'tcx>,
1490 closure_env: closure::ClosureEnv<'b>) {
1491 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1493 let _icx = push_ctxt("trans_closure");
1494 attributes::emit_uwtable(llfndecl, true);
1496 debug!("trans_closure(..., param_substs={})",
1497 param_substs.repr(ccx.tcx()));
1499 let has_env = match closure_env {
1500 closure::ClosureEnv::Closure(_) => true,
1501 closure::ClosureEnv::NotClosure => false,
1504 let (arena, fcx): (TypedArena<_>, FunctionContext);
1505 arena = TypedArena::new();
1506 fcx = new_fn_ctxt(ccx,
1514 let mut bcx = init_function(&fcx, false, output_type);
1516 // cleanup scope for the incoming arguments
1517 let fn_cleanup_debug_loc =
1518 debuginfo::get_cleanup_debug_loc_for_ast_node(ccx, fn_ast_id, body.span, true);
1519 let arg_scope = fcx.push_custom_cleanup_scope_with_debug_loc(fn_cleanup_debug_loc);
1521 let block_ty = node_id_type(bcx, body.id);
1523 // Set up arguments to the function.
1524 let monomorphized_arg_types =
1526 .map(|arg| node_id_type(bcx, arg.id))
1527 .collect::<Vec<_>>();
1528 let monomorphized_arg_types = match closure_env {
1529 closure::ClosureEnv::NotClosure => {
1530 monomorphized_arg_types
1533 // Tuple up closure argument types for the "rust-call" ABI.
1534 closure::ClosureEnv::Closure(_) => {
1535 vec![ty::mk_tup(ccx.tcx(), monomorphized_arg_types)]
1538 for monomorphized_arg_type in &monomorphized_arg_types {
1539 debug!("trans_closure: monomorphized_arg_type: {}",
1540 ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1542 debug!("trans_closure: function lltype: {}",
1543 bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
1545 let arg_datums = match closure_env {
1546 closure::ClosureEnv::NotClosure if abi == RustCall => {
1547 create_datums_for_fn_args_under_call_abi(bcx, arg_scope, &monomorphized_arg_types[..])
1550 let arg_tys = untuple_arguments_if_necessary(ccx, &monomorphized_arg_types, abi);
1551 create_datums_for_fn_args(&fcx, &arg_tys)
1555 bcx = copy_args_to_allocas(bcx, arg_scope, &decl.inputs, arg_datums);
1557 bcx = closure_env.load(bcx, cleanup::CustomScope(arg_scope));
1559 // Up until here, IR instructions for this function have explicitly not been annotated with
1560 // source code location, so we don't step into call setup code. From here on, source location
1561 // emitting should be enabled.
1562 debuginfo::start_emitting_source_locations(&fcx);
1564 let dest = match fcx.llretslotptr.get() {
1565 Some(_) => expr::SaveIn(fcx.get_ret_slot(bcx, ty::FnConverging(block_ty), "iret_slot")),
1567 assert!(type_is_zero_size(bcx.ccx(), block_ty));
1572 // This call to trans_block is the place where we bridge between
1573 // translation calls that don't have a return value (trans_crate,
1574 // trans_mod, trans_item, et cetera) and those that do
1575 // (trans_block, trans_expr, et cetera).
1576 bcx = controlflow::trans_block(bcx, body, dest);
1579 expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1580 Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1585 match fcx.llreturn.get() {
1587 Br(bcx, fcx.return_exit_block(), DebugLoc::None);
1588 fcx.pop_custom_cleanup_scope(arg_scope);
1591 // Microoptimization writ large: avoid creating a separate
1592 // llreturn basic block
1593 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1597 // Put return block after all other blocks.
1598 // This somewhat improves single-stepping experience in debugger.
1600 let llreturn = fcx.llreturn.get();
1601 if let Some(llreturn) = llreturn {
1602 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1606 let ret_debug_loc = DebugLoc::At(fn_cleanup_debug_loc.id,
1607 fn_cleanup_debug_loc.span);
1609 // Insert the mandatory first few basic blocks before lltop.
1610 finish_fn(&fcx, bcx, output_type, ret_debug_loc);
1613 /// Creates an LLVM function corresponding to a source language function.
1614 pub fn trans_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1618 param_substs: &'tcx Substs<'tcx>,
1620 attrs: &[ast::Attribute]) {
1621 let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string());
1622 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1623 let _icx = push_ctxt("trans_fn");
1624 let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1625 let output_type = ty::erase_late_bound_regions(ccx.tcx(), &ty::ty_fn_ret(fn_ty));
1626 let abi = ty::ty_fn_abi(fn_ty);
1627 trans_closure(ccx, decl, body, llfndecl, param_substs, id, attrs, output_type, abi,
1628 closure::ClosureEnv::NotClosure);
1631 pub fn trans_enum_variant<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1632 _enum_id: ast::NodeId,
1633 variant: &ast::Variant,
1634 _args: &[ast::VariantArg],
1636 param_substs: &'tcx Substs<'tcx>,
1637 llfndecl: ValueRef) {
1638 let _icx = push_ctxt("trans_enum_variant");
1640 trans_enum_variant_or_tuple_like_struct(
1648 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1651 args: callee::CallArgs,
1653 debug_loc: DebugLoc)
1654 -> Result<'blk, 'tcx> {
1656 let ccx = bcx.fcx.ccx;
1657 let tcx = ccx.tcx();
1659 let result_ty = match ctor_ty.sty {
1660 ty::ty_bare_fn(_, ref bft) => {
1661 ty::erase_late_bound_regions(bcx.tcx(), &bft.sig.output()).unwrap()
1663 _ => ccx.sess().bug(
1664 &format!("trans_enum_variant_constructor: \
1665 unexpected ctor return type {}",
1669 // Get location to store the result. If the user does not care about
1670 // the result, just make a stack slot
1671 let llresult = match dest {
1672 expr::SaveIn(d) => d,
1674 if !type_is_zero_size(ccx, result_ty) {
1675 alloc_ty(bcx, result_ty, "constructor_result")
1677 C_undef(type_of::type_of(ccx, result_ty))
1682 if !type_is_zero_size(ccx, result_ty) {
1684 callee::ArgExprs(exprs) => {
1685 let fields = exprs.iter().map(|x| &**x).enumerate().collect::<Vec<_>>();
1686 bcx = expr::trans_adt(bcx,
1691 expr::SaveIn(llresult),
1694 _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor")
1698 // If the caller doesn't care about the result
1699 // drop the temporary we made
1700 let bcx = match dest {
1701 expr::SaveIn(_) => bcx,
1703 let bcx = glue::drop_ty(bcx, llresult, result_ty, debug_loc);
1704 if !type_is_zero_size(ccx, result_ty) {
1705 call_lifetime_end(bcx, llresult);
1711 Result::new(bcx, llresult)
1714 pub fn trans_tuple_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1715 _fields: &[ast::StructField],
1716 ctor_id: ast::NodeId,
1717 param_substs: &'tcx Substs<'tcx>,
1718 llfndecl: ValueRef) {
1719 let _icx = push_ctxt("trans_tuple_struct");
1721 trans_enum_variant_or_tuple_like_struct(
1729 fn trans_enum_variant_or_tuple_like_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1730 ctor_id: ast::NodeId,
1732 param_substs: &'tcx Substs<'tcx>,
1733 llfndecl: ValueRef) {
1734 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1735 let ctor_ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &ctor_ty);
1737 let result_ty = match ctor_ty.sty {
1738 ty::ty_bare_fn(_, ref bft) => {
1739 ty::erase_late_bound_regions(ccx.tcx(), &bft.sig.output())
1741 _ => ccx.sess().bug(
1742 &format!("trans_enum_variant_or_tuple_like_struct: \
1743 unexpected ctor return type {}",
1744 ty_to_string(ccx.tcx(), ctor_ty)))
1747 let (arena, fcx): (TypedArena<_>, FunctionContext);
1748 arena = TypedArena::new();
1749 fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1750 param_substs, None, &arena);
1751 let bcx = init_function(&fcx, false, result_ty);
1753 assert!(!fcx.needs_ret_allocas);
1756 ty::erase_late_bound_regions(
1757 ccx.tcx(), &ty::ty_fn_args(ctor_ty));
1759 let arg_datums = create_datums_for_fn_args(&fcx, &arg_tys[..]);
1761 if !type_is_zero_size(fcx.ccx, result_ty.unwrap()) {
1762 let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot");
1763 let repr = adt::represent_type(ccx, result_ty.unwrap());
1764 for (i, arg_datum) in arg_datums.into_iter().enumerate() {
1765 let lldestptr = adt::trans_field_ptr(bcx,
1770 arg_datum.store_to(bcx, lldestptr);
1772 adt::trans_set_discr(bcx, &*repr, dest, disr);
1775 finish_fn(&fcx, bcx, result_ty, DebugLoc::None);
1778 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
1779 let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
1781 let print_info = ccx.sess().print_enum_sizes();
1783 let levels = ccx.tcx().node_lint_levels.borrow();
1784 let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCES);
1785 let lvlsrc = levels.get(&(id, lint_id));
1786 let is_allow = lvlsrc.map_or(true, |&(lvl, _)| lvl == lint::Allow);
1788 if is_allow && !print_info {
1789 // we're not interested in anything here
1793 let ty = ty::node_id_to_type(ccx.tcx(), id);
1794 let avar = adt::represent_type(ccx, ty);
1796 adt::General(_, ref variants, _) => {
1797 for var in variants {
1799 for field in var.fields.iter().skip(1) {
1800 // skip the discriminant
1801 size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
1806 _ => { /* its size is either constant or unimportant */ }
1809 let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
1810 |(l, s, li), (idx, &size)|
1813 } else if size > s {
1821 let llty = type_of::sizing_type_of(ccx, ty);
1823 let sess = &ccx.tcx().sess;
1824 sess.span_note(sp, &*format!("total size: {} bytes", llsize_of_real(ccx, llty)));
1826 adt::General(..) => {
1827 for (i, var) in enum_def.variants.iter().enumerate() {
1828 ccx.tcx().sess.span_note(var.span,
1829 &*format!("variant data: {} bytes", sizes[i]));
1836 // we only warn if the largest variant is at least thrice as large as
1837 // the second-largest.
1838 if !is_allow && largest > slargest * 3 && slargest > 0 {
1839 // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
1840 // pass for the latter already ran.
1841 lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCES,
1842 *lvlsrc.unwrap(), Some(sp),
1843 &format!("enum variant is more than three times larger \
1844 ({} bytes) than the next largest (ignoring padding)",
1847 ccx.sess().span_note(enum_def.variants[largest_index].span,
1848 "this variant is the largest");
1852 pub struct TransItemVisitor<'a, 'tcx: 'a> {
1853 pub ccx: &'a CrateContext<'a, 'tcx>,
1856 impl<'a, 'tcx, 'v> Visitor<'v> for TransItemVisitor<'a, 'tcx> {
1857 fn visit_item(&mut self, i: &ast::Item) {
1858 trans_item(self.ccx, i);
1862 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
1863 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
1864 // applicable to variable declarations and may not really make sense for
1865 // Rust code in the first place but whitelist them anyway and trust that
1866 // the user knows what s/he's doing. Who knows, unanticipated use cases
1867 // may pop up in the future.
1869 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
1870 // and don't have to be, LLVM treats them as no-ops.
1872 "appending" => Some(llvm::AppendingLinkage),
1873 "available_externally" => Some(llvm::AvailableExternallyLinkage),
1874 "common" => Some(llvm::CommonLinkage),
1875 "extern_weak" => Some(llvm::ExternalWeakLinkage),
1876 "external" => Some(llvm::ExternalLinkage),
1877 "internal" => Some(llvm::InternalLinkage),
1878 "linkonce" => Some(llvm::LinkOnceAnyLinkage),
1879 "linkonce_odr" => Some(llvm::LinkOnceODRLinkage),
1880 "private" => Some(llvm::PrivateLinkage),
1881 "weak" => Some(llvm::WeakAnyLinkage),
1882 "weak_odr" => Some(llvm::WeakODRLinkage),
1888 /// Enum describing the origin of an LLVM `Value`, for linkage purposes.
1889 #[derive(Copy, Clone)]
1890 pub enum ValueOrigin {
1891 /// The LLVM `Value` is in this context because the corresponding item was
1892 /// assigned to the current compilation unit.
1893 OriginalTranslation,
1894 /// The `Value`'s corresponding item was assigned to some other compilation
1895 /// unit, but the `Value` was translated in this context anyway because the
1896 /// item is marked `#[inline]`.
1900 /// Set the appropriate linkage for an LLVM `ValueRef` (function or global).
1901 /// If the `llval` is the direct translation of a specific Rust item, `id`
1902 /// should be set to the `NodeId` of that item. (This mapping should be
1903 /// 1-to-1, so monomorphizations and drop/visit glue should have `id` set to
1904 /// `None`.) `llval_origin` indicates whether `llval` is the translation of an
1905 /// item assigned to `ccx`'s compilation unit or an inlined copy of an item
1906 /// assigned to a different compilation unit.
1907 pub fn update_linkage(ccx: &CrateContext,
1909 id: Option<ast::NodeId>,
1910 llval_origin: ValueOrigin) {
1911 match llval_origin {
1913 // `llval` is a translation of an item defined in a separate
1914 // compilation unit. This only makes sense if there are at least
1915 // two compilation units.
1916 assert!(ccx.sess().opts.cg.codegen_units > 1);
1917 // `llval` is a copy of something defined elsewhere, so use
1918 // `AvailableExternallyLinkage` to avoid duplicating code in the
1920 llvm::SetLinkage(llval, llvm::AvailableExternallyLinkage);
1923 OriginalTranslation => {},
1926 if let Some(id) = id {
1927 let item = ccx.tcx().map.get(id);
1928 if let ast_map::NodeItem(i) = item {
1929 if let Some(name) = attr::first_attr_value_str_by_name(&i.attrs, "linkage") {
1930 if let Some(linkage) = llvm_linkage_by_name(&name) {
1931 llvm::SetLinkage(llval, linkage);
1933 ccx.sess().span_fatal(i.span, "invalid linkage specified");
1941 Some(id) if ccx.reachable().contains(&id) => {
1942 llvm::SetLinkage(llval, llvm::ExternalLinkage);
1945 // `id` does not refer to an item in `ccx.reachable`.
1946 if ccx.sess().opts.cg.codegen_units > 1 {
1947 llvm::SetLinkage(llval, llvm::ExternalLinkage);
1949 llvm::SetLinkage(llval, llvm::InternalLinkage);
1955 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1956 let _icx = push_ctxt("trans_item");
1958 let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
1961 ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
1962 if !generics.is_type_parameterized() {
1963 let trans_everywhere = attr::requests_inline(&item.attrs);
1964 // Ignore `trans_everywhere` for cross-crate inlined items
1965 // (`from_external`). `trans_item` will be called once for each
1966 // compilation unit that references the item, so it will still get
1967 // translated everywhere it's needed.
1968 for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
1969 let llfn = get_item_val(ccx, item.id);
1970 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
1972 foreign::trans_rust_fn_with_foreign_abi(ccx, &**decl, &**body, &item.attrs,
1973 llfn, empty_substs, item.id, None);
1975 trans_fn(ccx, &**decl, &**body, llfn, empty_substs, item.id, &item.attrs);
1977 update_linkage(ccx, llfn, Some(item.id),
1978 if is_origin { OriginalTranslation } else { InlinedCopy });
1980 if is_entry_fn(ccx.sess(), item.id) {
1981 create_entry_wrapper(ccx, item.span, llfn);
1982 // check for the #[rustc_error] annotation, which forces an
1983 // error in trans. This is used to write compile-fail tests
1984 // that actually test that compilation succeeds without
1985 // reporting an error.
1986 if ty::has_attr(ccx.tcx(), local_def(item.id), "rustc_error") {
1987 ccx.tcx().sess.span_fatal(item.span, "compilation successful");
1993 // Be sure to travel more than just one layer deep to catch nested
1994 // items in blocks and such.
1995 let mut v = TransItemVisitor{ ccx: ccx };
1996 v.visit_block(&**body);
1998 ast::ItemImpl(_, _, ref generics, _, _, ref impl_items) => {
1999 meth::trans_impl(ccx,
2005 ast::ItemMod(ref m) => {
2006 trans_mod(&ccx.rotate(), m);
2008 ast::ItemEnum(ref enum_definition, ref gens) => {
2009 if gens.ty_params.is_empty() {
2010 // sizes only make sense for non-generic types
2012 enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
2015 ast::ItemConst(_, ref expr) => {
2016 // Recurse on the expression to catch items in blocks
2017 let mut v = TransItemVisitor{ ccx: ccx };
2018 v.visit_expr(&**expr);
2020 ast::ItemStatic(_, m, ref expr) => {
2021 // Recurse on the expression to catch items in blocks
2022 let mut v = TransItemVisitor{ ccx: ccx };
2023 v.visit_expr(&**expr);
2025 let g = consts::trans_static(ccx, m, item.id);
2026 update_linkage(ccx, g, Some(item.id), OriginalTranslation);
2028 // Do static_assert checking. It can't really be done much earlier
2029 // because we need to get the value of the bool out of LLVM
2030 if attr::contains_name(&item.attrs, "static_assert") {
2031 if !ty::type_is_bool(ty::expr_ty(ccx.tcx(), expr)) {
2032 ccx.sess().span_fatal(expr.span,
2033 "can only have static_assert on a static \
2036 if m == ast::MutMutable {
2037 ccx.sess().span_fatal(expr.span,
2038 "cannot have static_assert on a mutable \
2042 let v = ccx.static_values().borrow().get(&item.id).unwrap().clone();
2044 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2045 ccx.sess().span_fatal(expr.span, "static assertion failed");
2050 ast::ItemForeignMod(ref foreign_mod) => {
2051 foreign::trans_foreign_mod(ccx, foreign_mod);
2053 ast::ItemTrait(..) => {
2054 // Inside of this trait definition, we won't be actually translating any
2055 // functions, but the trait still needs to be walked. Otherwise default
2056 // methods with items will not get translated and will cause ICE's when
2057 // metadata time comes around.
2058 let mut v = TransItemVisitor{ ccx: ccx };
2059 visit::walk_item(&mut v, item);
2061 _ => {/* fall through */ }
2065 // Translate a module. Doing this amounts to translating the items in the
2066 // module; there ends up being no artifact (aside from linkage names) of
2067 // separate modules in the compiled program. That's because modules exist
2068 // only as a convenience for humans working with the code, to organize names
2069 // and control visibility.
2070 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
2071 let _icx = push_ctxt("trans_mod");
2072 for item in &m.items {
2073 trans_item(ccx, &**item);
2078 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2079 pub fn register_fn_llvmty(ccx: &CrateContext,
2082 node_id: ast::NodeId,
2084 llfty: Type) -> ValueRef {
2085 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2087 let llfn = declare::define_fn(ccx, &sym[..], cc, llfty,
2088 ty::FnConverging(ty::mk_nil(ccx.tcx()))).unwrap_or_else(||{
2089 ccx.sess().span_fatal(sp, &format!("symbol `{}` is already defined", sym));
2091 finish_register_fn(ccx, sym, node_id, llfn);
2095 fn finish_register_fn(ccx: &CrateContext, sym: String, node_id: ast::NodeId,
2097 ccx.item_symbols().borrow_mut().insert(node_id, sym);
2099 // The stack exhaustion lang item shouldn't have a split stack because
2100 // otherwise it would continue to be exhausted (bad), and both it and the
2101 // eh_personality functions need to be externally linkable.
2102 let def = ast_util::local_def(node_id);
2103 if ccx.tcx().lang_items.stack_exhausted() == Some(def) {
2104 attributes::split_stack(llfn, false);
2105 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2107 if ccx.tcx().lang_items.eh_personality() == Some(def) {
2108 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2112 fn register_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2115 node_id: ast::NodeId,
2116 node_type: Ty<'tcx>)
2118 if let ty::ty_bare_fn(_, ref f) = node_type.sty {
2119 if f.abi != Rust && f.abi != RustCall {
2120 ccx.sess().span_bug(sp, &format!("only the `{}` or `{}` calling conventions are valid \
2121 for this function; `{}` was specified",
2122 Rust.name(), RustCall.name(), f.abi.name()));
2125 ccx.sess().span_bug(sp, "expected bare rust function")
2128 let llfn = declare::define_rust_fn(ccx, &sym[..], node_type).unwrap_or_else(||{
2129 ccx.sess().span_fatal(sp, &format!("symbol `{}` is already defined", sym));
2131 finish_register_fn(ccx, sym, node_id, llfn);
2135 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2136 match *sess.entry_fn.borrow() {
2137 Some((entry_id, _)) => node_id == entry_id,
2142 /// Create the `main` function which will initialise the rust runtime and call users’ main
2144 pub fn create_entry_wrapper(ccx: &CrateContext,
2146 main_llfn: ValueRef) {
2147 let et = ccx.sess().entry_type.get().unwrap();
2149 config::EntryMain => {
2150 create_entry_fn(ccx, sp, main_llfn, true);
2152 config::EntryStart => create_entry_fn(ccx, sp, 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()],
2163 let llfn = declare::define_cfn(ccx, "main", llfty,
2164 ty::mk_nil(ccx.tcx())).unwrap_or_else(||{
2165 ccx.sess().span_err(sp, "entry symbol `main` defined multiple times");
2166 // FIXME: We should be smart and show a better diagnostic here.
2167 ccx.sess().help("did you use #[no_mangle] on `fn main`? Use #[start] instead");
2168 ccx.sess().abort_if_errors();
2172 // FIXME: #16581: Marking a symbol in the executable with `dllexport`
2173 // linkage forces MinGW's linker to output a `.reloc` section for ASLR
2174 if ccx.sess().target.target.options.is_like_windows {
2175 unsafe { llvm::LLVMRustSetDLLExportStorageClass(llfn) }
2179 llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn,
2180 "top\0".as_ptr() as *const _)
2182 let bld = ccx.raw_builder();
2184 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2186 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx);
2188 let (start_fn, args) = if use_start_lang_item {
2189 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2191 Err(s) => { ccx.sess().fatal(&s[..]); }
2193 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2194 get_item_val(ccx, start_def_id.node)
2196 let start_fn_type = csearch::get_type(ccx.tcx(),
2198 trans_external_path(ccx, start_def_id, start_fn_type)
2202 let opaque_rust_main = llvm::LLVMBuildPointerCast(bld,
2203 rust_main, Type::i8p(ccx).to_ref(),
2204 "rust_main\0".as_ptr() as *const _);
2214 debug!("using user-defined start fn");
2216 get_param(llfn, 0 as c_uint),
2217 get_param(llfn, 1 as c_uint)
2223 let result = llvm::LLVMBuildCall(bld,
2226 args.len() as c_uint,
2229 llvm::LLVMBuildRet(bld, result);
2234 fn exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, id: ast::NodeId,
2235 ty: Ty<'tcx>, attrs: &[ast::Attribute]) -> String {
2236 match ccx.external_srcs().borrow().get(&id) {
2238 let sym = csearch::get_symbol(&ccx.sess().cstore, did);
2239 debug!("found item {} in other crate...", sym);
2245 match attr::find_export_name_attr(ccx.sess().diagnostic(), attrs) {
2246 // Use provided name
2247 Some(name) => name.to_string(),
2248 _ => ccx.tcx().map.with_path(id, |path| {
2249 if attr::contains_name(attrs, "no_mangle") {
2251 path.last().unwrap().to_string()
2253 match weak_lang_items::link_name(attrs) {
2254 Some(name) => name.to_string(),
2256 // Usual name mangling
2257 mangle_exported_name(ccx, path, ty, id)
2265 fn contains_null(s: &str) -> bool {
2266 s.bytes().any(|b| b == 0)
2269 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2270 debug!("get_item_val(id=`{}`)", id);
2272 match ccx.item_vals().borrow().get(&id).cloned() {
2273 Some(v) => return v,
2277 let item = ccx.tcx().map.get(id);
2278 debug!("get_item_val: id={} item={:?}", id, item);
2279 let val = match item {
2280 ast_map::NodeItem(i) => {
2281 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2282 let sym = || exported_name(ccx, id, ty, &i.attrs);
2284 let v = match i.node {
2285 ast::ItemStatic(_, _, ref expr) => {
2286 // If this static came from an external crate, then
2287 // we need to get the symbol from csearch instead of
2288 // using the current crate's name/version
2289 // information in the hash of the symbol
2291 debug!("making {}", sym);
2293 // We need the translated value here, because for enums the
2294 // LLVM type is not fully determined by the Rust type.
2295 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
2296 let (v, ty) = consts::const_expr(ccx, &**expr, empty_substs);
2297 ccx.static_values().borrow_mut().insert(id, v);
2299 // boolean SSA values are i1, but they have to be stored in i8 slots,
2300 // otherwise some LLVM optimization passes don't work as expected
2301 let llty = if ty::type_is_bool(ty) {
2302 llvm::LLVMInt8TypeInContext(ccx.llcx())
2307 // FIXME(nagisa): probably should be declare_global, because no definition
2308 // is happening here, but we depend on it being defined here from
2309 // const::trans_static. This all logic should be replaced.
2310 let g = declare::define_global(ccx, &sym[..],
2311 Type::from_ref(llty)).unwrap_or_else(||{
2312 ccx.sess().span_fatal(i.span, &format!("symbol `{}` is already defined",
2316 if attr::contains_name(&i.attrs,
2318 llvm::set_thread_local(g, true);
2320 ccx.item_symbols().borrow_mut().insert(i.id, sym);
2325 ast::ItemFn(_, _, abi, _, _) => {
2327 let llfn = if abi == Rust {
2328 register_fn(ccx, i.span, sym, i.id, ty)
2330 foreign::register_rust_fn_with_foreign_abi(ccx, i.span, sym, i.id)
2332 attributes::from_fn_attrs(ccx, &i.attrs, llfn);
2336 _ => ccx.sess().bug("get_item_val: weird result in table")
2339 match attr::first_attr_value_str_by_name(&i.attrs,
2342 if contains_null(§) {
2343 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`",
2347 let buf = CString::new(sect.as_bytes()).unwrap();
2348 llvm::LLVMSetSection(v, buf.as_ptr());
2357 ast_map::NodeTraitItem(trait_item) => {
2358 debug!("get_item_val(): processing a NodeTraitItem");
2359 match trait_item.node {
2360 ast::MethodTraitItem(_, Some(_)) => {
2361 register_method(ccx, id, &trait_item.attrs, trait_item.span)
2364 ccx.sess().span_bug(trait_item.span,
2365 "unexpected variant: trait item other than a provided \
2366 method in get_item_val()");
2371 ast_map::NodeImplItem(impl_item) => {
2372 match impl_item.node {
2373 ast::MethodImplItem(..) => {
2374 register_method(ccx, id, &impl_item.attrs, impl_item.span)
2377 ccx.sess().span_bug(impl_item.span,
2378 "unexpected variant: non-method impl item in \
2384 ast_map::NodeForeignItem(ni) => {
2386 ast::ForeignItemFn(..) => {
2387 let abi = ccx.tcx().map.get_foreign_abi(id);
2388 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2389 let name = foreign::link_name(&*ni);
2390 let llfn = foreign::register_foreign_item_fn(ccx, abi, ty, &name);
2391 attributes::from_fn_attrs(ccx, &ni.attrs, llfn);
2394 ast::ForeignItemStatic(..) => {
2395 foreign::register_static(ccx, &*ni)
2400 ast_map::NodeVariant(ref v) => {
2402 let args = match v.node.kind {
2403 ast::TupleVariantKind(ref args) => args,
2404 ast::StructVariantKind(_) => {
2405 ccx.sess().bug("struct variant kind unexpected in get_item_val")
2408 assert!(!args.is_empty());
2409 let ty = ty::node_id_to_type(ccx.tcx(), id);
2410 let parent = ccx.tcx().map.get_parent(id);
2411 let enm = ccx.tcx().map.expect_item(parent);
2412 let sym = exported_name(ccx,
2417 llfn = match enm.node {
2418 ast::ItemEnum(_, _) => {
2419 register_fn(ccx, (*v).span, sym, id, ty)
2421 _ => ccx.sess().bug("NodeVariant, shouldn't happen")
2423 attributes::inline(llfn, attributes::InlineAttr::Hint);
2427 ast_map::NodeStructCtor(struct_def) => {
2428 // Only register the constructor if this is a tuple-like struct.
2429 let ctor_id = match struct_def.ctor_id {
2431 ccx.sess().bug("attempt to register a constructor of \
2432 a non-tuple-like struct")
2434 Some(ctor_id) => ctor_id,
2436 let parent = ccx.tcx().map.get_parent(id);
2437 let struct_item = ccx.tcx().map.expect_item(parent);
2438 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2439 let sym = exported_name(ccx,
2442 &struct_item.attrs);
2443 let llfn = register_fn(ccx, struct_item.span,
2445 attributes::inline(llfn, attributes::InlineAttr::Hint);
2450 ccx.sess().bug(&format!("get_item_val(): unexpected variant: {:?}",
2455 // All LLVM globals and functions are initially created as external-linkage
2456 // declarations. If `trans_item`/`trans_fn` later turns the declaration
2457 // into a definition, it adjusts the linkage then (using `update_linkage`).
2459 // The exception is foreign items, which have their linkage set inside the
2460 // call to `foreign::register_*` above. We don't touch the linkage after
2461 // that (`foreign::trans_foreign_mod` doesn't adjust the linkage like the
2462 // other item translation functions do).
2464 ccx.item_vals().borrow_mut().insert(id, val);
2468 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2469 attrs: &[ast::Attribute], span: Span) -> ValueRef {
2470 let mty = ty::node_id_to_type(ccx.tcx(), id);
2472 let sym = exported_name(ccx, id, mty, &attrs);
2474 if let ty::ty_bare_fn(_, ref f) = mty.sty {
2475 let llfn = if f.abi == Rust || f.abi == RustCall {
2476 register_fn(ccx, span, sym, id, mty)
2478 foreign::register_rust_fn_with_foreign_abi(ccx, span, sym, id)
2480 attributes::from_fn_attrs(ccx, &attrs, llfn);
2483 ccx.sess().span_bug(span, "expected bare rust function");
2487 pub fn crate_ctxt_to_encode_parms<'a, 'tcx>(cx: &'a SharedCrateContext<'tcx>,
2488 ie: encoder::EncodeInlinedItem<'a>)
2489 -> encoder::EncodeParams<'a, 'tcx> {
2490 encoder::EncodeParams {
2491 diag: cx.sess().diagnostic(),
2493 reexports: cx.export_map(),
2494 item_symbols: cx.item_symbols(),
2495 link_meta: cx.link_meta(),
2496 cstore: &cx.sess().cstore,
2497 encode_inlined_item: ie,
2498 reachable: cx.reachable(),
2502 pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
2505 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2506 *ty != config::CrateTypeExecutable
2512 let encode_inlined_item: encoder::EncodeInlinedItem =
2513 Box::new(|ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii));
2515 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2516 let metadata = encoder::encode_metadata(encode_parms, krate);
2517 let mut compressed = encoder::metadata_encoding_version.to_vec();
2518 compressed.push_all(&flate::deflate_bytes(&metadata));
2519 let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
2520 let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
2521 let name = format!("rust_metadata_{}_{}",
2522 cx.link_meta().crate_name,
2523 cx.link_meta().crate_hash);
2524 let buf = CString::new(name).unwrap();
2525 let llglobal = unsafe {
2526 llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(),
2530 llvm::LLVMSetInitializer(llglobal, llconst);
2531 let name = loader::meta_section_name(&cx.sess().target.target);
2532 let name = CString::new(name).unwrap();
2533 llvm::LLVMSetSection(llglobal, name.as_ptr())
2538 /// Find any symbols that are defined in one compilation unit, but not declared
2539 /// in any other compilation unit. Give these symbols internal linkage.
2540 fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
2542 let mut declared = HashSet::new();
2544 let iter_globals = |llmod| {
2546 cur: llvm::LLVMGetFirstGlobal(llmod),
2547 step: llvm::LLVMGetNextGlobal,
2551 let iter_functions = |llmod| {
2553 cur: llvm::LLVMGetFirstFunction(llmod),
2554 step: llvm::LLVMGetNextFunction,
2558 // Collect all external declarations in all compilation units.
2559 for ccx in cx.iter() {
2560 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2561 let linkage = llvm::LLVMGetLinkage(val);
2562 // We only care about external declarations (not definitions)
2563 // and available_externally definitions.
2564 if !(linkage == llvm::ExternalLinkage as c_uint &&
2565 llvm::LLVMIsDeclaration(val) != 0) &&
2566 !(linkage == llvm::AvailableExternallyLinkage as c_uint) {
2570 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2571 .to_bytes().to_vec();
2572 declared.insert(name);
2576 // Examine each external definition. If the definition is not used in
2577 // any other compilation unit, and is not reachable from other crates,
2578 // then give it internal linkage.
2579 for ccx in cx.iter() {
2580 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2581 // We only care about external definitions.
2582 if !(llvm::LLVMGetLinkage(val) == llvm::ExternalLinkage as c_uint &&
2583 llvm::LLVMIsDeclaration(val) == 0) {
2587 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2588 .to_bytes().to_vec();
2589 if !declared.contains(&name) &&
2590 !reachable.contains(str::from_utf8(&name).unwrap()) {
2591 llvm::SetLinkage(val, llvm::InternalLinkage);
2600 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
2603 impl Iterator for ValueIter {
2604 type Item = ValueRef;
2606 fn next(&mut self) -> Option<ValueRef> {
2610 let step: unsafe extern "C" fn(ValueRef) -> ValueRef =
2611 mem::transmute_copy(&self.step);
2622 pub fn trans_crate<'tcx>(analysis: ty::CrateAnalysis<'tcx>)
2623 -> (ty::ctxt<'tcx>, CrateTranslation) {
2624 let ty::CrateAnalysis { ty_cx: tcx, export_map, reachable, name, .. } = analysis;
2625 let krate = tcx.map.krate();
2627 let check_overflow = if let Some(v) = tcx.sess.opts.debugging_opts.force_overflow_checks {
2630 tcx.sess.opts.debug_assertions
2633 let check_dropflag = if let Some(v) = tcx.sess.opts.debugging_opts.force_dropflag_checks {
2636 tcx.sess.opts.debug_assertions
2639 // Before we touch LLVM, make sure that multithreading is enabled.
2641 use std::sync::{Once, ONCE_INIT};
2642 static INIT: Once = ONCE_INIT;
2643 static mut POISONED: bool = false;
2645 if llvm::LLVMStartMultithreaded() != 1 {
2646 // use an extra bool to make sure that all future usage of LLVM
2647 // cannot proceed despite the Once not running more than once.
2653 tcx.sess.bug("couldn't enable multi-threaded LLVM");
2657 let link_meta = link::build_link_meta(&tcx.sess, krate, name);
2659 let codegen_units = tcx.sess.opts.cg.codegen_units;
2660 let shared_ccx = SharedCrateContext::new(&link_meta.crate_name,
2671 let ccx = shared_ccx.get_ccx(0);
2673 // First, verify intrinsics.
2674 intrinsic::check_intrinsics(&ccx);
2676 // Next, translate the module.
2678 let _icx = push_ctxt("text");
2679 trans_mod(&ccx, &krate.module);
2683 for ccx in shared_ccx.iter() {
2684 if ccx.sess().opts.debuginfo != NoDebugInfo {
2685 debuginfo::finalize(&ccx);
2689 // Translate the metadata.
2690 let metadata = write_metadata(&shared_ccx, krate);
2692 if shared_ccx.sess().trans_stats() {
2693 let stats = shared_ccx.stats();
2694 println!("--- trans stats ---");
2695 println!("n_glues_created: {}", stats.n_glues_created.get());
2696 println!("n_null_glues: {}", stats.n_null_glues.get());
2697 println!("n_real_glues: {}", stats.n_real_glues.get());
2699 println!("n_fns: {}", stats.n_fns.get());
2700 println!("n_monos: {}", stats.n_monos.get());
2701 println!("n_inlines: {}", stats.n_inlines.get());
2702 println!("n_closures: {}", stats.n_closures.get());
2703 println!("fn stats:");
2704 stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
2705 insns_b.cmp(&insns_a)
2707 for tuple in &*stats.fn_stats.borrow() {
2709 (ref name, insns) => {
2710 println!("{} insns, {}", insns, *name);
2715 if shared_ccx.sess().count_llvm_insns() {
2716 for (k, v) in &*shared_ccx.stats().llvm_insns.borrow() {
2717 println!("{:7} {}", *v, *k);
2721 let modules = shared_ccx.iter()
2722 .map(|ccx| ModuleTranslation { llcx: ccx.llcx(), llmod: ccx.llmod() })
2725 let mut reachable: Vec<String> = shared_ccx.reachable().iter().filter_map(|id| {
2726 shared_ccx.item_symbols().borrow().get(id).map(|s| s.to_string())
2729 // For the purposes of LTO, we add to the reachable set all of the upstream
2730 // reachable extern fns. These functions are all part of the public ABI of
2731 // the final product, so LTO needs to preserve them.
2732 shared_ccx.sess().cstore.iter_crate_data(|cnum, _| {
2733 let syms = csearch::get_reachable_extern_fns(&shared_ccx.sess().cstore, cnum);
2734 reachable.extend(syms.into_iter().map(|did| {
2735 csearch::get_symbol(&shared_ccx.sess().cstore, did)
2739 // Make sure that some other crucial symbols are not eliminated from the
2740 // module. This includes the main function, the crate map (used for debug
2741 // log settings and I/O), and finally the curious rust_stack_exhausted
2742 // symbol. This symbol is required for use by the libmorestack library that
2743 // we link in, so we must ensure that this symbol is not internalized (if
2744 // defined in the crate).
2745 reachable.push("main".to_string());
2746 reachable.push("rust_stack_exhausted".to_string());
2748 // referenced from .eh_frame section on some platforms
2749 reachable.push("rust_eh_personality".to_string());
2750 // referenced from rt/rust_try.ll
2751 reachable.push("rust_eh_personality_catch".to_string());
2753 if codegen_units > 1 {
2754 internalize_symbols(&shared_ccx, &reachable.iter().cloned().collect());
2757 let metadata_module = ModuleTranslation {
2758 llcx: shared_ccx.metadata_llcx(),
2759 llmod: shared_ccx.metadata_llmod(),
2761 let formats = shared_ccx.tcx().dependency_formats.borrow().clone();
2762 let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
2764 let translation = CrateTranslation {
2766 metadata_module: metadata_module,
2769 reachable: reachable,
2770 crate_formats: formats,
2771 no_builtins: no_builtins,
2774 (shared_ccx.take_tcx(), translation)