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, t, &name[..]);
674 let attrs = csearch::get_item_attrs(&ccx.sess().cstore, did);
675 attributes::from_fn_attrs(ccx, &attrs, llfn);
681 get_extern_const(ccx, did, t)
686 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
691 -> (ValueRef, Block<'blk, 'tcx>) {
692 let _icx = push_ctxt("invoke_");
693 if bcx.unreachable.get() {
694 return (C_null(Type::i8(bcx.ccx())), bcx);
697 let attributes = attributes::from_fn_type(bcx.ccx(), fn_ty);
699 match bcx.opt_node_id {
701 debug!("invoke at ???");
704 debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
708 if need_invoke(bcx) {
709 debug!("invoking {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
710 for &llarg in llargs {
711 debug!("arg: {}", bcx.val_to_string(llarg));
713 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
714 let landing_pad = bcx.fcx.get_landing_pad();
716 let llresult = Invoke(bcx,
723 return (llresult, normal_bcx);
725 debug!("calling {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
726 for &llarg in llargs {
727 debug!("arg: {}", bcx.val_to_string(llarg));
730 let llresult = Call(bcx,
735 return (llresult, bcx);
739 pub fn need_invoke(bcx: Block) -> bool {
740 if bcx.sess().no_landing_pads() {
744 // Avoid using invoke if we are already inside a landing pad.
749 bcx.fcx.needs_invoke()
752 pub fn load_if_immediate<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
753 v: ValueRef, t: Ty<'tcx>) -> ValueRef {
754 let _icx = push_ctxt("load_if_immediate");
755 if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
759 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
760 /// differs from the type used for SSA values. Also handles various special cases where the type
761 /// gives us better information about what we are loading.
762 pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
763 ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
764 if cx.unreachable.get() || type_is_zero_size(cx.ccx(), t) {
765 return C_undef(type_of::type_of(cx.ccx(), t));
768 let ptr = to_arg_ty_ptr(cx, ptr, t);
769 let align = type_of::align_of(cx.ccx(), t);
771 if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
772 let load = Load(cx, ptr);
774 llvm::LLVMSetAlignment(load, align);
780 let global = llvm::LLVMIsAGlobalVariable(ptr);
781 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
782 let val = llvm::LLVMGetInitializer(global);
784 return from_arg_ty(cx, val, t);
789 let val = if ty::type_is_bool(t) {
790 LoadRangeAssert(cx, ptr, 0, 2, llvm::False)
791 } else if ty::type_is_char(t) {
792 // a char is a Unicode codepoint, and so takes values from 0
793 // to 0x10FFFF inclusive only.
794 LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
795 } else if (ty::type_is_region_ptr(t) || ty::type_is_unique(t))
796 && !common::type_is_fat_ptr(cx.tcx(), t) {
803 llvm::LLVMSetAlignment(val, align);
806 from_arg_ty(cx, val, t)
809 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
810 /// differs from the type used for SSA values.
811 pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
812 if cx.unreachable.get() {
816 let store = Store(cx, to_arg_ty(cx, v, t), to_arg_ty_ptr(cx, dst, t));
818 llvm::LLVMSetAlignment(store, type_of::align_of(cx.ccx(), t));
822 pub fn to_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
823 if ty::type_is_bool(ty) {
824 ZExt(bcx, val, Type::i8(bcx.ccx()))
830 pub fn from_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
831 if ty::type_is_bool(ty) {
832 Trunc(bcx, val, Type::i1(bcx.ccx()))
838 pub fn to_arg_ty_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef, ty: Ty<'tcx>) -> ValueRef {
839 if type_is_immediate(bcx.ccx(), ty) && type_of::type_of(bcx.ccx(), ty).is_aggregate() {
840 // We want to pass small aggregates as immediate values, but using an aggregate LLVM type
841 // for this leads to bad optimizations, so its arg type is an appropriately sized integer
842 // and we have to convert it
843 BitCast(bcx, ptr, type_of::arg_type_of(bcx.ccx(), ty).ptr_to())
849 pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &ast::Local)
850 -> Block<'blk, 'tcx> {
851 debug!("init_local(bcx={}, local.id={})", bcx.to_str(), local.id);
852 let _indenter = indenter();
853 let _icx = push_ctxt("init_local");
854 _match::store_local(bcx, local)
857 pub fn raw_block<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
860 -> Block<'blk, 'tcx> {
861 common::BlockS::new(llbb, is_lpad, None, fcx)
864 pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
867 -> Block<'blk, 'tcx> where
868 F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>,
870 let _icx = push_ctxt("with_cond");
872 if bcx.unreachable.get() ||
873 (common::is_const(val) && common::const_to_uint(val) == 0) {
878 let next_cx = fcx.new_temp_block("next");
879 let cond_cx = fcx.new_temp_block("cond");
880 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb, DebugLoc::None);
881 let after_cx = f(cond_cx);
882 if !after_cx.terminated.get() {
883 Br(after_cx, next_cx.llbb, DebugLoc::None);
888 pub fn call_lifetime_start(cx: Block, ptr: ValueRef) {
889 if cx.sess().opts.optimize == config::No {
893 let _icx = push_ctxt("lifetime_start");
896 let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
897 let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
898 let lifetime_start = ccx.get_intrinsic(&"llvm.lifetime.start");
899 Call(cx, lifetime_start, &[llsize, ptr], None, DebugLoc::None);
902 pub fn call_lifetime_end(cx: Block, ptr: ValueRef) {
903 if cx.sess().opts.optimize == config::No {
907 let _icx = push_ctxt("lifetime_end");
910 let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
911 let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
912 let lifetime_end = ccx.get_intrinsic(&"llvm.lifetime.end");
913 Call(cx, lifetime_end, &[llsize, ptr], None, DebugLoc::None);
916 pub fn call_memcpy(cx: Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
917 let _icx = push_ctxt("call_memcpy");
919 let key = match &ccx.sess().target.target.target_pointer_width[..] {
920 "32" => "llvm.memcpy.p0i8.p0i8.i32",
921 "64" => "llvm.memcpy.p0i8.p0i8.i64",
922 tws => panic!("Unsupported target word size for memcpy: {}", tws),
924 let memcpy = ccx.get_intrinsic(&key);
925 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
926 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
927 let size = IntCast(cx, n_bytes, ccx.int_type());
928 let align = C_i32(ccx, align as i32);
929 let volatile = C_bool(ccx, false);
930 Call(cx, memcpy, &[dst_ptr, src_ptr, size, align, volatile], None, DebugLoc::None);
933 pub fn memcpy_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
934 dst: ValueRef, src: ValueRef,
936 let _icx = push_ctxt("memcpy_ty");
938 if ty::type_is_structural(t) {
939 let llty = type_of::type_of(ccx, t);
940 let llsz = llsize_of(ccx, llty);
941 let llalign = type_of::align_of(ccx, t);
942 call_memcpy(bcx, dst, src, llsz, llalign as u32);
944 store_ty(bcx, load_ty(bcx, src, t), dst, t);
948 pub fn drop_done_fill_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
949 if cx.unreachable.get() { return; }
950 let _icx = push_ctxt("drop_done_fill_mem");
952 memfill(&B(bcx), llptr, t, adt::DTOR_DONE);
955 pub fn init_zero_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
956 if cx.unreachable.get() { return; }
957 let _icx = push_ctxt("init_zero_mem");
959 memfill(&B(bcx), llptr, t, 0);
962 // Always use this function instead of storing a constant byte to the memory
963 // in question. e.g. if you store a zero constant, LLVM will drown in vreg
964 // allocation for large data structures, and the generated code will be
965 // awful. (A telltale sign of this is large quantities of
966 // `mov [byte ptr foo],0` in the generated code.)
967 fn memfill<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>, byte: u8) {
968 let _icx = push_ctxt("memfill");
971 let llty = type_of::type_of(ccx, ty);
973 let intrinsic_key = match &ccx.sess().target.target.target_pointer_width[..] {
974 "32" => "llvm.memset.p0i8.i32",
975 "64" => "llvm.memset.p0i8.i64",
976 tws => panic!("Unsupported target word size for memset: {}", tws),
979 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
980 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
981 let llzeroval = C_u8(ccx, byte as usize);
982 let size = machine::llsize_of(ccx, llty);
983 let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
984 let volatile = C_bool(ccx, false);
985 b.call(llintrinsicfn, &[llptr, llzeroval, size, align, volatile], None);
988 pub fn alloc_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, name: &str) -> ValueRef {
989 let _icx = push_ctxt("alloc_ty");
991 let ty = type_of::type_of(ccx, t);
992 assert!(!ty::type_has_params(t));
993 let val = alloca(bcx, ty, name);
997 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
998 let p = alloca_no_lifetime(cx, ty, name);
999 call_lifetime_start(cx, p);
1003 pub fn alloca_no_lifetime(cx: Block, ty: Type, name: &str) -> ValueRef {
1004 let _icx = push_ctxt("alloca");
1005 if cx.unreachable.get() {
1007 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1010 debuginfo::clear_source_location(cx.fcx);
1011 Alloca(cx, ty, name)
1014 // Creates the alloca slot which holds the pointer to the slot for the final return value
1015 pub fn make_return_slot_pointer<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1016 output_type: Ty<'tcx>) -> ValueRef {
1017 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1019 // We create an alloca to hold a pointer of type `output_type`
1020 // which will hold the pointer to the right alloca which has the
1022 if fcx.needs_ret_allocas {
1023 // Let's create the stack slot
1024 let slot = AllocaFcx(fcx, lloutputtype.ptr_to(), "llretslotptr");
1026 // and if we're using an out pointer, then store that in our newly made slot
1027 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1028 let outptr = get_param(fcx.llfn, 0);
1030 let b = fcx.ccx.builder();
1031 b.position_before(fcx.alloca_insert_pt.get().unwrap());
1032 b.store(outptr, slot);
1037 // But if there are no nested returns, we skip the indirection and have a single
1040 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1041 get_param(fcx.llfn, 0)
1043 AllocaFcx(fcx, lloutputtype, "sret_slot")
1048 struct FindNestedReturn {
1052 impl FindNestedReturn {
1053 fn new() -> FindNestedReturn {
1054 FindNestedReturn { found: false }
1058 impl<'v> Visitor<'v> for FindNestedReturn {
1059 fn visit_expr(&mut self, e: &ast::Expr) {
1061 ast::ExprRet(..) => {
1064 _ => visit::walk_expr(self, e)
1069 fn build_cfg(tcx: &ty::ctxt, id: ast::NodeId) -> (ast::NodeId, Option<cfg::CFG>) {
1070 let blk = match tcx.map.find(id) {
1071 Some(ast_map::NodeItem(i)) => {
1073 ast::ItemFn(_, _, _, _, ref blk) => {
1076 _ => tcx.sess.bug("unexpected item variant in has_nested_returns")
1079 Some(ast_map::NodeTraitItem(trait_item)) => {
1080 match trait_item.node {
1081 ast::MethodTraitItem(_, Some(ref body)) => body,
1083 tcx.sess.bug("unexpected variant: trait item other than a \
1084 provided method in has_nested_returns")
1088 Some(ast_map::NodeImplItem(impl_item)) => {
1089 match impl_item.node {
1090 ast::MethodImplItem(_, ref body) => body,
1092 tcx.sess.bug("unexpected variant: non-method impl item in \
1093 has_nested_returns")
1097 Some(ast_map::NodeExpr(e)) => {
1099 ast::ExprClosure(_, _, ref blk) => blk,
1100 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns")
1103 Some(ast_map::NodeVariant(..)) |
1104 Some(ast_map::NodeStructCtor(..)) => return (ast::DUMMY_NODE_ID, None),
1107 None if id == ast::DUMMY_NODE_ID => return (ast::DUMMY_NODE_ID, None),
1109 _ => tcx.sess.bug(&format!("unexpected variant in has_nested_returns: {}",
1110 tcx.map.path_to_string(id)))
1113 (blk.id, Some(cfg::CFG::new(tcx, blk)))
1116 // Checks for the presence of "nested returns" in a function.
1117 // Nested returns are when the inner expression of a return expression
1118 // (the 'expr' in 'return expr') contains a return expression. Only cases
1119 // where the outer return is actually reachable are considered. Implicit
1120 // returns from the end of blocks are considered as well.
1122 // This check is needed to handle the case where the inner expression is
1123 // part of a larger expression that may have already partially-filled the
1124 // return slot alloca. This can cause errors related to clean-up due to
1125 // the clobbering of the existing value in the return slot.
1126 fn has_nested_returns(tcx: &ty::ctxt, cfg: &cfg::CFG, blk_id: ast::NodeId) -> bool {
1127 for n in cfg.graph.depth_traverse(cfg.entry) {
1128 match tcx.map.find(n.id()) {
1129 Some(ast_map::NodeExpr(ex)) => {
1130 if let ast::ExprRet(Some(ref ret_expr)) = ex.node {
1131 let mut visitor = FindNestedReturn::new();
1132 visit::walk_expr(&mut visitor, &**ret_expr);
1138 Some(ast_map::NodeBlock(blk)) if blk.id == blk_id => {
1139 let mut visitor = FindNestedReturn::new();
1140 visit::walk_expr_opt(&mut visitor, &blk.expr);
1152 // NB: must keep 4 fns in sync:
1155 // - create_datums_for_fn_args.
1159 // Be warned! You must call `init_function` before doing anything with the
1160 // returned function context.
1161 pub fn new_fn_ctxt<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
1165 output_type: ty::FnOutput<'tcx>,
1166 param_substs: &'tcx Substs<'tcx>,
1168 block_arena: &'a TypedArena<common::BlockS<'a, 'tcx>>)
1169 -> FunctionContext<'a, 'tcx> {
1170 common::validate_substs(param_substs);
1172 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1176 ccx.tcx().map.path_to_string(id).to_string()
1178 id, param_substs.repr(ccx.tcx()));
1180 let uses_outptr = match output_type {
1181 ty::FnConverging(output_type) => {
1182 let substd_output_type =
1183 monomorphize::apply_param_substs(ccx.tcx(), param_substs, &output_type);
1184 type_of::return_uses_outptr(ccx, substd_output_type)
1186 ty::FnDiverging => false
1188 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1189 let (blk_id, cfg) = build_cfg(ccx.tcx(), id);
1190 let nested_returns = if let Some(ref cfg) = cfg {
1191 has_nested_returns(ccx.tcx(), cfg, blk_id)
1196 let mut fcx = FunctionContext {
1199 llretslotptr: Cell::new(None),
1200 param_env: ty::empty_parameter_environment(ccx.tcx()),
1201 alloca_insert_pt: Cell::new(None),
1202 llreturn: Cell::new(None),
1203 needs_ret_allocas: nested_returns,
1204 personality: Cell::new(None),
1205 caller_expects_out_pointer: uses_outptr,
1206 lllocals: RefCell::new(NodeMap()),
1207 llupvars: RefCell::new(NodeMap()),
1209 param_substs: param_substs,
1211 block_arena: block_arena,
1213 debug_context: debug_context,
1214 scopes: RefCell::new(Vec::new()),
1219 fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1225 /// Performs setup on a newly created function, creating the entry scope block
1226 /// and allocating space for the return pointer.
1227 pub fn init_function<'a, 'tcx>(fcx: &'a FunctionContext<'a, 'tcx>,
1229 output: ty::FnOutput<'tcx>)
1230 -> Block<'a, 'tcx> {
1231 let entry_bcx = fcx.new_temp_block("entry-block");
1233 // Use a dummy instruction as the insertion point for all allocas.
1234 // This is later removed in FunctionContext::cleanup.
1235 fcx.alloca_insert_pt.set(Some(unsafe {
1236 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1237 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1240 if let ty::FnConverging(output_type) = output {
1241 // This shouldn't need to recompute the return type,
1242 // as new_fn_ctxt did it already.
1243 let substd_output_type = fcx.monomorphize(&output_type);
1244 if !return_type_is_void(fcx.ccx, substd_output_type) {
1245 // If the function returns nil/bot, there is no real return
1246 // value, so do not set `llretslotptr`.
1247 if !skip_retptr || fcx.caller_expects_out_pointer {
1248 // Otherwise, we normally allocate the llretslotptr, unless we
1249 // have been instructed to skip it for immediate return
1251 fcx.llretslotptr.set(Some(make_return_slot_pointer(fcx, substd_output_type)));
1259 // NB: must keep 4 fns in sync:
1262 // - create_datums_for_fn_args.
1266 pub fn arg_kind<'a, 'tcx>(cx: &FunctionContext<'a, 'tcx>, t: Ty<'tcx>)
1268 use trans::datum::{ByRef, ByValue};
1271 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1275 // work around bizarre resolve errors
1276 pub type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
1278 // create_datums_for_fn_args: creates rvalue datums for each of the
1279 // incoming function arguments. These will later be stored into
1280 // appropriate lvalue datums.
1281 pub fn create_datums_for_fn_args<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1282 arg_tys: &[Ty<'tcx>])
1283 -> Vec<RvalueDatum<'tcx>> {
1284 let _icx = push_ctxt("create_datums_for_fn_args");
1286 // Return an array wrapping the ValueRefs that we get from `get_param` for
1287 // each argument into datums.
1288 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1289 let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1290 datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1294 /// Creates rvalue datums for each of the incoming function arguments and
1295 /// tuples the arguments. These will later be stored into appropriate lvalue
1298 /// FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1299 fn create_datums_for_fn_args_under_call_abi<'blk, 'tcx>(
1300 mut bcx: Block<'blk, 'tcx>,
1301 arg_scope: cleanup::CustomScopeIndex,
1302 arg_tys: &[Ty<'tcx>])
1303 -> Vec<RvalueDatum<'tcx>> {
1304 let mut result = Vec::new();
1305 for (i, &arg_ty) in arg_tys.iter().enumerate() {
1306 if i < arg_tys.len() - 1 {
1307 // Regular argument.
1308 let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1309 result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1314 // This is the last argument. Tuple it.
1316 ty::ty_tup(ref tupled_arg_tys) => {
1317 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1320 datum::lvalue_scratch_datum(bcx,
1323 tuple_args_scope_id,
1328 for (j, &tupled_arg_ty) in
1329 tupled_arg_tys.iter().enumerate() {
1331 get_param(bcx.fcx.llfn,
1332 bcx.fcx.arg_pos(i + j) as c_uint);
1333 let lldest = GEPi(bcx, llval, &[0, j]);
1334 let datum = datum::Datum::new(
1337 arg_kind(bcx.fcx, tupled_arg_ty));
1338 bcx = datum.store_to(bcx, lldest);
1342 let tuple = unpack_datum!(bcx,
1343 tuple.to_expr_datum()
1344 .to_rvalue_datum(bcx,
1349 bcx.tcx().sess.bug("last argument of a function with \
1350 `rust-call` ABI isn't a tuple?!")
1359 fn copy_args_to_allocas<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1360 arg_scope: cleanup::CustomScopeIndex,
1362 arg_datums: Vec<RvalueDatum<'tcx>>)
1363 -> Block<'blk, 'tcx> {
1364 debug!("copy_args_to_allocas");
1366 let _icx = push_ctxt("copy_args_to_allocas");
1369 let arg_scope_id = cleanup::CustomScope(arg_scope);
1371 for (i, arg_datum) in arg_datums.into_iter().enumerate() {
1372 // For certain mode/type combinations, the raw llarg values are passed
1373 // by value. However, within the fn body itself, we want to always
1374 // have all locals and arguments be by-ref so that we can cancel the
1375 // cleanup and for better interaction with LLVM's debug info. So, if
1376 // the argument would be passed by value, we store it into an alloca.
1377 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1378 // the event it's not truly needed.
1380 bcx = _match::store_arg(bcx, &*args[i].pat, arg_datum, arg_scope_id);
1381 debuginfo::create_argument_metadata(bcx, &args[i]);
1387 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1388 // and builds the return block.
1389 pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1390 last_bcx: Block<'blk, 'tcx>,
1391 retty: ty::FnOutput<'tcx>,
1392 ret_debug_loc: DebugLoc) {
1393 let _icx = push_ctxt("finish_fn");
1395 let ret_cx = match fcx.llreturn.get() {
1397 if !last_bcx.terminated.get() {
1398 Br(last_bcx, llreturn, DebugLoc::None);
1400 raw_block(fcx, false, llreturn)
1405 // This shouldn't need to recompute the return type,
1406 // as new_fn_ctxt did it already.
1407 let substd_retty = fcx.monomorphize(&retty);
1408 build_return_block(fcx, ret_cx, substd_retty, ret_debug_loc);
1410 debuginfo::clear_source_location(fcx);
1414 // Builds the return block for a function.
1415 pub fn build_return_block<'blk, 'tcx>(fcx: &FunctionContext<'blk, 'tcx>,
1416 ret_cx: Block<'blk, 'tcx>,
1417 retty: ty::FnOutput<'tcx>,
1418 ret_debug_location: DebugLoc) {
1419 if fcx.llretslotptr.get().is_none() ||
1420 (!fcx.needs_ret_allocas && fcx.caller_expects_out_pointer) {
1421 return RetVoid(ret_cx, ret_debug_location);
1424 let retslot = if fcx.needs_ret_allocas {
1425 Load(ret_cx, fcx.llretslotptr.get().unwrap())
1427 fcx.llretslotptr.get().unwrap()
1429 let retptr = Value(retslot);
1430 match retptr.get_dominating_store(ret_cx) {
1431 // If there's only a single store to the ret slot, we can directly return
1432 // the value that was stored and omit the store and the alloca
1434 let retval = s.get_operand(0).unwrap().get();
1435 s.erase_from_parent();
1437 if retptr.has_no_uses() {
1438 retptr.erase_from_parent();
1441 let retval = if retty == ty::FnConverging(fcx.ccx.tcx().types.bool) {
1442 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1447 if fcx.caller_expects_out_pointer {
1448 if let ty::FnConverging(retty) = retty {
1449 store_ty(ret_cx, retval, get_param(fcx.llfn, 0), retty);
1451 RetVoid(ret_cx, ret_debug_location)
1453 Ret(ret_cx, retval, ret_debug_location)
1456 // Otherwise, copy the return value to the ret slot
1457 None => match retty {
1458 ty::FnConverging(retty) => {
1459 if fcx.caller_expects_out_pointer {
1460 memcpy_ty(ret_cx, get_param(fcx.llfn, 0), retslot, retty);
1461 RetVoid(ret_cx, ret_debug_location)
1463 Ret(ret_cx, load_ty(ret_cx, retslot, retty), ret_debug_location)
1466 ty::FnDiverging => {
1467 if fcx.caller_expects_out_pointer {
1468 RetVoid(ret_cx, ret_debug_location)
1470 Ret(ret_cx, C_undef(Type::nil(fcx.ccx)), ret_debug_location)
1477 /// Builds an LLVM function out of a source function.
1479 /// If the function closes over its environment a closure will be returned.
1480 pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1484 param_substs: &'tcx Substs<'tcx>,
1485 fn_ast_id: ast::NodeId,
1486 _attributes: &[ast::Attribute],
1487 output_type: ty::FnOutput<'tcx>,
1489 closure_env: closure::ClosureEnv<'b>) {
1490 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1492 let _icx = push_ctxt("trans_closure");
1493 attributes::emit_uwtable(llfndecl, true);
1495 debug!("trans_closure(..., param_substs={})",
1496 param_substs.repr(ccx.tcx()));
1498 let has_env = match closure_env {
1499 closure::ClosureEnv::Closure(_) => true,
1500 closure::ClosureEnv::NotClosure => false,
1503 let (arena, fcx): (TypedArena<_>, FunctionContext);
1504 arena = TypedArena::new();
1505 fcx = new_fn_ctxt(ccx,
1513 let mut bcx = init_function(&fcx, false, output_type);
1515 // cleanup scope for the incoming arguments
1516 let fn_cleanup_debug_loc =
1517 debuginfo::get_cleanup_debug_loc_for_ast_node(ccx, fn_ast_id, body.span, true);
1518 let arg_scope = fcx.push_custom_cleanup_scope_with_debug_loc(fn_cleanup_debug_loc);
1520 let block_ty = node_id_type(bcx, body.id);
1522 // Set up arguments to the function.
1523 let monomorphized_arg_types =
1525 .map(|arg| node_id_type(bcx, arg.id))
1526 .collect::<Vec<_>>();
1527 let monomorphized_arg_types = match closure_env {
1528 closure::ClosureEnv::NotClosure => {
1529 monomorphized_arg_types
1532 // Tuple up closure argument types for the "rust-call" ABI.
1533 closure::ClosureEnv::Closure(_) => {
1534 vec![ty::mk_tup(ccx.tcx(), monomorphized_arg_types)]
1537 for monomorphized_arg_type in &monomorphized_arg_types {
1538 debug!("trans_closure: monomorphized_arg_type: {}",
1539 ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1541 debug!("trans_closure: function lltype: {}",
1542 bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
1544 let arg_datums = match closure_env {
1545 closure::ClosureEnv::NotClosure if abi == RustCall => {
1546 create_datums_for_fn_args_under_call_abi(bcx, arg_scope, &monomorphized_arg_types[..])
1549 let arg_tys = untuple_arguments_if_necessary(ccx, &monomorphized_arg_types, abi);
1550 create_datums_for_fn_args(&fcx, &arg_tys)
1554 bcx = copy_args_to_allocas(bcx, arg_scope, &decl.inputs, arg_datums);
1556 bcx = closure_env.load(bcx, cleanup::CustomScope(arg_scope));
1558 // Up until here, IR instructions for this function have explicitly not been annotated with
1559 // source code location, so we don't step into call setup code. From here on, source location
1560 // emitting should be enabled.
1561 debuginfo::start_emitting_source_locations(&fcx);
1563 let dest = match fcx.llretslotptr.get() {
1564 Some(_) => expr::SaveIn(fcx.get_ret_slot(bcx, ty::FnConverging(block_ty), "iret_slot")),
1566 assert!(type_is_zero_size(bcx.ccx(), block_ty));
1571 // This call to trans_block is the place where we bridge between
1572 // translation calls that don't have a return value (trans_crate,
1573 // trans_mod, trans_item, et cetera) and those that do
1574 // (trans_block, trans_expr, et cetera).
1575 bcx = controlflow::trans_block(bcx, body, dest);
1578 expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1579 Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1584 match fcx.llreturn.get() {
1586 Br(bcx, fcx.return_exit_block(), DebugLoc::None);
1587 fcx.pop_custom_cleanup_scope(arg_scope);
1590 // Microoptimization writ large: avoid creating a separate
1591 // llreturn basic block
1592 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1596 // Put return block after all other blocks.
1597 // This somewhat improves single-stepping experience in debugger.
1599 let llreturn = fcx.llreturn.get();
1600 if let Some(llreturn) = llreturn {
1601 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1605 let ret_debug_loc = DebugLoc::At(fn_cleanup_debug_loc.id,
1606 fn_cleanup_debug_loc.span);
1608 // Insert the mandatory first few basic blocks before lltop.
1609 finish_fn(&fcx, bcx, output_type, ret_debug_loc);
1612 /// Creates an LLVM function corresponding to a source language function.
1613 pub fn trans_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1617 param_substs: &'tcx Substs<'tcx>,
1619 attrs: &[ast::Attribute]) {
1620 let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string());
1621 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1622 let _icx = push_ctxt("trans_fn");
1623 let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1624 let output_type = ty::erase_late_bound_regions(ccx.tcx(), &ty::ty_fn_ret(fn_ty));
1625 let abi = ty::ty_fn_abi(fn_ty);
1626 trans_closure(ccx, decl, body, llfndecl, param_substs, id, attrs, output_type, abi,
1627 closure::ClosureEnv::NotClosure);
1630 pub fn trans_enum_variant<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1631 _enum_id: ast::NodeId,
1632 variant: &ast::Variant,
1633 _args: &[ast::VariantArg],
1635 param_substs: &'tcx Substs<'tcx>,
1636 llfndecl: ValueRef) {
1637 let _icx = push_ctxt("trans_enum_variant");
1639 trans_enum_variant_or_tuple_like_struct(
1647 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1650 args: callee::CallArgs,
1652 debug_loc: DebugLoc)
1653 -> Result<'blk, 'tcx> {
1655 let ccx = bcx.fcx.ccx;
1656 let tcx = ccx.tcx();
1658 let result_ty = match ctor_ty.sty {
1659 ty::ty_bare_fn(_, ref bft) => {
1660 ty::erase_late_bound_regions(bcx.tcx(), &bft.sig.output()).unwrap()
1662 _ => ccx.sess().bug(
1663 &format!("trans_enum_variant_constructor: \
1664 unexpected ctor return type {}",
1668 // Get location to store the result. If the user does not care about
1669 // the result, just make a stack slot
1670 let llresult = match dest {
1671 expr::SaveIn(d) => d,
1673 if !type_is_zero_size(ccx, result_ty) {
1674 alloc_ty(bcx, result_ty, "constructor_result")
1676 C_undef(type_of::type_of(ccx, result_ty))
1681 if !type_is_zero_size(ccx, result_ty) {
1683 callee::ArgExprs(exprs) => {
1684 let fields = exprs.iter().map(|x| &**x).enumerate().collect::<Vec<_>>();
1685 bcx = expr::trans_adt(bcx,
1690 expr::SaveIn(llresult),
1693 _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor")
1697 // If the caller doesn't care about the result
1698 // drop the temporary we made
1699 let bcx = match dest {
1700 expr::SaveIn(_) => bcx,
1702 let bcx = glue::drop_ty(bcx, llresult, result_ty, debug_loc);
1703 if !type_is_zero_size(ccx, result_ty) {
1704 call_lifetime_end(bcx, llresult);
1710 Result::new(bcx, llresult)
1713 pub fn trans_tuple_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1714 _fields: &[ast::StructField],
1715 ctor_id: ast::NodeId,
1716 param_substs: &'tcx Substs<'tcx>,
1717 llfndecl: ValueRef) {
1718 let _icx = push_ctxt("trans_tuple_struct");
1720 trans_enum_variant_or_tuple_like_struct(
1728 fn trans_enum_variant_or_tuple_like_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1729 ctor_id: ast::NodeId,
1731 param_substs: &'tcx Substs<'tcx>,
1732 llfndecl: ValueRef) {
1733 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1734 let ctor_ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &ctor_ty);
1736 let result_ty = match ctor_ty.sty {
1737 ty::ty_bare_fn(_, ref bft) => {
1738 ty::erase_late_bound_regions(ccx.tcx(), &bft.sig.output())
1740 _ => ccx.sess().bug(
1741 &format!("trans_enum_variant_or_tuple_like_struct: \
1742 unexpected ctor return type {}",
1743 ty_to_string(ccx.tcx(), ctor_ty)))
1746 let (arena, fcx): (TypedArena<_>, FunctionContext);
1747 arena = TypedArena::new();
1748 fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1749 param_substs, None, &arena);
1750 let bcx = init_function(&fcx, false, result_ty);
1752 assert!(!fcx.needs_ret_allocas);
1755 ty::erase_late_bound_regions(
1756 ccx.tcx(), &ty::ty_fn_args(ctor_ty));
1758 let arg_datums = create_datums_for_fn_args(&fcx, &arg_tys[..]);
1760 if !type_is_zero_size(fcx.ccx, result_ty.unwrap()) {
1761 let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot");
1762 let repr = adt::represent_type(ccx, result_ty.unwrap());
1763 for (i, arg_datum) in arg_datums.into_iter().enumerate() {
1764 let lldestptr = adt::trans_field_ptr(bcx,
1769 arg_datum.store_to(bcx, lldestptr);
1771 adt::trans_set_discr(bcx, &*repr, dest, disr);
1774 finish_fn(&fcx, bcx, result_ty, DebugLoc::None);
1777 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
1778 let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
1780 let print_info = ccx.sess().print_enum_sizes();
1782 let levels = ccx.tcx().node_lint_levels.borrow();
1783 let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCES);
1784 let lvlsrc = levels.get(&(id, lint_id));
1785 let is_allow = lvlsrc.map_or(true, |&(lvl, _)| lvl == lint::Allow);
1787 if is_allow && !print_info {
1788 // we're not interested in anything here
1792 let ty = ty::node_id_to_type(ccx.tcx(), id);
1793 let avar = adt::represent_type(ccx, ty);
1795 adt::General(_, ref variants, _) => {
1796 for var in variants {
1798 for field in var.fields.iter().skip(1) {
1799 // skip the discriminant
1800 size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
1805 _ => { /* its size is either constant or unimportant */ }
1808 let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
1809 |(l, s, li), (idx, &size)|
1812 } else if size > s {
1820 let llty = type_of::sizing_type_of(ccx, ty);
1822 let sess = &ccx.tcx().sess;
1823 sess.span_note(sp, &*format!("total size: {} bytes", llsize_of_real(ccx, llty)));
1825 adt::General(..) => {
1826 for (i, var) in enum_def.variants.iter().enumerate() {
1827 ccx.tcx().sess.span_note(var.span,
1828 &*format!("variant data: {} bytes", sizes[i]));
1835 // we only warn if the largest variant is at least thrice as large as
1836 // the second-largest.
1837 if !is_allow && largest > slargest * 3 && slargest > 0 {
1838 // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
1839 // pass for the latter already ran.
1840 lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCES,
1841 *lvlsrc.unwrap(), Some(sp),
1842 &format!("enum variant is more than three times larger \
1843 ({} bytes) than the next largest (ignoring padding)",
1846 ccx.sess().span_note(enum_def.variants[largest_index].span,
1847 "this variant is the largest");
1851 pub struct TransItemVisitor<'a, 'tcx: 'a> {
1852 pub ccx: &'a CrateContext<'a, 'tcx>,
1855 impl<'a, 'tcx, 'v> Visitor<'v> for TransItemVisitor<'a, 'tcx> {
1856 fn visit_item(&mut self, i: &ast::Item) {
1857 trans_item(self.ccx, i);
1861 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
1862 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
1863 // applicable to variable declarations and may not really make sense for
1864 // Rust code in the first place but whitelist them anyway and trust that
1865 // the user knows what s/he's doing. Who knows, unanticipated use cases
1866 // may pop up in the future.
1868 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
1869 // and don't have to be, LLVM treats them as no-ops.
1871 "appending" => Some(llvm::AppendingLinkage),
1872 "available_externally" => Some(llvm::AvailableExternallyLinkage),
1873 "common" => Some(llvm::CommonLinkage),
1874 "extern_weak" => Some(llvm::ExternalWeakLinkage),
1875 "external" => Some(llvm::ExternalLinkage),
1876 "internal" => Some(llvm::InternalLinkage),
1877 "linkonce" => Some(llvm::LinkOnceAnyLinkage),
1878 "linkonce_odr" => Some(llvm::LinkOnceODRLinkage),
1879 "private" => Some(llvm::PrivateLinkage),
1880 "weak" => Some(llvm::WeakAnyLinkage),
1881 "weak_odr" => Some(llvm::WeakODRLinkage),
1887 /// Enum describing the origin of an LLVM `Value`, for linkage purposes.
1888 #[derive(Copy, Clone)]
1889 pub enum ValueOrigin {
1890 /// The LLVM `Value` is in this context because the corresponding item was
1891 /// assigned to the current compilation unit.
1892 OriginalTranslation,
1893 /// The `Value`'s corresponding item was assigned to some other compilation
1894 /// unit, but the `Value` was translated in this context anyway because the
1895 /// item is marked `#[inline]`.
1899 /// Set the appropriate linkage for an LLVM `ValueRef` (function or global).
1900 /// If the `llval` is the direct translation of a specific Rust item, `id`
1901 /// should be set to the `NodeId` of that item. (This mapping should be
1902 /// 1-to-1, so monomorphizations and drop/visit glue should have `id` set to
1903 /// `None`.) `llval_origin` indicates whether `llval` is the translation of an
1904 /// item assigned to `ccx`'s compilation unit or an inlined copy of an item
1905 /// assigned to a different compilation unit.
1906 pub fn update_linkage(ccx: &CrateContext,
1908 id: Option<ast::NodeId>,
1909 llval_origin: ValueOrigin) {
1910 match llval_origin {
1912 // `llval` is a translation of an item defined in a separate
1913 // compilation unit. This only makes sense if there are at least
1914 // two compilation units.
1915 assert!(ccx.sess().opts.cg.codegen_units > 1);
1916 // `llval` is a copy of something defined elsewhere, so use
1917 // `AvailableExternallyLinkage` to avoid duplicating code in the
1919 llvm::SetLinkage(llval, llvm::AvailableExternallyLinkage);
1922 OriginalTranslation => {},
1925 if let Some(id) = id {
1926 let item = ccx.tcx().map.get(id);
1927 if let ast_map::NodeItem(i) = item {
1928 if let Some(name) = attr::first_attr_value_str_by_name(&i.attrs, "linkage") {
1929 if let Some(linkage) = llvm_linkage_by_name(&name) {
1930 llvm::SetLinkage(llval, linkage);
1932 ccx.sess().span_fatal(i.span, "invalid linkage specified");
1940 Some(id) if ccx.reachable().contains(&id) => {
1941 llvm::SetLinkage(llval, llvm::ExternalLinkage);
1944 // `id` does not refer to an item in `ccx.reachable`.
1945 if ccx.sess().opts.cg.codegen_units > 1 {
1946 llvm::SetLinkage(llval, llvm::ExternalLinkage);
1948 llvm::SetLinkage(llval, llvm::InternalLinkage);
1954 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1955 let _icx = push_ctxt("trans_item");
1957 let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
1960 ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
1961 if !generics.is_type_parameterized() {
1962 let trans_everywhere = attr::requests_inline(&item.attrs);
1963 // Ignore `trans_everywhere` for cross-crate inlined items
1964 // (`from_external`). `trans_item` will be called once for each
1965 // compilation unit that references the item, so it will still get
1966 // translated everywhere it's needed.
1967 for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
1968 let llfn = get_item_val(ccx, item.id);
1969 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
1971 foreign::trans_rust_fn_with_foreign_abi(ccx, &**decl, &**body, &item.attrs,
1972 llfn, empty_substs, item.id, None);
1974 trans_fn(ccx, &**decl, &**body, llfn, empty_substs, item.id, &item.attrs);
1976 update_linkage(ccx, llfn, Some(item.id),
1977 if is_origin { OriginalTranslation } else { InlinedCopy });
1979 if is_entry_fn(ccx.sess(), item.id) {
1980 create_entry_wrapper(ccx, item.span, llfn);
1981 // check for the #[rustc_error] annotation, which forces an
1982 // error in trans. This is used to write compile-fail tests
1983 // that actually test that compilation succeeds without
1984 // reporting an error.
1985 if ty::has_attr(ccx.tcx(), local_def(item.id), "rustc_error") {
1986 ccx.tcx().sess.span_fatal(item.span, "compilation successful");
1992 // Be sure to travel more than just one layer deep to catch nested
1993 // items in blocks and such.
1994 let mut v = TransItemVisitor{ ccx: ccx };
1995 v.visit_block(&**body);
1997 ast::ItemImpl(_, _, ref generics, _, _, ref impl_items) => {
1998 meth::trans_impl(ccx,
2004 ast::ItemMod(ref m) => {
2005 trans_mod(&ccx.rotate(), m);
2007 ast::ItemEnum(ref enum_definition, ref gens) => {
2008 if gens.ty_params.is_empty() {
2009 // sizes only make sense for non-generic types
2011 enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
2014 ast::ItemConst(_, ref expr) => {
2015 // Recurse on the expression to catch items in blocks
2016 let mut v = TransItemVisitor{ ccx: ccx };
2017 v.visit_expr(&**expr);
2019 ast::ItemStatic(_, m, ref expr) => {
2020 // Recurse on the expression to catch items in blocks
2021 let mut v = TransItemVisitor{ ccx: ccx };
2022 v.visit_expr(&**expr);
2024 let g = consts::trans_static(ccx, m, item.id);
2025 update_linkage(ccx, g, Some(item.id), OriginalTranslation);
2027 // Do static_assert checking. It can't really be done much earlier
2028 // because we need to get the value of the bool out of LLVM
2029 if attr::contains_name(&item.attrs, "static_assert") {
2030 if !ty::type_is_bool(ty::expr_ty(ccx.tcx(), expr)) {
2031 ccx.sess().span_fatal(expr.span,
2032 "can only have static_assert on a static \
2035 if m == ast::MutMutable {
2036 ccx.sess().span_fatal(expr.span,
2037 "cannot have static_assert on a mutable \
2041 let v = ccx.static_values().borrow().get(&item.id).unwrap().clone();
2043 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2044 ccx.sess().span_fatal(expr.span, "static assertion failed");
2049 ast::ItemForeignMod(ref foreign_mod) => {
2050 foreign::trans_foreign_mod(ccx, foreign_mod);
2052 ast::ItemTrait(..) => {
2053 // Inside of this trait definition, we won't be actually translating any
2054 // functions, but the trait still needs to be walked. Otherwise default
2055 // methods with items will not get translated and will cause ICE's when
2056 // metadata time comes around.
2057 let mut v = TransItemVisitor{ ccx: ccx };
2058 visit::walk_item(&mut v, item);
2060 _ => {/* fall through */ }
2064 // Translate a module. Doing this amounts to translating the items in the
2065 // module; there ends up being no artifact (aside from linkage names) of
2066 // separate modules in the compiled program. That's because modules exist
2067 // only as a convenience for humans working with the code, to organize names
2068 // and control visibility.
2069 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
2070 let _icx = push_ctxt("trans_mod");
2071 for item in &m.items {
2072 trans_item(ccx, &**item);
2077 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2078 pub fn register_fn_llvmty(ccx: &CrateContext,
2081 node_id: ast::NodeId,
2083 llfty: Type) -> ValueRef {
2084 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2086 let llfn = declare::define_fn(ccx, &sym[..], cc, llfty,
2087 ty::FnConverging(ty::mk_nil(ccx.tcx()))).unwrap_or_else(||{
2088 ccx.sess().span_fatal(sp, &format!("symbol `{}` is already defined", sym));
2090 finish_register_fn(ccx, sym, node_id, llfn);
2094 fn finish_register_fn(ccx: &CrateContext, sym: String, node_id: ast::NodeId,
2096 ccx.item_symbols().borrow_mut().insert(node_id, sym);
2098 // The stack exhaustion lang item shouldn't have a split stack because
2099 // otherwise it would continue to be exhausted (bad), and both it and the
2100 // eh_personality functions need to be externally linkable.
2101 let def = ast_util::local_def(node_id);
2102 if ccx.tcx().lang_items.stack_exhausted() == Some(def) {
2103 attributes::split_stack(llfn, false);
2104 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2106 if ccx.tcx().lang_items.eh_personality() == Some(def) {
2107 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2111 fn register_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2114 node_id: ast::NodeId,
2115 node_type: Ty<'tcx>)
2117 if let ty::ty_bare_fn(_, ref f) = node_type.sty {
2118 if f.abi != Rust && f.abi != RustCall {
2119 ccx.sess().span_bug(sp, &format!("only the `{}` or `{}` calling conventions are valid \
2120 for this function; `{}` was specified",
2121 Rust.name(), RustCall.name(), f.abi.name()));
2124 ccx.sess().span_bug(sp, "expected bare rust function")
2127 let llfn = declare::define_rust_fn(ccx, &sym[..], node_type).unwrap_or_else(||{
2128 ccx.sess().span_fatal(sp, &format!("symbol `{}` is already defined", sym));
2130 finish_register_fn(ccx, sym, node_id, llfn);
2134 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2135 match *sess.entry_fn.borrow() {
2136 Some((entry_id, _)) => node_id == entry_id,
2141 /// Create the `main` function which will initialise the rust runtime and call users’ main
2143 pub fn create_entry_wrapper(ccx: &CrateContext,
2145 main_llfn: ValueRef) {
2146 let et = ccx.sess().entry_type.get().unwrap();
2148 config::EntryMain => {
2149 create_entry_fn(ccx, sp, main_llfn, true);
2151 config::EntryStart => create_entry_fn(ccx, sp, main_llfn, false),
2152 config::EntryNone => {} // Do nothing.
2155 fn create_entry_fn(ccx: &CrateContext,
2157 rust_main: ValueRef,
2158 use_start_lang_item: bool) {
2159 let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()],
2162 let llfn = declare::define_cfn(ccx, "main", llfty,
2163 ty::mk_nil(ccx.tcx())).unwrap_or_else(||{
2164 ccx.sess().span_err(sp, "entry symbol `main` defined multiple times");
2165 // FIXME: We should be smart and show a better diagnostic here.
2166 ccx.sess().help("did you use #[no_mangle] on `fn main`? Use #[start] instead");
2167 ccx.sess().abort_if_errors();
2171 // FIXME: #16581: Marking a symbol in the executable with `dllexport`
2172 // linkage forces MinGW's linker to output a `.reloc` section for ASLR
2173 if ccx.sess().target.target.options.is_like_windows {
2174 unsafe { llvm::LLVMRustSetDLLExportStorageClass(llfn) }
2178 llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn,
2179 "top\0".as_ptr() as *const _)
2181 let bld = ccx.raw_builder();
2183 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2185 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx);
2187 let (start_fn, args) = if use_start_lang_item {
2188 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2190 Err(s) => { ccx.sess().fatal(&s[..]); }
2192 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2193 get_item_val(ccx, start_def_id.node)
2195 let start_fn_type = csearch::get_type(ccx.tcx(),
2197 trans_external_path(ccx, start_def_id, start_fn_type)
2201 let opaque_rust_main = llvm::LLVMBuildPointerCast(bld,
2202 rust_main, Type::i8p(ccx).to_ref(),
2203 "rust_main\0".as_ptr() as *const _);
2213 debug!("using user-defined start fn");
2215 get_param(llfn, 0 as c_uint),
2216 get_param(llfn, 1 as c_uint)
2222 let result = llvm::LLVMBuildCall(bld,
2225 args.len() as c_uint,
2228 llvm::LLVMBuildRet(bld, result);
2233 fn exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, id: ast::NodeId,
2234 ty: Ty<'tcx>, attrs: &[ast::Attribute]) -> String {
2235 match ccx.external_srcs().borrow().get(&id) {
2237 let sym = csearch::get_symbol(&ccx.sess().cstore, did);
2238 debug!("found item {} in other crate...", sym);
2244 match attr::find_export_name_attr(ccx.sess().diagnostic(), attrs) {
2245 // Use provided name
2246 Some(name) => name.to_string(),
2247 _ => ccx.tcx().map.with_path(id, |path| {
2248 if attr::contains_name(attrs, "no_mangle") {
2250 path.last().unwrap().to_string()
2252 match weak_lang_items::link_name(attrs) {
2253 Some(name) => name.to_string(),
2255 // Usual name mangling
2256 mangle_exported_name(ccx, path, ty, id)
2264 fn contains_null(s: &str) -> bool {
2265 s.bytes().any(|b| b == 0)
2268 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2269 debug!("get_item_val(id=`{}`)", id);
2271 match ccx.item_vals().borrow().get(&id).cloned() {
2272 Some(v) => return v,
2276 let item = ccx.tcx().map.get(id);
2277 debug!("get_item_val: id={} item={:?}", id, item);
2278 let val = match item {
2279 ast_map::NodeItem(i) => {
2280 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2281 let sym = || exported_name(ccx, id, ty, &i.attrs);
2283 let v = match i.node {
2284 ast::ItemStatic(_, _, ref expr) => {
2285 // If this static came from an external crate, then
2286 // we need to get the symbol from csearch instead of
2287 // using the current crate's name/version
2288 // information in the hash of the symbol
2290 debug!("making {}", sym);
2292 // We need the translated value here, because for enums the
2293 // LLVM type is not fully determined by the Rust type.
2294 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
2295 let (v, ty) = consts::const_expr(ccx, &**expr, empty_substs);
2296 ccx.static_values().borrow_mut().insert(id, v);
2298 // boolean SSA values are i1, but they have to be stored in i8 slots,
2299 // otherwise some LLVM optimization passes don't work as expected
2300 let llty = if ty::type_is_bool(ty) {
2301 llvm::LLVMInt8TypeInContext(ccx.llcx())
2306 // FIXME(nagisa): probably should be declare_global, because no definition
2307 // is happening here, but we depend on it being defined here from
2308 // const::trans_static. This all logic should be replaced.
2309 let g = declare::define_global(ccx, &sym[..],
2310 Type::from_ref(llty)).unwrap_or_else(||{
2311 ccx.sess().span_fatal(i.span, &format!("symbol `{}` is already defined",
2315 if attr::contains_name(&i.attrs,
2317 llvm::set_thread_local(g, true);
2319 ccx.item_symbols().borrow_mut().insert(i.id, sym);
2324 ast::ItemFn(_, _, abi, _, _) => {
2326 let llfn = if abi == Rust {
2327 register_fn(ccx, i.span, sym, i.id, ty)
2329 foreign::register_rust_fn_with_foreign_abi(ccx, i.span, sym, i.id)
2331 attributes::from_fn_attrs(ccx, &i.attrs, llfn);
2335 _ => ccx.sess().bug("get_item_val: weird result in table")
2338 match attr::first_attr_value_str_by_name(&i.attrs,
2341 if contains_null(§) {
2342 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`",
2346 let buf = CString::new(sect.as_bytes()).unwrap();
2347 llvm::LLVMSetSection(v, buf.as_ptr());
2356 ast_map::NodeTraitItem(trait_item) => {
2357 debug!("get_item_val(): processing a NodeTraitItem");
2358 match trait_item.node {
2359 ast::MethodTraitItem(_, Some(_)) => {
2360 register_method(ccx, id, &trait_item.attrs, trait_item.span)
2363 ccx.sess().span_bug(trait_item.span,
2364 "unexpected variant: trait item other than a provided \
2365 method in get_item_val()");
2370 ast_map::NodeImplItem(impl_item) => {
2371 match impl_item.node {
2372 ast::MethodImplItem(..) => {
2373 register_method(ccx, id, &impl_item.attrs, impl_item.span)
2376 ccx.sess().span_bug(impl_item.span,
2377 "unexpected variant: non-method impl item in \
2383 ast_map::NodeForeignItem(ni) => {
2385 ast::ForeignItemFn(..) => {
2386 let abi = ccx.tcx().map.get_foreign_abi(id);
2387 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2388 let name = foreign::link_name(&*ni);
2389 let llfn = foreign::register_foreign_item_fn(ccx, abi, ty, &name);
2390 attributes::from_fn_attrs(ccx, &ni.attrs, llfn);
2393 ast::ForeignItemStatic(..) => {
2394 foreign::register_static(ccx, &*ni)
2399 ast_map::NodeVariant(ref v) => {
2401 let args = match v.node.kind {
2402 ast::TupleVariantKind(ref args) => args,
2403 ast::StructVariantKind(_) => {
2404 ccx.sess().bug("struct variant kind unexpected in get_item_val")
2407 assert!(!args.is_empty());
2408 let ty = ty::node_id_to_type(ccx.tcx(), id);
2409 let parent = ccx.tcx().map.get_parent(id);
2410 let enm = ccx.tcx().map.expect_item(parent);
2411 let sym = exported_name(ccx,
2416 llfn = match enm.node {
2417 ast::ItemEnum(_, _) => {
2418 register_fn(ccx, (*v).span, sym, id, ty)
2420 _ => ccx.sess().bug("NodeVariant, shouldn't happen")
2422 attributes::inline(llfn, attributes::InlineAttr::Hint);
2426 ast_map::NodeStructCtor(struct_def) => {
2427 // Only register the constructor if this is a tuple-like struct.
2428 let ctor_id = match struct_def.ctor_id {
2430 ccx.sess().bug("attempt to register a constructor of \
2431 a non-tuple-like struct")
2433 Some(ctor_id) => ctor_id,
2435 let parent = ccx.tcx().map.get_parent(id);
2436 let struct_item = ccx.tcx().map.expect_item(parent);
2437 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2438 let sym = exported_name(ccx,
2441 &struct_item.attrs);
2442 let llfn = register_fn(ccx, struct_item.span,
2444 attributes::inline(llfn, attributes::InlineAttr::Hint);
2449 ccx.sess().bug(&format!("get_item_val(): unexpected variant: {:?}",
2454 // All LLVM globals and functions are initially created as external-linkage
2455 // declarations. If `trans_item`/`trans_fn` later turns the declaration
2456 // into a definition, it adjusts the linkage then (using `update_linkage`).
2458 // The exception is foreign items, which have their linkage set inside the
2459 // call to `foreign::register_*` above. We don't touch the linkage after
2460 // that (`foreign::trans_foreign_mod` doesn't adjust the linkage like the
2461 // other item translation functions do).
2463 ccx.item_vals().borrow_mut().insert(id, val);
2467 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2468 attrs: &[ast::Attribute], span: Span) -> ValueRef {
2469 let mty = ty::node_id_to_type(ccx.tcx(), id);
2471 let sym = exported_name(ccx, id, mty, &attrs);
2473 if let ty::ty_bare_fn(_, ref f) = mty.sty {
2474 let llfn = if f.abi == Rust || f.abi == RustCall {
2475 register_fn(ccx, span, sym, id, mty)
2477 foreign::register_rust_fn_with_foreign_abi(ccx, span, sym, id)
2479 attributes::from_fn_attrs(ccx, &attrs, llfn);
2482 ccx.sess().span_bug(span, "expected bare rust function");
2486 pub fn crate_ctxt_to_encode_parms<'a, 'tcx>(cx: &'a SharedCrateContext<'tcx>,
2487 ie: encoder::EncodeInlinedItem<'a>)
2488 -> encoder::EncodeParams<'a, 'tcx> {
2489 encoder::EncodeParams {
2490 diag: cx.sess().diagnostic(),
2492 reexports: cx.export_map(),
2493 item_symbols: cx.item_symbols(),
2494 link_meta: cx.link_meta(),
2495 cstore: &cx.sess().cstore,
2496 encode_inlined_item: ie,
2497 reachable: cx.reachable(),
2501 pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
2504 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2505 *ty != config::CrateTypeExecutable
2511 let encode_inlined_item: encoder::EncodeInlinedItem =
2512 Box::new(|ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii));
2514 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2515 let metadata = encoder::encode_metadata(encode_parms, krate);
2516 let mut compressed = encoder::metadata_encoding_version.to_vec();
2517 compressed.push_all(&flate::deflate_bytes(&metadata));
2518 let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
2519 let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
2520 let name = format!("rust_metadata_{}_{}",
2521 cx.link_meta().crate_name,
2522 cx.link_meta().crate_hash);
2523 let buf = CString::new(name).unwrap();
2524 let llglobal = unsafe {
2525 llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(),
2529 llvm::LLVMSetInitializer(llglobal, llconst);
2530 let name = loader::meta_section_name(cx.sess().target.target.options.is_like_osx);
2531 let name = CString::new(name).unwrap();
2532 llvm::LLVMSetSection(llglobal, name.as_ptr())
2537 /// Find any symbols that are defined in one compilation unit, but not declared
2538 /// in any other compilation unit. Give these symbols internal linkage.
2539 fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
2541 let mut declared = HashSet::new();
2543 let iter_globals = |llmod| {
2545 cur: llvm::LLVMGetFirstGlobal(llmod),
2546 step: llvm::LLVMGetNextGlobal,
2550 let iter_functions = |llmod| {
2552 cur: llvm::LLVMGetFirstFunction(llmod),
2553 step: llvm::LLVMGetNextFunction,
2557 // Collect all external declarations in all compilation units.
2558 for ccx in cx.iter() {
2559 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2560 let linkage = llvm::LLVMGetLinkage(val);
2561 // We only care about external declarations (not definitions)
2562 // and available_externally definitions.
2563 if !(linkage == llvm::ExternalLinkage as c_uint &&
2564 llvm::LLVMIsDeclaration(val) != 0) &&
2565 !(linkage == llvm::AvailableExternallyLinkage as c_uint) {
2569 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2570 .to_bytes().to_vec();
2571 declared.insert(name);
2575 // Examine each external definition. If the definition is not used in
2576 // any other compilation unit, and is not reachable from other crates,
2577 // then give it internal linkage.
2578 for ccx in cx.iter() {
2579 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2580 // We only care about external definitions.
2581 if !(llvm::LLVMGetLinkage(val) == llvm::ExternalLinkage as c_uint &&
2582 llvm::LLVMIsDeclaration(val) == 0) {
2586 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2587 .to_bytes().to_vec();
2588 if !declared.contains(&name) &&
2589 !reachable.contains(str::from_utf8(&name).unwrap()) {
2590 llvm::SetLinkage(val, llvm::InternalLinkage);
2599 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
2602 impl Iterator for ValueIter {
2603 type Item = ValueRef;
2605 fn next(&mut self) -> Option<ValueRef> {
2609 let step: unsafe extern "C" fn(ValueRef) -> ValueRef =
2610 mem::transmute_copy(&self.step);
2621 pub fn trans_crate<'tcx>(analysis: ty::CrateAnalysis<'tcx>)
2622 -> (ty::ctxt<'tcx>, CrateTranslation) {
2623 let ty::CrateAnalysis { ty_cx: tcx, export_map, reachable, name, .. } = analysis;
2624 let krate = tcx.map.krate();
2626 let check_overflow = if let Some(v) = tcx.sess.opts.debugging_opts.force_overflow_checks {
2629 tcx.sess.opts.debug_assertions
2632 let check_dropflag = if let Some(v) = tcx.sess.opts.debugging_opts.force_dropflag_checks {
2635 tcx.sess.opts.debug_assertions
2638 // Before we touch LLVM, make sure that multithreading is enabled.
2640 use std::sync::{Once, ONCE_INIT};
2641 static INIT: Once = ONCE_INIT;
2642 static mut POISONED: bool = false;
2644 if llvm::LLVMStartMultithreaded() != 1 {
2645 // use an extra bool to make sure that all future usage of LLVM
2646 // cannot proceed despite the Once not running more than once.
2652 tcx.sess.bug("couldn't enable multi-threaded LLVM");
2656 let link_meta = link::build_link_meta(&tcx.sess, krate, name);
2658 let codegen_units = tcx.sess.opts.cg.codegen_units;
2659 let shared_ccx = SharedCrateContext::new(&link_meta.crate_name,
2670 let ccx = shared_ccx.get_ccx(0);
2672 // First, verify intrinsics.
2673 intrinsic::check_intrinsics(&ccx);
2675 // Next, translate the module.
2677 let _icx = push_ctxt("text");
2678 trans_mod(&ccx, &krate.module);
2682 for ccx in shared_ccx.iter() {
2683 if ccx.sess().opts.debuginfo != NoDebugInfo {
2684 debuginfo::finalize(&ccx);
2688 // Translate the metadata.
2689 let metadata = write_metadata(&shared_ccx, krate);
2691 if shared_ccx.sess().trans_stats() {
2692 let stats = shared_ccx.stats();
2693 println!("--- trans stats ---");
2694 println!("n_glues_created: {}", stats.n_glues_created.get());
2695 println!("n_null_glues: {}", stats.n_null_glues.get());
2696 println!("n_real_glues: {}", stats.n_real_glues.get());
2698 println!("n_fns: {}", stats.n_fns.get());
2699 println!("n_monos: {}", stats.n_monos.get());
2700 println!("n_inlines: {}", stats.n_inlines.get());
2701 println!("n_closures: {}", stats.n_closures.get());
2702 println!("fn stats:");
2703 stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
2704 insns_b.cmp(&insns_a)
2706 for tuple in &*stats.fn_stats.borrow() {
2708 (ref name, insns) => {
2709 println!("{} insns, {}", insns, *name);
2714 if shared_ccx.sess().count_llvm_insns() {
2715 for (k, v) in &*shared_ccx.stats().llvm_insns.borrow() {
2716 println!("{:7} {}", *v, *k);
2720 let modules = shared_ccx.iter()
2721 .map(|ccx| ModuleTranslation { llcx: ccx.llcx(), llmod: ccx.llmod() })
2724 let mut reachable: Vec<String> = shared_ccx.reachable().iter().filter_map(|id| {
2725 shared_ccx.item_symbols().borrow().get(id).map(|s| s.to_string())
2728 // For the purposes of LTO, we add to the reachable set all of the upstream
2729 // reachable extern fns. These functions are all part of the public ABI of
2730 // the final product, so LTO needs to preserve them.
2731 shared_ccx.sess().cstore.iter_crate_data(|cnum, _| {
2732 let syms = csearch::get_reachable_extern_fns(&shared_ccx.sess().cstore, cnum);
2733 reachable.extend(syms.into_iter().map(|did| {
2734 csearch::get_symbol(&shared_ccx.sess().cstore, did)
2738 // Make sure that some other crucial symbols are not eliminated from the
2739 // module. This includes the main function, the crate map (used for debug
2740 // log settings and I/O), and finally the curious rust_stack_exhausted
2741 // symbol. This symbol is required for use by the libmorestack library that
2742 // we link in, so we must ensure that this symbol is not internalized (if
2743 // defined in the crate).
2744 reachable.push("main".to_string());
2745 reachable.push("rust_stack_exhausted".to_string());
2747 // referenced from .eh_frame section on some platforms
2748 reachable.push("rust_eh_personality".to_string());
2749 // referenced from rt/rust_try.ll
2750 reachable.push("rust_eh_personality_catch".to_string());
2752 if codegen_units > 1 {
2753 internalize_symbols(&shared_ccx, &reachable.iter().cloned().collect());
2756 let metadata_module = ModuleTranslation {
2757 llcx: shared_ccx.metadata_llcx(),
2758 llmod: shared_ccx.metadata_llmod(),
2760 let formats = shared_ccx.tcx().dependency_formats.borrow().clone();
2761 let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
2763 let translation = CrateTranslation {
2765 metadata_module: metadata_module,
2768 reachable: reachable,
2769 crate_formats: formats,
2770 no_builtins: no_builtins,
2773 (shared_ccx.take_tcx(), translation)