1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // trans.rs: Translate the completed AST to the LLVM IR.
13 // Some functions here, such as trans_block and trans_expr, return a value --
14 // the result of the translation to LLVM -- while others, such as trans_fn,
15 // trans_impl, and trans_item, are called only for the side effect of adding a
16 // particular definition to the LLVM IR output we're producing.
18 // Hopefully useful general knowledge about trans:
20 // * There's no way to find out the Ty type of a ValueRef. Doing so
21 // would be "trying to get the eggs out of an omelette" (credit:
22 // pcwalton). You can, instead, find out its TypeRef by calling val_ty,
23 // but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
24 // int) and rec(x=int, y=int, z=int) will have the same TypeRef.
26 #![allow(non_camel_case_types)]
28 pub use self::ValueOrigin::*;
30 use super::CrateTranslation;
31 use super::ModuleTranslation;
33 use back::link::{mangle_exported_name};
34 use back::{link, abi};
36 use llvm::{BasicBlockRef, Linkage, ValueRef, Vector, get_param};
38 use metadata::{csearch, encoder, loader};
39 use middle::astencode;
41 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
42 use middle::weak_lang_items;
43 use middle::subst::{Subst, Substs};
44 use middle::ty::{self, Ty, ClosureTyper};
45 use session::config::{self, NoDebugInfo};
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_integral};
56 use trans::common::{C_null, C_struct_in_context, C_u64, C_u8, C_undef};
57 use trans::common::{CrateContext, ExternMap, FunctionContext};
58 use trans::common::{Result, NodeIdAndSpan};
59 use trans::common::{node_id_type, return_type_is_void};
60 use trans::common::{tydesc_info, type_is_immediate};
61 use trans::common::{type_is_zero_size, val_ty};
64 use trans::context::SharedCrateContext;
65 use trans::controlflow;
67 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
74 use trans::machine::{llsize_of, llsize_of_real};
76 use trans::monomorphize;
78 use trans::type_::Type;
80 use trans::type_of::*;
81 use trans::value::Value;
82 use util::common::indenter;
83 use util::ppaux::{Repr, ty_to_string};
84 use util::sha2::Sha256;
85 use util::nodemap::NodeMap;
87 use arena::TypedArena;
88 use libc::{c_uint, uint64_t};
89 use std::ffi::{CStr, CString};
90 use std::cell::{Cell, RefCell};
91 use std::collections::HashSet;
95 use std::{i8, i16, i32, i64};
96 use syntax::abi::{Rust, RustCall, RustIntrinsic, Abi};
97 use syntax::ast_util::local_def;
98 use syntax::attr::AttrMetaMethods;
100 use syntax::codemap::Span;
101 use syntax::parse::token::InternedString;
102 use syntax::visit::Visitor;
104 use syntax::{ast, ast_util, ast_map};
107 static TASK_LOCAL_INSN_KEY: RefCell<Option<Vec<&'static str>>> = {
112 pub fn with_insn_ctxt<F>(blk: F) where
113 F: FnOnce(&[&'static str]),
115 TASK_LOCAL_INSN_KEY.with(move |slot| {
116 slot.borrow().as_ref().map(move |s| blk(s));
120 pub fn init_insn_ctxt() {
121 TASK_LOCAL_INSN_KEY.with(|slot| {
122 *slot.borrow_mut() = Some(Vec::new());
126 pub struct _InsnCtxt {
127 _cannot_construct_outside_of_this_module: ()
131 impl Drop for _InsnCtxt {
133 TASK_LOCAL_INSN_KEY.with(|slot| {
134 match slot.borrow_mut().as_mut() {
135 Some(ctx) => { ctx.pop(); }
142 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
143 debug!("new InsnCtxt: {}", s);
144 TASK_LOCAL_INSN_KEY.with(|slot| {
145 match slot.borrow_mut().as_mut() {
146 Some(ctx) => ctx.push(s),
150 _InsnCtxt { _cannot_construct_outside_of_this_module: () }
153 pub struct StatRecorder<'a, 'tcx: 'a> {
154 ccx: &'a CrateContext<'a, 'tcx>,
155 name: Option<String>,
159 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
160 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String)
161 -> StatRecorder<'a, 'tcx> {
162 let istart = ccx.stats().n_llvm_insns.get();
172 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
174 if self.ccx.sess().trans_stats() {
175 let iend = self.ccx.stats().n_llvm_insns.get();
176 self.ccx.stats().fn_stats.borrow_mut().push((self.name.take().unwrap(),
177 iend - self.istart));
178 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
179 // Reset LLVM insn count to avoid compound costs.
180 self.ccx.stats().n_llvm_insns.set(self.istart);
185 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
186 pub fn decl_fn(ccx: &CrateContext, name: &str, cc: llvm::CallConv,
187 ty: Type, output: ty::FnOutput) -> ValueRef {
189 let buf = CString::new(name).unwrap();
190 let llfn: ValueRef = unsafe {
191 llvm::LLVMGetOrInsertFunction(ccx.llmod(), buf.as_ptr(), ty.to_ref())
194 // diverging functions may unwind, but can never return normally
195 if output == ty::FnDiverging {
196 llvm::SetFunctionAttribute(llfn, llvm::NoReturnAttribute);
199 if ccx.tcx().sess.opts.cg.no_redzone
200 .unwrap_or(ccx.tcx().sess.target.target.options.disable_redzone) {
201 llvm::SetFunctionAttribute(llfn, llvm::NoRedZoneAttribute)
204 llvm::SetFunctionCallConv(llfn, cc);
205 // Function addresses in Rust are never significant, allowing functions to be merged.
206 llvm::SetUnnamedAddr(llfn, true);
208 if ccx.is_split_stack_supported() && !ccx.sess().opts.cg.no_stack_check {
209 set_split_stack(llfn);
215 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
216 pub fn decl_cdecl_fn(ccx: &CrateContext,
219 output: Ty) -> ValueRef {
220 decl_fn(ccx, name, llvm::CCallConv, ty, ty::FnConverging(output))
223 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
224 pub fn get_extern_fn(ccx: &CrateContext,
225 externs: &mut ExternMap,
231 match externs.get(name) {
232 Some(n) => return *n,
235 let f = decl_fn(ccx, name, cc, ty, ty::FnConverging(output));
236 externs.insert(name.to_string(), f);
240 fn get_extern_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty: Ty<'tcx>,
241 name: &str, did: ast::DefId) -> ValueRef {
242 match ccx.externs().borrow().get(name) {
243 Some(n) => return *n,
247 let f = decl_rust_fn(ccx, fn_ty, name);
249 let attrs = csearch::get_item_attrs(&ccx.sess().cstore, did);
250 set_llvm_fn_attrs(ccx, &attrs[..], f);
252 ccx.externs().borrow_mut().insert(name.to_string(), f);
256 pub fn self_type_for_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
257 closure_id: ast::DefId,
261 let closure_kind = ccx.tcx().closure_kind(closure_id);
263 ty::FnClosureKind => {
264 ty::mk_imm_rptr(ccx.tcx(), ccx.tcx().mk_region(ty::ReStatic), fn_ty)
266 ty::FnMutClosureKind => {
267 ty::mk_mut_rptr(ccx.tcx(), ccx.tcx().mk_region(ty::ReStatic), fn_ty)
269 ty::FnOnceClosureKind => fn_ty
273 pub fn kind_for_closure(ccx: &CrateContext, closure_id: ast::DefId) -> ty::ClosureKind {
274 ccx.tcx().closure_kinds.borrow()[closure_id]
277 pub fn decl_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
278 fn_ty: Ty<'tcx>, name: &str) -> ValueRef {
279 debug!("decl_rust_fn(fn_ty={}, name={:?})",
280 fn_ty.repr(ccx.tcx()),
283 let fn_ty = monomorphize::normalize_associated_type(ccx.tcx(), &fn_ty);
285 debug!("decl_rust_fn: fn_ty={} (after normalized associated types)",
286 fn_ty.repr(ccx.tcx()));
288 let function_type; // placeholder so that the memory ownership works out ok
290 let (sig, abi, env) = match fn_ty.sty {
291 ty::ty_bare_fn(_, ref f) => {
292 (&f.sig, f.abi, None)
294 ty::ty_closure(closure_did, _, substs) => {
295 let typer = common::NormalizingClosureTyper::new(ccx.tcx());
296 function_type = typer.closure_type(closure_did, substs);
297 let self_type = self_type_for_closure(ccx, closure_did, fn_ty);
298 let llenvironment_type = type_of_explicit_arg(ccx, self_type);
299 debug!("decl_rust_fn: function_type={} self_type={}",
300 function_type.repr(ccx.tcx()),
301 self_type.repr(ccx.tcx()));
302 (&function_type.sig, RustCall, Some(llenvironment_type))
304 _ => panic!("expected closure or fn")
307 let sig = ty::erase_late_bound_regions(ccx.tcx(), sig);
308 let sig = ty::Binder(sig);
310 debug!("decl_rust_fn: sig={} (after erasing regions)",
311 sig.repr(ccx.tcx()));
313 let llfty = type_of_rust_fn(ccx, env, &sig, abi);
315 debug!("decl_rust_fn: llfty={}",
316 ccx.tn().type_to_string(llfty));
318 let llfn = decl_fn(ccx, name, llvm::CCallConv, llfty, sig.0.output /* (1) */);
319 let attrs = get_fn_llvm_attributes(ccx, fn_ty);
320 attrs.apply_llfn(llfn);
322 // (1) it's ok to directly access sig.0.output because we erased all late-bound-regions above
327 pub fn decl_internal_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
328 fn_ty: Ty<'tcx>, name: &str) -> ValueRef {
329 let llfn = decl_rust_fn(ccx, fn_ty, name);
330 llvm::SetLinkage(llfn, llvm::InternalLinkage);
334 pub fn get_extern_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId,
335 t: Ty<'tcx>) -> ValueRef {
336 let name = csearch::get_symbol(&ccx.sess().cstore, did);
337 let ty = type_of(ccx, t);
338 match ccx.externs().borrow_mut().get(&name) {
339 Some(n) => return *n,
343 let buf = CString::new(name.clone()).unwrap();
344 let c = llvm::LLVMAddGlobal(ccx.llmod(), ty.to_ref(), buf.as_ptr());
345 // Thread-local statics in some other crate need to *always* be linked
346 // against in a thread-local fashion, so we need to be sure to apply the
347 // thread-local attribute locally if it was present remotely. If we
348 // don't do this then linker errors can be generated where the linker
349 // complains that one object files has a thread local version of the
350 // symbol and another one doesn't.
351 for attr in &*ty::get_attrs(ccx.tcx(), did) {
352 if attr.check_name("thread_local") {
353 llvm::set_thread_local(c, true);
356 ccx.externs().borrow_mut().insert(name.to_string(), c);
361 fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
362 info_ty: Ty<'tcx>, it: LangItem) -> ast::DefId {
363 match bcx.tcx().lang_items.require(it) {
366 bcx.sess().fatal(&format!("allocation of `{}` {}",
367 bcx.ty_to_string(info_ty),
373 // The following malloc_raw_dyn* functions allocate a box to contain
374 // a given type, but with a potentially dynamic size.
376 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
382 -> Result<'blk, 'tcx> {
383 let _icx = push_ctxt("malloc_raw_exchange");
386 let r = callee::trans_lang_call(bcx,
387 require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem),
392 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
395 // Type descriptor and type glue stuff
397 pub fn get_tydesc<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
398 t: Ty<'tcx>) -> Rc<tydesc_info<'tcx>> {
399 match ccx.tydescs().borrow().get(&t) {
400 Some(inf) => return inf.clone(),
404 ccx.stats().n_static_tydescs.set(ccx.stats().n_static_tydescs.get() + 1);
405 let inf = Rc::new(glue::declare_tydesc(ccx, t));
407 ccx.tydescs().borrow_mut().insert(t, inf.clone());
411 #[allow(dead_code)] // useful
412 pub fn set_optimize_for_size(f: ValueRef) {
413 llvm::SetFunctionAttribute(f, llvm::OptimizeForSizeAttribute)
416 pub fn set_no_inline(f: ValueRef) {
417 llvm::SetFunctionAttribute(f, llvm::NoInlineAttribute)
420 #[allow(dead_code)] // useful
421 pub fn set_no_unwind(f: ValueRef) {
422 llvm::SetFunctionAttribute(f, llvm::NoUnwindAttribute)
425 // Tell LLVM to emit the information necessary to unwind the stack for the
427 pub fn set_uwtable(f: ValueRef) {
428 llvm::SetFunctionAttribute(f, llvm::UWTableAttribute)
431 pub fn set_inline_hint(f: ValueRef) {
432 llvm::SetFunctionAttribute(f, llvm::InlineHintAttribute)
435 pub fn set_llvm_fn_attrs(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: ValueRef) {
437 // Set the inline hint if there is one
438 match find_inline_attr(attrs) {
439 InlineHint => set_inline_hint(llfn),
440 InlineAlways => set_always_inline(llfn),
441 InlineNever => set_no_inline(llfn),
442 InlineNone => { /* fallthrough */ }
447 match &attr.name()[] {
448 "no_stack_check" => unset_split_stack(llfn),
449 "no_split_stack" => {
450 unset_split_stack(llfn);
451 ccx.sess().span_warn(attr.span,
452 "no_split_stack is a deprecated synonym for no_stack_check");
455 llvm::LLVMAddFunctionAttribute(llfn,
456 llvm::FunctionIndex as c_uint,
457 llvm::ColdAttribute as uint64_t)
462 attr::mark_used(attr);
467 pub fn set_always_inline(f: ValueRef) {
468 llvm::SetFunctionAttribute(f, llvm::AlwaysInlineAttribute)
471 pub fn set_split_stack(f: ValueRef) {
473 llvm::LLVMAddFunctionAttrString(f, llvm::FunctionIndex as c_uint,
474 "split-stack\0".as_ptr() as *const _);
478 pub fn unset_split_stack(f: ValueRef) {
480 llvm::LLVMRemoveFunctionAttrString(f, llvm::FunctionIndex as c_uint,
481 "split-stack\0".as_ptr() as *const _);
485 // Double-check that we never ask LLVM to declare the same symbol twice. It
486 // silently mangles such symbols, breaking our linkage model.
487 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) {
488 if ccx.all_llvm_symbols().borrow().contains(&sym) {
489 ccx.sess().bug(&format!("duplicate LLVM symbol: {}", sym)[]);
491 ccx.all_llvm_symbols().borrow_mut().insert(sym);
495 pub fn get_res_dtor<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
498 parent_id: ast::DefId,
499 substs: &Substs<'tcx>)
501 let _icx = push_ctxt("trans_res_dtor");
502 let did = inline::maybe_instantiate_inline(ccx, did);
504 if !substs.types.is_empty() {
505 assert_eq!(did.krate, ast::LOCAL_CRATE);
507 // Since we're in trans we don't care for any region parameters
508 let substs = ccx.tcx().mk_substs(Substs::erased(substs.types.clone()));
510 let (val, _, _) = monomorphize::monomorphic_fn(ccx, did, substs, None);
513 } else if did.krate == ast::LOCAL_CRATE {
514 get_item_val(ccx, did.node)
517 let name = csearch::get_symbol(&ccx.sess().cstore, did);
518 let class_ty = ty::lookup_item_type(tcx, parent_id).ty.subst(tcx, substs);
519 let llty = type_of_dtor(ccx, class_ty);
520 let dtor_ty = ty::mk_ctor_fn(ccx.tcx(),
522 &[glue::get_drop_glue_type(ccx, t)],
523 ty::mk_nil(ccx.tcx()));
525 &mut *ccx.externs().borrow_mut(),
533 pub fn bin_op_to_icmp_predicate(ccx: &CrateContext, op: ast::BinOp_, signed: bool)
534 -> llvm::IntPredicate {
536 ast::BiEq => llvm::IntEQ,
537 ast::BiNe => llvm::IntNE,
538 ast::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
539 ast::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
540 ast::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
541 ast::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
543 ccx.sess().bug(&format!("comparison_op_to_icmp_predicate: expected \
544 comparison operator, found {:?}", op)[]);
549 pub fn bin_op_to_fcmp_predicate(ccx: &CrateContext, op: ast::BinOp_)
550 -> llvm::RealPredicate {
552 ast::BiEq => llvm::RealOEQ,
553 ast::BiNe => llvm::RealUNE,
554 ast::BiLt => llvm::RealOLT,
555 ast::BiLe => llvm::RealOLE,
556 ast::BiGt => llvm::RealOGT,
557 ast::BiGe => llvm::RealOGE,
559 ccx.sess().bug(&format!("comparison_op_to_fcmp_predicate: expected \
560 comparison operator, found {:?}", op)[]);
565 pub fn compare_scalar_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
573 ty::ty_tup(ref tys) if tys.is_empty() => {
574 // We don't need to do actual comparisons for nil.
575 // () == () holds but () < () does not.
577 ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(bcx.ccx(), true),
578 ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(bcx.ccx(), false),
579 // refinements would be nice
580 _ => bcx.sess().bug("compare_scalar_types: must be a comparison operator")
583 ty::ty_bool | ty::ty_uint(_) | ty::ty_char => {
584 ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, false), lhs, rhs, debug_loc)
586 ty::ty_ptr(mt) if common::type_is_sized(bcx.tcx(), mt.ty) => {
587 ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, false), lhs, rhs, debug_loc)
590 ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, true), lhs, rhs, debug_loc)
593 FCmp(bcx, bin_op_to_fcmp_predicate(bcx.ccx(), op), lhs, rhs, debug_loc)
595 // Should never get here, because t is scalar.
596 _ => bcx.sess().bug("non-scalar type passed to compare_scalar_types")
600 pub fn compare_simd_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
607 let signed = match t.sty {
609 // The comparison operators for floating point vectors are challenging.
610 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
611 // then bitcast to a floating point vector, the result will be `-NaN`
612 // for each truth value. Because of this they are unsupported.
613 bcx.sess().bug("compare_simd_types: comparison operators \
614 not supported for floating point SIMD types")
616 ty::ty_uint(_) => false,
617 ty::ty_int(_) => true,
618 _ => bcx.sess().bug("compare_simd_types: invalid SIMD type"),
621 let cmp = bin_op_to_icmp_predicate(bcx.ccx(), op, signed);
622 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
623 // to get the correctly sized type. This will compile to a single instruction
624 // once the IR is converted to assembly if the SIMD instruction is supported
625 // by the target architecture.
626 SExt(bcx, ICmp(bcx, cmp, lhs, rhs, debug_loc), val_ty(lhs))
629 // Iterates through the elements of a structural type.
630 pub fn iter_structural_ty<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
634 -> Block<'blk, 'tcx> where
635 F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
637 let _icx = push_ctxt("iter_structural_ty");
639 fn iter_variant<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
640 repr: &adt::Repr<'tcx>,
642 variant: &ty::VariantInfo<'tcx>,
643 substs: &Substs<'tcx>,
645 -> Block<'blk, 'tcx> where
646 F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
648 let _icx = push_ctxt("iter_variant");
652 for (i, &arg) in variant.args.iter().enumerate() {
653 let arg = monomorphize::apply_param_substs(tcx, substs, &arg);
654 cx = f(cx, adt::trans_field_ptr(cx, repr, av, variant.disr_val, i), arg);
659 let (data_ptr, info) = if common::type_is_sized(cx.tcx(), t) {
662 let data = GEPi(cx, av, &[0, abi::FAT_PTR_ADDR]);
663 let info = GEPi(cx, av, &[0, abi::FAT_PTR_EXTRA]);
664 (Load(cx, data), Some(Load(cx, info)))
669 ty::ty_struct(..) => {
670 let repr = adt::represent_type(cx.ccx(), t);
671 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
672 for (i, field_ty) in field_tys.iter().enumerate() {
673 let field_ty = field_ty.mt.ty;
674 let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, discr, i);
676 let val = if common::type_is_sized(cx.tcx(), field_ty) {
679 let boxed_ty = ty::mk_open(cx.tcx(), field_ty);
680 let scratch = datum::rvalue_scratch_datum(cx, boxed_ty, "__fat_ptr_iter");
681 Store(cx, llfld_a, GEPi(cx, scratch.val, &[0, abi::FAT_PTR_ADDR]));
682 Store(cx, info.unwrap(), GEPi(cx, scratch.val, &[0, abi::FAT_PTR_EXTRA]));
685 cx = f(cx, val, field_ty);
689 ty::ty_closure(def_id, _, substs) => {
690 let repr = adt::represent_type(cx.ccx(), t);
691 let typer = common::NormalizingClosureTyper::new(cx.tcx());
692 let upvars = typer.closure_upvars(def_id, substs).unwrap();
693 for (i, upvar) in upvars.iter().enumerate() {
694 let llupvar = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
695 cx = f(cx, llupvar, upvar.ty);
698 ty::ty_vec(_, Some(n)) => {
699 let (base, len) = tvec::get_fixed_base_and_len(cx, data_ptr, n);
700 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
701 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
703 ty::ty_tup(ref args) => {
704 let repr = adt::represent_type(cx.ccx(), t);
705 for (i, arg) in args.iter().enumerate() {
706 let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
707 cx = f(cx, llfld_a, *arg);
710 ty::ty_enum(tid, substs) => {
714 let repr = adt::represent_type(ccx, t);
715 let variants = ty::enum_variants(ccx.tcx(), tid);
716 let n_variants = (*variants).len();
718 // NB: we must hit the discriminant first so that structural
719 // comparison know not to proceed when the discriminants differ.
721 match adt::trans_switch(cx, &*repr, av) {
722 (_match::Single, None) => {
723 cx = iter_variant(cx, &*repr, av, &*(*variants)[0],
726 (_match::Switch, Some(lldiscrim_a)) => {
727 cx = f(cx, lldiscrim_a, cx.tcx().types.int);
728 let unr_cx = fcx.new_temp_block("enum-iter-unr");
730 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
732 let next_cx = fcx.new_temp_block("enum-iter-next");
734 for variant in &(*variants) {
737 &format!("enum-iter-variant-{}",
738 &variant.disr_val.to_string()[])
740 match adt::trans_case(cx, &*repr, variant.disr_val) {
741 _match::SingleResult(r) => {
742 AddCase(llswitch, r.val, variant_cx.llbb)
744 _ => ccx.sess().unimpl("value from adt::trans_case \
745 in iter_structural_ty")
748 iter_variant(variant_cx,
754 Br(variant_cx, next_cx.llbb, DebugLoc::None);
758 _ => ccx.sess().unimpl("value from adt::trans_switch \
759 in iter_structural_ty")
763 cx.sess().unimpl(&format!("type in iter_structural_ty: {}",
764 ty_to_string(cx.tcx(), t))[])
770 pub fn cast_shift_expr_rhs(cx: Block,
775 cast_shift_rhs(op, lhs, rhs,
776 |a,b| Trunc(cx, a, b),
777 |a,b| ZExt(cx, a, b))
780 pub fn cast_shift_const_rhs(op: ast::BinOp,
781 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
782 cast_shift_rhs(op, lhs, rhs,
783 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
784 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
787 pub fn cast_shift_rhs<F, G>(op: ast::BinOp,
793 F: FnOnce(ValueRef, Type) -> ValueRef,
794 G: FnOnce(ValueRef, Type) -> ValueRef,
796 // Shifts may have any size int on the rhs
797 if ast_util::is_shift_binop(op.node) {
798 let mut rhs_llty = val_ty(rhs);
799 let mut lhs_llty = val_ty(lhs);
800 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
801 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
802 let rhs_sz = rhs_llty.int_width();
803 let lhs_sz = lhs_llty.int_width();
806 } else if lhs_sz > rhs_sz {
807 // FIXME (#1877: If shifting by negative
808 // values becomes not undefined then this is wrong.
818 pub fn fail_if_zero_or_overflows<'blk, 'tcx>(
819 cx: Block<'blk, 'tcx>,
820 call_info: NodeIdAndSpan,
825 -> Block<'blk, 'tcx> {
826 let (zero_text, overflow_text) = if divrem.node == ast::BiDiv {
827 ("attempted to divide by zero",
828 "attempted to divide with overflow")
830 ("attempted remainder with a divisor of zero",
831 "attempted remainder with overflow")
833 let debug_loc = call_info.debug_loc();
835 let (is_zero, is_signed) = match rhs_t.sty {
837 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
838 (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), true)
841 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
842 (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), false)
845 cx.sess().bug(&format!("fail-if-zero on unexpected type: {}",
846 ty_to_string(cx.tcx(), rhs_t))[]);
849 let bcx = with_cond(cx, is_zero, |bcx| {
850 controlflow::trans_fail(bcx, call_info, InternedString::new(zero_text))
853 // To quote LLVM's documentation for the sdiv instruction:
855 // Division by zero leads to undefined behavior. Overflow also leads
856 // to undefined behavior; this is a rare case, but can occur, for
857 // example, by doing a 32-bit division of -2147483648 by -1.
859 // In order to avoid undefined behavior, we perform runtime checks for
860 // signed division/remainder which would trigger overflow. For unsigned
861 // integers, no action beyond checking for zero need be taken.
863 let (llty, min) = match rhs_t.sty {
865 let llty = Type::int_from_ty(cx.ccx(), t);
867 ast::TyIs(_) if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
868 ast::TyIs(_) => i64::MIN as u64,
869 ast::TyI8 => i8::MIN as u64,
870 ast::TyI16 => i16::MIN as u64,
871 ast::TyI32 => i32::MIN as u64,
872 ast::TyI64 => i64::MIN as u64,
878 let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
879 C_integral(llty, -1, false), debug_loc);
880 with_cond(bcx, minus_one, |bcx| {
881 let is_min = ICmp(bcx, llvm::IntEQ, lhs,
882 C_integral(llty, min, true), debug_loc);
883 with_cond(bcx, is_min, |bcx| {
884 controlflow::trans_fail(bcx,
886 InternedString::new(overflow_text))
894 pub fn trans_external_path<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
895 did: ast::DefId, t: Ty<'tcx>) -> ValueRef {
896 let name = csearch::get_symbol(&ccx.sess().cstore, did);
898 ty::ty_bare_fn(_, ref fn_ty) => {
899 match ccx.sess().target.target.adjust_abi(fn_ty.abi) {
901 get_extern_rust_fn(ccx, t, &name[..], did)
904 ccx.sess().bug("unexpected intrinsic in trans_external_path")
907 foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
913 get_extern_const(ccx, did, t)
918 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
923 -> (ValueRef, Block<'blk, 'tcx>) {
924 let _icx = push_ctxt("invoke_");
925 if bcx.unreachable.get() {
926 return (C_null(Type::i8(bcx.ccx())), bcx);
929 let attributes = get_fn_llvm_attributes(bcx.ccx(), fn_ty);
931 match bcx.opt_node_id {
933 debug!("invoke at ???");
936 debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
940 if need_invoke(bcx) {
941 debug!("invoking {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
942 for &llarg in llargs {
943 debug!("arg: {}", bcx.val_to_string(llarg));
945 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
946 let landing_pad = bcx.fcx.get_landing_pad();
948 let llresult = Invoke(bcx,
955 return (llresult, normal_bcx);
957 debug!("calling {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
958 for &llarg in llargs {
959 debug!("arg: {}", bcx.val_to_string(llarg));
962 let llresult = Call(bcx,
967 return (llresult, bcx);
971 pub fn need_invoke(bcx: Block) -> bool {
972 if bcx.sess().no_landing_pads() {
976 // Avoid using invoke if we are already inside a landing pad.
981 bcx.fcx.needs_invoke()
984 pub fn load_if_immediate<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
985 v: ValueRef, t: Ty<'tcx>) -> ValueRef {
986 let _icx = push_ctxt("load_if_immediate");
987 if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
991 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
992 /// differs from the type used for SSA values. Also handles various special cases where the type
993 /// gives us better information about what we are loading.
994 pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
995 ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
996 if type_is_zero_size(cx.ccx(), t) {
997 C_undef(type_of::type_of(cx.ccx(), t))
998 } else if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
999 // We want to pass small aggregates as immediate values, but using an aggregate LLVM type
1000 // for this leads to bad optimizations, so its arg type is an appropriately sized integer
1001 // and we have to convert it
1002 Load(cx, BitCast(cx, ptr, type_of::arg_type_of(cx.ccx(), t).ptr_to()))
1005 let global = llvm::LLVMIsAGlobalVariable(ptr);
1006 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
1007 let val = llvm::LLVMGetInitializer(global);
1009 // This could go into its own function, for DRY.
1010 // (something like "pre-store packing/post-load unpacking")
1011 if ty::type_is_bool(t) {
1012 return Trunc(cx, val, Type::i1(cx.ccx()));
1019 if ty::type_is_bool(t) {
1020 Trunc(cx, LoadRangeAssert(cx, ptr, 0, 2, llvm::False), Type::i1(cx.ccx()))
1021 } else if ty::type_is_char(t) {
1022 // a char is a Unicode codepoint, and so takes values from 0
1023 // to 0x10FFFF inclusive only.
1024 LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
1025 } else if (ty::type_is_region_ptr(t) || ty::type_is_unique(t))
1026 && !common::type_is_fat_ptr(cx.tcx(), t) {
1027 LoadNonNull(cx, ptr)
1034 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
1035 /// differs from the type used for SSA values.
1036 pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
1037 if ty::type_is_bool(t) {
1038 Store(cx, ZExt(cx, v, Type::i8(cx.ccx())), dst);
1039 } else if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
1040 // We want to pass small aggregates as immediate values, but using an aggregate LLVM type
1041 // for this leads to bad optimizations, so its arg type is an appropriately sized integer
1042 // and we have to convert it
1043 Store(cx, v, BitCast(cx, dst, type_of::arg_type_of(cx.ccx(), t).ptr_to()));
1049 pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &ast::Local)
1050 -> Block<'blk, 'tcx> {
1051 debug!("init_local(bcx={}, local.id={})", bcx.to_str(), local.id);
1052 let _indenter = indenter();
1053 let _icx = push_ctxt("init_local");
1054 _match::store_local(bcx, local)
1057 pub fn raw_block<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1059 llbb: BasicBlockRef)
1060 -> Block<'blk, 'tcx> {
1061 common::BlockS::new(llbb, is_lpad, None, fcx)
1064 pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
1067 -> Block<'blk, 'tcx> where
1068 F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>,
1070 let _icx = push_ctxt("with_cond");
1072 if bcx.unreachable.get() ||
1073 (common::is_const(val) && common::const_to_uint(val) == 0) {
1078 let next_cx = fcx.new_temp_block("next");
1079 let cond_cx = fcx.new_temp_block("cond");
1080 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb, DebugLoc::None);
1081 let after_cx = f(cond_cx);
1082 if !after_cx.terminated.get() {
1083 Br(after_cx, next_cx.llbb, DebugLoc::None);
1088 pub fn call_lifetime_start(cx: Block, ptr: ValueRef) {
1089 if cx.sess().opts.optimize == config::No {
1093 let _icx = push_ctxt("lifetime_start");
1096 let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
1097 let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
1098 let lifetime_start = ccx.get_intrinsic(&"llvm.lifetime.start");
1099 Call(cx, lifetime_start, &[llsize, ptr], None, DebugLoc::None);
1102 pub fn call_lifetime_end(cx: Block, ptr: ValueRef) {
1103 if cx.sess().opts.optimize == config::No {
1107 let _icx = push_ctxt("lifetime_end");
1110 let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
1111 let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
1112 let lifetime_end = ccx.get_intrinsic(&"llvm.lifetime.end");
1113 Call(cx, lifetime_end, &[llsize, ptr], None, DebugLoc::None);
1116 pub fn call_memcpy(cx: Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1117 let _icx = push_ctxt("call_memcpy");
1119 let key = match &ccx.sess().target.target.target_pointer_width[] {
1120 "32" => "llvm.memcpy.p0i8.p0i8.i32",
1121 "64" => "llvm.memcpy.p0i8.p0i8.i64",
1122 tws => panic!("Unsupported target word size for memcpy: {}", tws),
1124 let memcpy = ccx.get_intrinsic(&key);
1125 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1126 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1127 let size = IntCast(cx, n_bytes, ccx.int_type());
1128 let align = C_i32(ccx, align as i32);
1129 let volatile = C_bool(ccx, false);
1130 Call(cx, memcpy, &[dst_ptr, src_ptr, size, align, volatile], None, DebugLoc::None);
1133 pub fn memcpy_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1134 dst: ValueRef, src: ValueRef,
1136 let _icx = push_ctxt("memcpy_ty");
1137 let ccx = bcx.ccx();
1138 if ty::type_is_structural(t) {
1139 let llty = type_of::type_of(ccx, t);
1140 let llsz = llsize_of(ccx, llty);
1141 let llalign = type_of::align_of(ccx, t);
1142 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1144 store_ty(bcx, load_ty(bcx, src, t), dst, t);
1148 pub fn zero_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
1149 if cx.unreachable.get() { return; }
1150 let _icx = push_ctxt("zero_mem");
1152 memzero(&B(bcx), llptr, t);
1155 // Always use this function instead of storing a zero constant to the memory
1156 // in question. If you store a zero constant, LLVM will drown in vreg
1157 // allocation for large data structures, and the generated code will be
1158 // awful. (A telltale sign of this is large quantities of
1159 // `mov [byte ptr foo],0` in the generated code.)
1160 fn memzero<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>) {
1161 let _icx = push_ctxt("memzero");
1164 let llty = type_of::type_of(ccx, ty);
1166 let intrinsic_key = match &ccx.sess().target.target.target_pointer_width[] {
1167 "32" => "llvm.memset.p0i8.i32",
1168 "64" => "llvm.memset.p0i8.i64",
1169 tws => panic!("Unsupported target word size for memset: {}", tws),
1172 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1173 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1174 let llzeroval = C_u8(ccx, 0);
1175 let size = machine::llsize_of(ccx, llty);
1176 let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
1177 let volatile = C_bool(ccx, false);
1178 b.call(llintrinsicfn, &[llptr, llzeroval, size, align, volatile], None);
1181 pub fn alloc_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, name: &str) -> ValueRef {
1182 let _icx = push_ctxt("alloc_ty");
1183 let ccx = bcx.ccx();
1184 let ty = type_of::type_of(ccx, t);
1185 assert!(!ty::type_has_params(t));
1186 let val = alloca(bcx, ty, name);
1190 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
1191 let p = alloca_no_lifetime(cx, ty, name);
1192 call_lifetime_start(cx, p);
1196 pub fn alloca_no_lifetime(cx: Block, ty: Type, name: &str) -> ValueRef {
1197 let _icx = push_ctxt("alloca");
1198 if cx.unreachable.get() {
1200 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1203 debuginfo::clear_source_location(cx.fcx);
1204 Alloca(cx, ty, name)
1207 pub fn alloca_zeroed<'blk, 'tcx>(cx: Block<'blk, 'tcx>, ty: Ty<'tcx>,
1208 name: &str) -> ValueRef {
1209 let llty = type_of::type_of(cx.ccx(), ty);
1210 if cx.unreachable.get() {
1212 return llvm::LLVMGetUndef(llty.ptr_to().to_ref());
1215 let p = alloca_no_lifetime(cx, llty, name);
1216 let b = cx.fcx.ccx.builder();
1217 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1222 // Creates the alloca slot which holds the pointer to the slot for the final return value
1223 pub fn make_return_slot_pointer<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1224 output_type: Ty<'tcx>) -> ValueRef {
1225 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1227 // We create an alloca to hold a pointer of type `output_type`
1228 // which will hold the pointer to the right alloca which has the
1230 if fcx.needs_ret_allocas {
1231 // Let's create the stack slot
1232 let slot = AllocaFcx(fcx, lloutputtype.ptr_to(), "llretslotptr");
1234 // and if we're using an out pointer, then store that in our newly made slot
1235 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1236 let outptr = get_param(fcx.llfn, 0);
1238 let b = fcx.ccx.builder();
1239 b.position_before(fcx.alloca_insert_pt.get().unwrap());
1240 b.store(outptr, slot);
1245 // But if there are no nested returns, we skip the indirection and have a single
1248 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1249 get_param(fcx.llfn, 0)
1251 AllocaFcx(fcx, lloutputtype, "sret_slot")
1256 struct FindNestedReturn {
1260 impl FindNestedReturn {
1261 fn new() -> FindNestedReturn {
1262 FindNestedReturn { found: false }
1266 impl<'v> Visitor<'v> for FindNestedReturn {
1267 fn visit_expr(&mut self, e: &ast::Expr) {
1269 ast::ExprRet(..) => {
1272 _ => visit::walk_expr(self, e)
1277 fn build_cfg(tcx: &ty::ctxt, id: ast::NodeId) -> (ast::NodeId, Option<cfg::CFG>) {
1278 let blk = match tcx.map.find(id) {
1279 Some(ast_map::NodeItem(i)) => {
1281 ast::ItemFn(_, _, _, _, ref blk) => {
1284 _ => tcx.sess.bug("unexpected item variant in has_nested_returns")
1287 Some(ast_map::NodeTraitItem(trait_method)) => {
1288 match *trait_method {
1289 ast::ProvidedMethod(ref m) => {
1291 ast::MethDecl(_, _, _, _, _, _, ref blk, _) => {
1294 ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
1297 ast::RequiredMethod(_) => {
1298 tcx.sess.bug("unexpected variant: required trait method \
1299 in has_nested_returns")
1301 ast::TypeTraitItem(_) => {
1302 tcx.sess.bug("unexpected variant: type trait item in \
1303 has_nested_returns")
1307 Some(ast_map::NodeImplItem(ii)) => {
1309 ast::MethodImplItem(ref m) => {
1311 ast::MethDecl(_, _, _, _, _, _, ref blk, _) => {
1314 ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
1317 ast::TypeImplItem(_) => {
1318 tcx.sess.bug("unexpected variant: type impl item in \
1319 has_nested_returns")
1323 Some(ast_map::NodeExpr(e)) => {
1325 ast::ExprClosure(_, _, ref blk) => {
1328 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns")
1331 Some(ast_map::NodeVariant(..)) |
1332 Some(ast_map::NodeStructCtor(..)) => return (ast::DUMMY_NODE_ID, None),
1335 None if id == ast::DUMMY_NODE_ID => return (ast::DUMMY_NODE_ID, None),
1337 _ => tcx.sess.bug(&format!("unexpected variant in has_nested_returns: {}",
1338 tcx.map.path_to_string(id)))
1341 (blk.id, Some(cfg::CFG::new(tcx, &**blk)))
1344 // Checks for the presence of "nested returns" in a function.
1345 // Nested returns are when the inner expression of a return expression
1346 // (the 'expr' in 'return expr') contains a return expression. Only cases
1347 // where the outer return is actually reachable are considered. Implicit
1348 // returns from the end of blocks are considered as well.
1350 // This check is needed to handle the case where the inner expression is
1351 // part of a larger expression that may have already partially-filled the
1352 // return slot alloca. This can cause errors related to clean-up due to
1353 // the clobbering of the existing value in the return slot.
1354 fn has_nested_returns(tcx: &ty::ctxt, cfg: &cfg::CFG, blk_id: ast::NodeId) -> bool {
1355 for n in cfg.graph.depth_traverse(cfg.entry) {
1356 match tcx.map.find(n.id) {
1357 Some(ast_map::NodeExpr(ex)) => {
1358 if let ast::ExprRet(Some(ref ret_expr)) = ex.node {
1359 let mut visitor = FindNestedReturn::new();
1360 visit::walk_expr(&mut visitor, &**ret_expr);
1366 Some(ast_map::NodeBlock(blk)) if blk.id == blk_id => {
1367 let mut visitor = FindNestedReturn::new();
1368 visit::walk_expr_opt(&mut visitor, &blk.expr);
1380 // NB: must keep 4 fns in sync:
1383 // - create_datums_for_fn_args.
1387 // Be warned! You must call `init_function` before doing anything with the
1388 // returned function context.
1389 pub fn new_fn_ctxt<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
1393 output_type: ty::FnOutput<'tcx>,
1394 param_substs: &'tcx Substs<'tcx>,
1396 block_arena: &'a TypedArena<common::BlockS<'a, 'tcx>>)
1397 -> FunctionContext<'a, 'tcx> {
1398 common::validate_substs(param_substs);
1400 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1404 ccx.tcx().map.path_to_string(id).to_string()
1406 id, param_substs.repr(ccx.tcx()));
1408 let uses_outptr = match output_type {
1409 ty::FnConverging(output_type) => {
1410 let substd_output_type =
1411 monomorphize::apply_param_substs(ccx.tcx(), param_substs, &output_type);
1412 type_of::return_uses_outptr(ccx, substd_output_type)
1414 ty::FnDiverging => false
1416 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1417 let (blk_id, cfg) = build_cfg(ccx.tcx(), id);
1418 let nested_returns = if let Some(ref cfg) = cfg {
1419 has_nested_returns(ccx.tcx(), cfg, blk_id)
1424 let mut fcx = FunctionContext {
1427 llretslotptr: Cell::new(None),
1428 param_env: ty::empty_parameter_environment(ccx.tcx()),
1429 alloca_insert_pt: Cell::new(None),
1430 llreturn: Cell::new(None),
1431 needs_ret_allocas: nested_returns,
1432 personality: Cell::new(None),
1433 caller_expects_out_pointer: uses_outptr,
1434 lllocals: RefCell::new(NodeMap()),
1435 llupvars: RefCell::new(NodeMap()),
1437 param_substs: param_substs,
1439 block_arena: block_arena,
1441 debug_context: debug_context,
1442 scopes: RefCell::new(Vec::new()),
1447 fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1453 /// Performs setup on a newly created function, creating the entry scope block
1454 /// and allocating space for the return pointer.
1455 pub fn init_function<'a, 'tcx>(fcx: &'a FunctionContext<'a, 'tcx>,
1457 output: ty::FnOutput<'tcx>)
1458 -> Block<'a, 'tcx> {
1459 let entry_bcx = fcx.new_temp_block("entry-block");
1461 // Use a dummy instruction as the insertion point for all allocas.
1462 // This is later removed in FunctionContext::cleanup.
1463 fcx.alloca_insert_pt.set(Some(unsafe {
1464 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1465 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1468 if let ty::FnConverging(output_type) = output {
1469 // This shouldn't need to recompute the return type,
1470 // as new_fn_ctxt did it already.
1471 let substd_output_type = fcx.monomorphize(&output_type);
1472 if !return_type_is_void(fcx.ccx, substd_output_type) {
1473 // If the function returns nil/bot, there is no real return
1474 // value, so do not set `llretslotptr`.
1475 if !skip_retptr || fcx.caller_expects_out_pointer {
1476 // Otherwise, we normally allocate the llretslotptr, unless we
1477 // have been instructed to skip it for immediate return
1479 fcx.llretslotptr.set(Some(make_return_slot_pointer(fcx, substd_output_type)));
1487 // NB: must keep 4 fns in sync:
1490 // - create_datums_for_fn_args.
1494 pub fn arg_kind<'a, 'tcx>(cx: &FunctionContext<'a, 'tcx>, t: Ty<'tcx>)
1496 use trans::datum::{ByRef, ByValue};
1499 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1503 // work around bizarre resolve errors
1504 type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
1506 // create_datums_for_fn_args: creates rvalue datums for each of the
1507 // incoming function arguments. These will later be stored into
1508 // appropriate lvalue datums.
1509 pub fn create_datums_for_fn_args<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1510 arg_tys: &[Ty<'tcx>])
1511 -> Vec<RvalueDatum<'tcx>> {
1512 let _icx = push_ctxt("create_datums_for_fn_args");
1514 // Return an array wrapping the ValueRefs that we get from `get_param` for
1515 // each argument into datums.
1516 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1517 let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1518 datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1522 /// Creates rvalue datums for each of the incoming function arguments and
1523 /// tuples the arguments. These will later be stored into appropriate lvalue
1526 /// FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1527 fn create_datums_for_fn_args_under_call_abi<'blk, 'tcx>(
1528 mut bcx: Block<'blk, 'tcx>,
1529 arg_scope: cleanup::CustomScopeIndex,
1530 arg_tys: &[Ty<'tcx>])
1531 -> Vec<RvalueDatum<'tcx>> {
1532 let mut result = Vec::new();
1533 for (i, &arg_ty) in arg_tys.iter().enumerate() {
1534 if i < arg_tys.len() - 1 {
1535 // Regular argument.
1536 let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1537 result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1542 // This is the last argument. Tuple it.
1544 ty::ty_tup(ref tupled_arg_tys) => {
1545 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1548 datum::lvalue_scratch_datum(bcx,
1552 tuple_args_scope_id,
1557 for (j, &tupled_arg_ty) in
1558 tupled_arg_tys.iter().enumerate() {
1560 get_param(bcx.fcx.llfn,
1561 bcx.fcx.arg_pos(i + j) as c_uint);
1562 let lldest = GEPi(bcx, llval, &[0, j]);
1563 let datum = datum::Datum::new(
1566 arg_kind(bcx.fcx, tupled_arg_ty));
1567 bcx = datum.store_to(bcx, lldest);
1571 let tuple = unpack_datum!(bcx,
1572 tuple.to_expr_datum()
1573 .to_rvalue_datum(bcx,
1578 bcx.tcx().sess.bug("last argument of a function with \
1579 `rust-call` ABI isn't a tuple?!")
1588 fn copy_args_to_allocas<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1589 arg_scope: cleanup::CustomScopeIndex,
1591 arg_datums: Vec<RvalueDatum<'tcx>>)
1592 -> Block<'blk, 'tcx> {
1593 debug!("copy_args_to_allocas");
1595 let _icx = push_ctxt("copy_args_to_allocas");
1598 let arg_scope_id = cleanup::CustomScope(arg_scope);
1600 for (i, arg_datum) in arg_datums.into_iter().enumerate() {
1601 // For certain mode/type combinations, the raw llarg values are passed
1602 // by value. However, within the fn body itself, we want to always
1603 // have all locals and arguments be by-ref so that we can cancel the
1604 // cleanup and for better interaction with LLVM's debug info. So, if
1605 // the argument would be passed by value, we store it into an alloca.
1606 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1607 // the event it's not truly needed.
1609 bcx = _match::store_arg(bcx, &*args[i].pat, arg_datum, arg_scope_id);
1610 debuginfo::create_argument_metadata(bcx, &args[i]);
1616 fn copy_closure_args_to_allocas<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1617 arg_scope: cleanup::CustomScopeIndex,
1619 arg_datums: Vec<RvalueDatum<'tcx>>,
1620 monomorphized_arg_types: &[Ty<'tcx>])
1621 -> Block<'blk, 'tcx> {
1622 let _icx = push_ctxt("copy_closure_args_to_allocas");
1623 let arg_scope_id = cleanup::CustomScope(arg_scope);
1625 assert_eq!(arg_datums.len(), 1);
1627 let arg_datum = arg_datums.into_iter().next().unwrap();
1629 // Untuple the rest of the arguments.
1632 arg_datum.to_lvalue_datum_in_scope(bcx,
1635 let untupled_arg_types = match monomorphized_arg_types[0].sty {
1636 ty::ty_tup(ref types) => &types[..],
1638 bcx.tcx().sess.span_bug(args[0].pat.span,
1639 "first arg to `rust-call` ABI function \
1643 for j in 0..args.len() {
1644 let tuple_element_type = untupled_arg_types[j];
1645 let tuple_element_datum =
1646 tuple_datum.get_element(bcx,
1648 |llval| GEPi(bcx, llval, &[0, j]));
1649 let tuple_element_datum = tuple_element_datum.to_expr_datum();
1650 let tuple_element_datum =
1652 tuple_element_datum.to_rvalue_datum(bcx,
1654 bcx = _match::store_arg(bcx,
1656 tuple_element_datum,
1659 debuginfo::create_argument_metadata(bcx, &args[j]);
1665 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1666 // and builds the return block.
1667 pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1668 last_bcx: Block<'blk, 'tcx>,
1669 retty: ty::FnOutput<'tcx>,
1670 ret_debug_loc: DebugLoc) {
1671 let _icx = push_ctxt("finish_fn");
1673 let ret_cx = match fcx.llreturn.get() {
1675 if !last_bcx.terminated.get() {
1676 Br(last_bcx, llreturn, DebugLoc::None);
1678 raw_block(fcx, false, llreturn)
1683 // This shouldn't need to recompute the return type,
1684 // as new_fn_ctxt did it already.
1685 let substd_retty = fcx.monomorphize(&retty);
1686 build_return_block(fcx, ret_cx, substd_retty, ret_debug_loc);
1688 debuginfo::clear_source_location(fcx);
1692 // Builds the return block for a function.
1693 pub fn build_return_block<'blk, 'tcx>(fcx: &FunctionContext<'blk, 'tcx>,
1694 ret_cx: Block<'blk, 'tcx>,
1695 retty: ty::FnOutput<'tcx>,
1696 ret_debug_location: DebugLoc) {
1697 if fcx.llretslotptr.get().is_none() ||
1698 (!fcx.needs_ret_allocas && fcx.caller_expects_out_pointer) {
1699 return RetVoid(ret_cx, ret_debug_location);
1702 let retslot = if fcx.needs_ret_allocas {
1703 Load(ret_cx, fcx.llretslotptr.get().unwrap())
1705 fcx.llretslotptr.get().unwrap()
1707 let retptr = Value(retslot);
1708 match retptr.get_dominating_store(ret_cx) {
1709 // If there's only a single store to the ret slot, we can directly return
1710 // the value that was stored and omit the store and the alloca
1712 let retval = s.get_operand(0).unwrap().get();
1713 s.erase_from_parent();
1715 if retptr.has_no_uses() {
1716 retptr.erase_from_parent();
1719 let retval = if retty == ty::FnConverging(fcx.ccx.tcx().types.bool) {
1720 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1725 if fcx.caller_expects_out_pointer {
1726 if let ty::FnConverging(retty) = retty {
1727 store_ty(ret_cx, retval, get_param(fcx.llfn, 0), retty);
1729 RetVoid(ret_cx, ret_debug_location)
1731 Ret(ret_cx, retval, ret_debug_location)
1734 // Otherwise, copy the return value to the ret slot
1735 None => match retty {
1736 ty::FnConverging(retty) => {
1737 if fcx.caller_expects_out_pointer {
1738 memcpy_ty(ret_cx, get_param(fcx.llfn, 0), retslot, retty);
1739 RetVoid(ret_cx, ret_debug_location)
1741 Ret(ret_cx, load_ty(ret_cx, retslot, retty), ret_debug_location)
1744 ty::FnDiverging => {
1745 if fcx.caller_expects_out_pointer {
1746 RetVoid(ret_cx, ret_debug_location)
1748 Ret(ret_cx, C_undef(Type::nil(fcx.ccx)), ret_debug_location)
1755 // trans_closure: Builds an LLVM function out of a source function.
1756 // If the function closes over its environment a closure will be
1758 pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1762 param_substs: &'tcx Substs<'tcx>,
1763 fn_ast_id: ast::NodeId,
1764 _attributes: &[ast::Attribute],
1765 output_type: ty::FnOutput<'tcx>,
1767 closure_env: closure::ClosureEnv<'b>) {
1768 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1770 let _icx = push_ctxt("trans_closure");
1771 set_uwtable(llfndecl);
1773 debug!("trans_closure(..., param_substs={})",
1774 param_substs.repr(ccx.tcx()));
1776 let has_env = match closure_env {
1777 closure::ClosureEnv::Closure(_) => true,
1778 closure::ClosureEnv::NotClosure => false,
1781 let (arena, fcx): (TypedArena<_>, FunctionContext);
1782 arena = TypedArena::new();
1783 fcx = new_fn_ctxt(ccx,
1791 let mut bcx = init_function(&fcx, false, output_type);
1793 // cleanup scope for the incoming arguments
1794 let fn_cleanup_debug_loc =
1795 debuginfo::get_cleanup_debug_loc_for_ast_node(ccx, fn_ast_id, body.span, true);
1796 let arg_scope = fcx.push_custom_cleanup_scope_with_debug_loc(fn_cleanup_debug_loc);
1798 let block_ty = node_id_type(bcx, body.id);
1800 // Set up arguments to the function.
1801 let monomorphized_arg_types =
1803 .map(|arg| node_id_type(bcx, arg.id))
1804 .collect::<Vec<_>>();
1805 let monomorphized_arg_types = match closure_env {
1806 closure::ClosureEnv::NotClosure => {
1807 monomorphized_arg_types
1810 // Tuple up closure argument types for the "rust-call" ABI.
1811 closure::ClosureEnv::Closure(_) => {
1812 vec![ty::mk_tup(ccx.tcx(), monomorphized_arg_types)]
1815 for monomorphized_arg_type in &monomorphized_arg_types {
1816 debug!("trans_closure: monomorphized_arg_type: {}",
1817 ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1819 debug!("trans_closure: function lltype: {}",
1820 bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
1822 let arg_datums = if abi != RustCall {
1823 create_datums_for_fn_args(&fcx,
1824 &monomorphized_arg_types[..])
1826 create_datums_for_fn_args_under_call_abi(
1829 &monomorphized_arg_types[..])
1832 bcx = match closure_env {
1833 closure::ClosureEnv::NotClosure => {
1834 copy_args_to_allocas(bcx,
1839 closure::ClosureEnv::Closure(_) => {
1840 copy_closure_args_to_allocas(
1845 &monomorphized_arg_types[..])
1849 bcx = closure_env.load(bcx, cleanup::CustomScope(arg_scope));
1851 // Up until here, IR instructions for this function have explicitly not been annotated with
1852 // source code location, so we don't step into call setup code. From here on, source location
1853 // emitting should be enabled.
1854 debuginfo::start_emitting_source_locations(&fcx);
1856 let dest = match fcx.llretslotptr.get() {
1857 Some(_) => expr::SaveIn(fcx.get_ret_slot(bcx, ty::FnConverging(block_ty), "iret_slot")),
1859 assert!(type_is_zero_size(bcx.ccx(), block_ty));
1864 // This call to trans_block is the place where we bridge between
1865 // translation calls that don't have a return value (trans_crate,
1866 // trans_mod, trans_item, et cetera) and those that do
1867 // (trans_block, trans_expr, et cetera).
1868 bcx = controlflow::trans_block(bcx, body, dest);
1871 expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1872 Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1877 match fcx.llreturn.get() {
1879 Br(bcx, fcx.return_exit_block(), DebugLoc::None);
1880 fcx.pop_custom_cleanup_scope(arg_scope);
1883 // Microoptimization writ large: avoid creating a separate
1884 // llreturn basic block
1885 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1889 // Put return block after all other blocks.
1890 // This somewhat improves single-stepping experience in debugger.
1892 let llreturn = fcx.llreturn.get();
1893 if let Some(llreturn) = llreturn {
1894 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1898 let ret_debug_loc = DebugLoc::At(fn_cleanup_debug_loc.id,
1899 fn_cleanup_debug_loc.span);
1901 // Insert the mandatory first few basic blocks before lltop.
1902 finish_fn(&fcx, bcx, output_type, ret_debug_loc);
1905 // trans_fn: creates an LLVM function corresponding to a source language
1907 pub fn trans_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1911 param_substs: &'tcx Substs<'tcx>,
1913 attrs: &[ast::Attribute]) {
1914 let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string());
1915 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1916 let _icx = push_ctxt("trans_fn");
1917 let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1918 let output_type = ty::erase_late_bound_regions(ccx.tcx(), &ty::ty_fn_ret(fn_ty));
1919 let abi = ty::ty_fn_abi(fn_ty);
1929 closure::ClosureEnv::NotClosure);
1932 pub fn trans_enum_variant<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1933 _enum_id: ast::NodeId,
1934 variant: &ast::Variant,
1935 _args: &[ast::VariantArg],
1937 param_substs: &'tcx Substs<'tcx>,
1938 llfndecl: ValueRef) {
1939 let _icx = push_ctxt("trans_enum_variant");
1941 trans_enum_variant_or_tuple_like_struct(
1949 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1952 args: callee::CallArgs,
1954 debug_loc: DebugLoc)
1955 -> Result<'blk, 'tcx> {
1957 let ccx = bcx.fcx.ccx;
1958 let tcx = ccx.tcx();
1960 let result_ty = match ctor_ty.sty {
1961 ty::ty_bare_fn(_, ref bft) => {
1962 ty::erase_late_bound_regions(bcx.tcx(), &bft.sig.output()).unwrap()
1964 _ => ccx.sess().bug(
1965 &format!("trans_enum_variant_constructor: \
1966 unexpected ctor return type {}",
1967 ctor_ty.repr(tcx))[])
1970 // Get location to store the result. If the user does not care about
1971 // the result, just make a stack slot
1972 let llresult = match dest {
1973 expr::SaveIn(d) => d,
1975 if !type_is_zero_size(ccx, result_ty) {
1976 alloc_ty(bcx, result_ty, "constructor_result")
1978 C_undef(type_of::type_of(ccx, result_ty))
1983 if !type_is_zero_size(ccx, result_ty) {
1985 callee::ArgExprs(exprs) => {
1986 let fields = exprs.iter().map(|x| &**x).enumerate().collect::<Vec<_>>();
1987 bcx = expr::trans_adt(bcx,
1992 expr::SaveIn(llresult),
1995 _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor")
1999 // If the caller doesn't care about the result
2000 // drop the temporary we made
2001 let bcx = match dest {
2002 expr::SaveIn(_) => bcx,
2004 let bcx = glue::drop_ty(bcx, llresult, result_ty, debug_loc);
2005 if !type_is_zero_size(ccx, result_ty) {
2006 call_lifetime_end(bcx, llresult);
2012 Result::new(bcx, llresult)
2015 pub fn trans_tuple_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2016 _fields: &[ast::StructField],
2017 ctor_id: ast::NodeId,
2018 param_substs: &'tcx Substs<'tcx>,
2019 llfndecl: ValueRef) {
2020 let _icx = push_ctxt("trans_tuple_struct");
2022 trans_enum_variant_or_tuple_like_struct(
2030 fn trans_enum_variant_or_tuple_like_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2031 ctor_id: ast::NodeId,
2033 param_substs: &'tcx Substs<'tcx>,
2034 llfndecl: ValueRef) {
2035 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2036 let ctor_ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &ctor_ty);
2038 let result_ty = match ctor_ty.sty {
2039 ty::ty_bare_fn(_, ref bft) => {
2040 ty::erase_late_bound_regions(ccx.tcx(), &bft.sig.output())
2042 _ => ccx.sess().bug(
2043 &format!("trans_enum_variant_or_tuple_like_struct: \
2044 unexpected ctor return type {}",
2045 ty_to_string(ccx.tcx(), ctor_ty))[])
2048 let (arena, fcx): (TypedArena<_>, FunctionContext);
2049 arena = TypedArena::new();
2050 fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
2051 param_substs, None, &arena);
2052 let bcx = init_function(&fcx, false, result_ty);
2054 assert!(!fcx.needs_ret_allocas);
2057 ty::erase_late_bound_regions(
2058 ccx.tcx(), &ty::ty_fn_args(ctor_ty));
2060 let arg_datums = create_datums_for_fn_args(&fcx, &arg_tys[..]);
2062 if !type_is_zero_size(fcx.ccx, result_ty.unwrap()) {
2063 let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot");
2064 let repr = adt::represent_type(ccx, result_ty.unwrap());
2065 for (i, arg_datum) in arg_datums.into_iter().enumerate() {
2066 let lldestptr = adt::trans_field_ptr(bcx,
2071 arg_datum.store_to(bcx, lldestptr);
2073 adt::trans_set_discr(bcx, &*repr, dest, disr);
2076 finish_fn(&fcx, bcx, result_ty, DebugLoc::None);
2079 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
2080 let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
2082 let print_info = ccx.sess().print_enum_sizes();
2084 let levels = ccx.tcx().node_lint_levels.borrow();
2085 let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCES);
2086 let lvlsrc = levels.get(&(id, lint_id));
2087 let is_allow = lvlsrc.map_or(true, |&(lvl, _)| lvl == lint::Allow);
2089 if is_allow && !print_info {
2090 // we're not interested in anything here
2094 let ty = ty::node_id_to_type(ccx.tcx(), id);
2095 let avar = adt::represent_type(ccx, ty);
2097 adt::General(_, ref variants, _) => {
2098 for var in variants {
2100 for field in var.fields.iter().skip(1) {
2101 // skip the discriminant
2102 size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
2107 _ => { /* its size is either constant or unimportant */ }
2110 let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
2111 |(l, s, li), (idx, &size)|
2114 } else if size > s {
2122 let llty = type_of::sizing_type_of(ccx, ty);
2124 let sess = &ccx.tcx().sess;
2125 sess.span_note(sp, &*format!("total size: {} bytes", llsize_of_real(ccx, llty)));
2127 adt::General(..) => {
2128 for (i, var) in enum_def.variants.iter().enumerate() {
2129 ccx.tcx().sess.span_note(var.span,
2130 &*format!("variant data: {} bytes", sizes[i]));
2137 // we only warn if the largest variant is at least thrice as large as
2138 // the second-largest.
2139 if !is_allow && largest > slargest * 3 && slargest > 0 {
2140 // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
2141 // pass for the latter already ran.
2142 lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCES,
2143 *lvlsrc.unwrap(), Some(sp),
2144 &format!("enum variant is more than three times larger \
2145 ({} bytes) than the next largest (ignoring padding)",
2148 ccx.sess().span_note(enum_def.variants[largest_index].span,
2149 "this variant is the largest");
2153 pub struct TransItemVisitor<'a, 'tcx: 'a> {
2154 pub ccx: &'a CrateContext<'a, 'tcx>,
2157 impl<'a, 'tcx, 'v> Visitor<'v> for TransItemVisitor<'a, 'tcx> {
2158 fn visit_item(&mut self, i: &ast::Item) {
2159 trans_item(self.ccx, i);
2163 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
2164 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2165 // applicable to variable declarations and may not really make sense for
2166 // Rust code in the first place but whitelist them anyway and trust that
2167 // the user knows what s/he's doing. Who knows, unanticipated use cases
2168 // may pop up in the future.
2170 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2171 // and don't have to be, LLVM treats them as no-ops.
2173 "appending" => Some(llvm::AppendingLinkage),
2174 "available_externally" => Some(llvm::AvailableExternallyLinkage),
2175 "common" => Some(llvm::CommonLinkage),
2176 "extern_weak" => Some(llvm::ExternalWeakLinkage),
2177 "external" => Some(llvm::ExternalLinkage),
2178 "internal" => Some(llvm::InternalLinkage),
2179 "linkonce" => Some(llvm::LinkOnceAnyLinkage),
2180 "linkonce_odr" => Some(llvm::LinkOnceODRLinkage),
2181 "private" => Some(llvm::PrivateLinkage),
2182 "weak" => Some(llvm::WeakAnyLinkage),
2183 "weak_odr" => Some(llvm::WeakODRLinkage),
2189 /// Enum describing the origin of an LLVM `Value`, for linkage purposes.
2191 pub enum ValueOrigin {
2192 /// The LLVM `Value` is in this context because the corresponding item was
2193 /// assigned to the current compilation unit.
2194 OriginalTranslation,
2195 /// The `Value`'s corresponding item was assigned to some other compilation
2196 /// unit, but the `Value` was translated in this context anyway because the
2197 /// item is marked `#[inline]`.
2201 /// Set the appropriate linkage for an LLVM `ValueRef` (function or global).
2202 /// If the `llval` is the direct translation of a specific Rust item, `id`
2203 /// should be set to the `NodeId` of that item. (This mapping should be
2204 /// 1-to-1, so monomorphizations and drop/visit glue should have `id` set to
2205 /// `None`.) `llval_origin` indicates whether `llval` is the translation of an
2206 /// item assigned to `ccx`'s compilation unit or an inlined copy of an item
2207 /// assigned to a different compilation unit.
2208 pub fn update_linkage(ccx: &CrateContext,
2210 id: Option<ast::NodeId>,
2211 llval_origin: ValueOrigin) {
2212 match llval_origin {
2214 // `llval` is a translation of an item defined in a separate
2215 // compilation unit. This only makes sense if there are at least
2216 // two compilation units.
2217 assert!(ccx.sess().opts.cg.codegen_units > 1);
2218 // `llval` is a copy of something defined elsewhere, so use
2219 // `AvailableExternallyLinkage` to avoid duplicating code in the
2221 llvm::SetLinkage(llval, llvm::AvailableExternallyLinkage);
2224 OriginalTranslation => {},
2227 if let Some(id) = id {
2228 let item = ccx.tcx().map.get(id);
2229 if let ast_map::NodeItem(i) = item {
2230 if let Some(name) = attr::first_attr_value_str_by_name(&i.attrs, "linkage") {
2231 if let Some(linkage) = llvm_linkage_by_name(&name) {
2232 llvm::SetLinkage(llval, linkage);
2234 ccx.sess().span_fatal(i.span, "invalid linkage specified");
2242 Some(id) if ccx.reachable().contains(&id) => {
2243 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2246 // `id` does not refer to an item in `ccx.reachable`.
2247 if ccx.sess().opts.cg.codegen_units > 1 {
2248 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2250 llvm::SetLinkage(llval, llvm::InternalLinkage);
2256 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
2257 let _icx = push_ctxt("trans_item");
2259 let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
2262 ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
2263 if !generics.is_type_parameterized() {
2264 let trans_everywhere = attr::requests_inline(&item.attrs[]);
2265 // Ignore `trans_everywhere` for cross-crate inlined items
2266 // (`from_external`). `trans_item` will be called once for each
2267 // compilation unit that references the item, so it will still get
2268 // translated everywhere it's needed.
2269 for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2270 let llfn = get_item_val(ccx, item.id);
2271 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
2273 foreign::trans_rust_fn_with_foreign_abi(ccx,
2293 if is_origin { OriginalTranslation } else { InlinedCopy });
2297 // Be sure to travel more than just one layer deep to catch nested
2298 // items in blocks and such.
2299 let mut v = TransItemVisitor{ ccx: ccx };
2300 v.visit_block(&**body);
2302 ast::ItemImpl(_, _, ref generics, _, _, ref impl_items) => {
2303 meth::trans_impl(ccx,
2309 ast::ItemMod(ref m) => {
2310 trans_mod(&ccx.rotate(), m);
2312 ast::ItemEnum(ref enum_definition, ref gens) => {
2313 if gens.ty_params.is_empty() {
2314 // sizes only make sense for non-generic types
2316 enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
2319 ast::ItemConst(_, ref expr) => {
2320 // Recurse on the expression to catch items in blocks
2321 let mut v = TransItemVisitor{ ccx: ccx };
2322 v.visit_expr(&**expr);
2324 ast::ItemStatic(_, m, ref expr) => {
2325 // Recurse on the expression to catch items in blocks
2326 let mut v = TransItemVisitor{ ccx: ccx };
2327 v.visit_expr(&**expr);
2329 consts::trans_static(ccx, m, item.id);
2330 let g = get_item_val(ccx, item.id);
2331 update_linkage(ccx, g, Some(item.id), OriginalTranslation);
2333 // Do static_assert checking. It can't really be done much earlier
2334 // because we need to get the value of the bool out of LLVM
2335 if attr::contains_name(&item.attrs[], "static_assert") {
2336 if m == ast::MutMutable {
2337 ccx.sess().span_fatal(expr.span,
2338 "cannot have static_assert on a mutable \
2342 let v = ccx.static_values().borrow()[item.id].clone();
2344 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2345 ccx.sess().span_fatal(expr.span, "static assertion failed");
2350 ast::ItemForeignMod(ref foreign_mod) => {
2351 foreign::trans_foreign_mod(ccx, foreign_mod);
2353 ast::ItemTrait(..) => {
2354 // Inside of this trait definition, we won't be actually translating any
2355 // functions, but the trait still needs to be walked. Otherwise default
2356 // methods with items will not get translated and will cause ICE's when
2357 // metadata time comes around.
2358 let mut v = TransItemVisitor{ ccx: ccx };
2359 visit::walk_item(&mut v, item);
2361 _ => {/* fall through */ }
2365 // Translate a module. Doing this amounts to translating the items in the
2366 // module; there ends up being no artifact (aside from linkage names) of
2367 // separate modules in the compiled program. That's because modules exist
2368 // only as a convenience for humans working with the code, to organize names
2369 // and control visibility.
2370 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
2371 let _icx = push_ctxt("trans_mod");
2372 for item in &m.items {
2373 trans_item(ccx, &**item);
2377 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
2379 ccx.item_symbols().borrow_mut().insert(node_id, sym);
2381 // The stack exhaustion lang item shouldn't have a split stack because
2382 // otherwise it would continue to be exhausted (bad), and both it and the
2383 // eh_personality functions need to be externally linkable.
2384 let def = ast_util::local_def(node_id);
2385 if ccx.tcx().lang_items.stack_exhausted() == Some(def) {
2386 unset_split_stack(llfn);
2387 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2389 if ccx.tcx().lang_items.eh_personality() == Some(def) {
2390 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2394 if is_entry_fn(ccx.sess(), node_id) {
2395 // check for the #[rustc_error] annotation, which forces an
2396 // error in trans. This is used to write compile-fail tests
2397 // that actually test that compilation succeeds without
2398 // reporting an error.
2399 if ty::has_attr(ccx.tcx(), local_def(node_id), "rustc_error") {
2400 ccx.tcx().sess.span_fatal(sp, "compilation successful");
2403 create_entry_wrapper(ccx, sp, llfn);
2407 fn register_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2410 node_id: ast::NodeId,
2411 node_type: Ty<'tcx>)
2413 match node_type.sty {
2414 ty::ty_bare_fn(_, ref f) => {
2415 assert!(f.abi == Rust || f.abi == RustCall);
2417 _ => panic!("expected bare rust fn")
2420 let llfn = decl_rust_fn(ccx, node_type, &sym[..]);
2421 finish_register_fn(ccx, sp, sym, node_id, llfn);
2425 pub fn get_fn_llvm_attributes<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty: Ty<'tcx>)
2426 -> llvm::AttrBuilder
2428 use middle::ty::{BrAnon, ReLateBound};
2431 let (fn_sig, abi, has_env) = match fn_ty.sty {
2432 ty::ty_bare_fn(_, ref f) => (&f.sig, f.abi, false),
2433 ty::ty_closure(closure_did, _, substs) => {
2434 let typer = common::NormalizingClosureTyper::new(ccx.tcx());
2435 function_type = typer.closure_type(closure_did, substs);
2436 (&function_type.sig, RustCall, true)
2438 _ => ccx.sess().bug("expected closure or function.")
2441 let fn_sig = ty::erase_late_bound_regions(ccx.tcx(), fn_sig);
2443 // Since index 0 is the return value of the llvm func, we start
2444 // at either 1 or 2 depending on whether there's an env slot or not
2445 let mut first_arg_offset = if has_env { 2 } else { 1 };
2446 let mut attrs = llvm::AttrBuilder::new();
2447 let ret_ty = fn_sig.output;
2449 // These have an odd calling convention, so we need to manually
2450 // unpack the input ty's
2451 let input_tys = match fn_ty.sty {
2452 ty::ty_closure(_, _, _) => {
2453 assert!(abi == RustCall);
2455 match fn_sig.inputs[0].sty {
2456 ty::ty_tup(ref inputs) => inputs.clone(),
2457 _ => ccx.sess().bug("expected tuple'd inputs")
2460 ty::ty_bare_fn(..) if abi == RustCall => {
2461 let mut inputs = vec![fn_sig.inputs[0]];
2463 match fn_sig.inputs[1].sty {
2464 ty::ty_tup(ref t_in) => {
2465 inputs.push_all(&t_in[..]);
2468 _ => ccx.sess().bug("expected tuple'd inputs")
2471 _ => fn_sig.inputs.clone()
2474 if let ty::FnConverging(ret_ty) = ret_ty {
2475 // A function pointer is called without the declaration
2476 // available, so we have to apply any attributes with ABI
2477 // implications directly to the call instruction. Right now,
2478 // the only attribute we need to worry about is `sret`.
2479 if type_of::return_uses_outptr(ccx, ret_ty) {
2480 let llret_sz = llsize_of_real(ccx, type_of::type_of(ccx, ret_ty));
2482 // The outptr can be noalias and nocapture because it's entirely
2483 // invisible to the program. We also know it's nonnull as well
2484 // as how many bytes we can dereference
2485 attrs.arg(1, llvm::StructRetAttribute)
2486 .arg(1, llvm::NoAliasAttribute)
2487 .arg(1, llvm::NoCaptureAttribute)
2488 .arg(1, llvm::DereferenceableAttribute(llret_sz));
2490 // Add one more since there's an outptr
2491 first_arg_offset += 1;
2493 // The `noalias` attribute on the return value is useful to a
2494 // function ptr caller.
2496 // `~` pointer return values never alias because ownership
2498 ty::ty_uniq(it) if !common::type_is_sized(ccx.tcx(), it) => {}
2500 attrs.ret(llvm::NoAliasAttribute);
2505 // We can also mark the return value as `dereferenceable` in certain cases
2507 // These are not really pointers but pairs, (pointer, len)
2509 ty::ty_rptr(_, ty::mt { ty: it, .. }) if !common::type_is_sized(ccx.tcx(), it) => {}
2510 ty::ty_uniq(inner) | ty::ty_rptr(_, ty::mt { ty: inner, .. }) => {
2511 let llret_sz = llsize_of_real(ccx, type_of::type_of(ccx, inner));
2512 attrs.ret(llvm::DereferenceableAttribute(llret_sz));
2517 if let ty::ty_bool = ret_ty.sty {
2518 attrs.ret(llvm::ZExtAttribute);
2523 for (idx, &t) in input_tys.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
2525 // this needs to be first to prevent fat pointers from falling through
2526 _ if !type_is_immediate(ccx, t) => {
2527 let llarg_sz = llsize_of_real(ccx, type_of::type_of(ccx, t));
2529 // For non-immediate arguments the callee gets its own copy of
2530 // the value on the stack, so there are no aliases. It's also
2531 // program-invisible so can't possibly capture
2532 attrs.arg(idx, llvm::NoAliasAttribute)
2533 .arg(idx, llvm::NoCaptureAttribute)
2534 .arg(idx, llvm::DereferenceableAttribute(llarg_sz));
2538 attrs.arg(idx, llvm::ZExtAttribute);
2541 // `~` pointer parameters never alias because ownership is transferred
2542 ty::ty_uniq(inner) => {
2543 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, inner));
2545 attrs.arg(idx, llvm::NoAliasAttribute)
2546 .arg(idx, llvm::DereferenceableAttribute(llsz));
2549 // `&mut` pointer parameters never alias other parameters, or mutable global data
2551 // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as both
2552 // `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely on
2553 // memory dependencies rather than pointer equality
2554 ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable ||
2555 !ty::type_contents(ccx.tcx(), mt.ty).interior_unsafe() => {
2557 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2558 attrs.arg(idx, llvm::NoAliasAttribute)
2559 .arg(idx, llvm::DereferenceableAttribute(llsz));
2561 if mt.mutbl == ast::MutImmutable {
2562 attrs.arg(idx, llvm::ReadOnlyAttribute);
2565 if let ReLateBound(_, BrAnon(_)) = *b {
2566 attrs.arg(idx, llvm::NoCaptureAttribute);
2570 // When a reference in an argument has no named lifetime, it's impossible for that
2571 // reference to escape this function (returned or stored beyond the call by a closure).
2572 ty::ty_rptr(&ReLateBound(_, BrAnon(_)), mt) => {
2573 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2574 attrs.arg(idx, llvm::NoCaptureAttribute)
2575 .arg(idx, llvm::DereferenceableAttribute(llsz));
2578 // & pointer parameters are also never null and we know exactly how
2579 // many bytes we can dereference
2580 ty::ty_rptr(_, mt) => {
2581 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2582 attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
2591 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2592 pub fn register_fn_llvmty(ccx: &CrateContext,
2595 node_id: ast::NodeId,
2597 llfty: Type) -> ValueRef {
2598 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2600 let llfn = decl_fn(ccx,
2604 ty::FnConverging(ty::mk_nil(ccx.tcx())));
2605 finish_register_fn(ccx, sp, sym, node_id, llfn);
2609 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2610 match *sess.entry_fn.borrow() {
2611 Some((entry_id, _)) => node_id == entry_id,
2616 // Create a _rust_main(args: ~[str]) function which will be called from the
2617 // runtime rust_start function
2618 pub fn create_entry_wrapper(ccx: &CrateContext,
2620 main_llfn: ValueRef) {
2621 let et = ccx.sess().entry_type.get().unwrap();
2623 config::EntryMain => {
2624 create_entry_fn(ccx, main_llfn, true);
2626 config::EntryStart => create_entry_fn(ccx, main_llfn, false),
2627 config::EntryNone => {} // Do nothing.
2630 fn create_entry_fn(ccx: &CrateContext,
2631 rust_main: ValueRef,
2632 use_start_lang_item: bool) {
2633 let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()],
2636 let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil(ccx.tcx()));
2638 // FIXME: #16581: Marking a symbol in the executable with `dllexport`
2639 // linkage forces MinGW's linker to output a `.reloc` section for ASLR
2640 if ccx.sess().target.target.options.is_like_windows {
2641 unsafe { llvm::LLVMRustSetDLLExportStorageClass(llfn) }
2645 llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn,
2646 "top\0".as_ptr() as *const _)
2648 let bld = ccx.raw_builder();
2650 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2652 debuginfo::insert_reference_to_gdb_debug_scripts_section_global(ccx);
2654 let (start_fn, args) = if use_start_lang_item {
2655 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2657 Err(s) => { ccx.sess().fatal(&s[..]); }
2659 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2660 get_item_val(ccx, start_def_id.node)
2662 let start_fn_type = csearch::get_type(ccx.tcx(),
2664 trans_external_path(ccx, start_def_id, start_fn_type)
2668 let opaque_rust_main = llvm::LLVMBuildPointerCast(bld,
2669 rust_main, Type::i8p(ccx).to_ref(),
2670 "rust_main\0".as_ptr() as *const _);
2680 debug!("using user-defined start fn");
2682 get_param(llfn, 0 as c_uint),
2683 get_param(llfn, 1 as c_uint)
2689 let result = llvm::LLVMBuildCall(bld,
2692 args.len() as c_uint,
2695 llvm::LLVMBuildRet(bld, result);
2700 fn exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, id: ast::NodeId,
2701 ty: Ty<'tcx>, attrs: &[ast::Attribute]) -> String {
2702 match ccx.external_srcs().borrow().get(&id) {
2704 let sym = csearch::get_symbol(&ccx.sess().cstore, did);
2705 debug!("found item {} in other crate...", sym);
2711 match attr::first_attr_value_str_by_name(attrs, "export_name") {
2712 // Use provided name
2713 Some(name) => name.to_string(),
2715 _ => ccx.tcx().map.with_path(id, |path| {
2716 if attr::contains_name(attrs, "no_mangle") {
2718 path.last().unwrap().to_string()
2720 match weak_lang_items::link_name(attrs) {
2721 Some(name) => name.to_string(),
2723 // Usual name mangling
2724 mangle_exported_name(ccx, path, ty, id)
2732 fn contains_null(s: &str) -> bool {
2733 s.bytes().any(|b| b == 0)
2736 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2737 debug!("get_item_val(id=`{}`)", id);
2739 match ccx.item_vals().borrow().get(&id).cloned() {
2740 Some(v) => return v,
2744 let item = ccx.tcx().map.get(id);
2745 debug!("get_item_val: id={} item={:?}", id, item);
2746 let val = match item {
2747 ast_map::NodeItem(i) => {
2748 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2749 let sym = || exported_name(ccx, id, ty, &i.attrs[]);
2751 let v = match i.node {
2752 ast::ItemStatic(_, _, ref expr) => {
2753 // If this static came from an external crate, then
2754 // we need to get the symbol from csearch instead of
2755 // using the current crate's name/version
2756 // information in the hash of the symbol
2758 debug!("making {}", sym);
2760 // We need the translated value here, because for enums the
2761 // LLVM type is not fully determined by the Rust type.
2762 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
2763 let (v, ty) = consts::const_expr(ccx, &**expr, empty_substs);
2764 ccx.static_values().borrow_mut().insert(id, v);
2766 // boolean SSA values are i1, but they have to be stored in i8 slots,
2767 // otherwise some LLVM optimization passes don't work as expected
2768 let llty = if ty::type_is_bool(ty) {
2769 llvm::LLVMInt8TypeInContext(ccx.llcx())
2773 if contains_null(&sym[..]) {
2775 &format!("Illegal null byte in export_name \
2776 value: `{}`", sym)[]);
2778 let buf = CString::new(sym.clone()).unwrap();
2779 let g = llvm::LLVMAddGlobal(ccx.llmod(), llty,
2782 if attr::contains_name(&i.attrs[],
2784 llvm::set_thread_local(g, true);
2786 ccx.item_symbols().borrow_mut().insert(i.id, sym);
2791 ast::ItemFn(_, _, abi, _, _) => {
2793 let llfn = if abi == Rust {
2794 register_fn(ccx, i.span, sym, i.id, ty)
2796 foreign::register_rust_fn_with_foreign_abi(ccx,
2801 set_llvm_fn_attrs(ccx, &i.attrs[], llfn);
2805 _ => panic!("get_item_val: weird result in table")
2808 match attr::first_attr_value_str_by_name(&i.attrs[],
2811 if contains_null(§) {
2812 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`",
2816 let buf = CString::new(sect.as_bytes()).unwrap();
2817 llvm::LLVMSetSection(v, buf.as_ptr());
2826 ast_map::NodeTraitItem(trait_method) => {
2827 debug!("get_item_val(): processing a NodeTraitItem");
2828 match *trait_method {
2829 ast::RequiredMethod(_) | ast::TypeTraitItem(_) => {
2830 ccx.sess().bug("unexpected variant: required trait \
2831 method in get_item_val()");
2833 ast::ProvidedMethod(ref m) => {
2834 register_method(ccx, id, &**m)
2839 ast_map::NodeImplItem(ii) => {
2841 ast::MethodImplItem(ref m) => register_method(ccx, id, &**m),
2842 ast::TypeImplItem(ref typedef) => {
2843 ccx.sess().span_bug(typedef.span,
2844 "unexpected variant: required impl \
2845 method in get_item_val()")
2850 ast_map::NodeForeignItem(ni) => {
2852 ast::ForeignItemFn(..) => {
2853 let abi = ccx.tcx().map.get_foreign_abi(id);
2854 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2855 let name = foreign::link_name(&*ni);
2856 foreign::register_foreign_item_fn(ccx, abi, ty, &name)
2858 ast::ForeignItemStatic(..) => {
2859 foreign::register_static(ccx, &*ni)
2864 ast_map::NodeVariant(ref v) => {
2866 let args = match v.node.kind {
2867 ast::TupleVariantKind(ref args) => args,
2868 ast::StructVariantKind(_) => {
2869 panic!("struct variant kind unexpected in get_item_val")
2872 assert!(args.len() != 0);
2873 let ty = ty::node_id_to_type(ccx.tcx(), id);
2874 let parent = ccx.tcx().map.get_parent(id);
2875 let enm = ccx.tcx().map.expect_item(parent);
2876 let sym = exported_name(ccx,
2881 llfn = match enm.node {
2882 ast::ItemEnum(_, _) => {
2883 register_fn(ccx, (*v).span, sym, id, ty)
2885 _ => panic!("NodeVariant, shouldn't happen")
2887 set_inline_hint(llfn);
2891 ast_map::NodeStructCtor(struct_def) => {
2892 // Only register the constructor if this is a tuple-like struct.
2893 let ctor_id = match struct_def.ctor_id {
2895 ccx.sess().bug("attempt to register a constructor of \
2896 a non-tuple-like struct")
2898 Some(ctor_id) => ctor_id,
2900 let parent = ccx.tcx().map.get_parent(id);
2901 let struct_item = ccx.tcx().map.expect_item(parent);
2902 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2903 let sym = exported_name(ccx,
2906 &struct_item.attrs[]);
2907 let llfn = register_fn(ccx, struct_item.span,
2909 set_inline_hint(llfn);
2914 ccx.sess().bug(&format!("get_item_val(): unexpected variant: {:?}",
2919 // All LLVM globals and functions are initially created as external-linkage
2920 // declarations. If `trans_item`/`trans_fn` later turns the declaration
2921 // into a definition, it adjusts the linkage then (using `update_linkage`).
2923 // The exception is foreign items, which have their linkage set inside the
2924 // call to `foreign::register_*` above. We don't touch the linkage after
2925 // that (`foreign::trans_foreign_mod` doesn't adjust the linkage like the
2926 // other item translation functions do).
2928 ccx.item_vals().borrow_mut().insert(id, val);
2932 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2933 m: &ast::Method) -> ValueRef {
2934 let mty = ty::node_id_to_type(ccx.tcx(), id);
2936 let sym = exported_name(ccx, id, mty, &m.attrs[]);
2938 let llfn = register_fn(ccx, m.span, sym, id, mty);
2939 set_llvm_fn_attrs(ccx, &m.attrs[], llfn);
2943 pub fn crate_ctxt_to_encode_parms<'a, 'tcx>(cx: &'a SharedCrateContext<'tcx>,
2944 ie: encoder::EncodeInlinedItem<'a>)
2945 -> encoder::EncodeParams<'a, 'tcx> {
2946 encoder::EncodeParams {
2947 diag: cx.sess().diagnostic(),
2949 reexports: cx.export_map(),
2950 item_symbols: cx.item_symbols(),
2951 link_meta: cx.link_meta(),
2952 cstore: &cx.sess().cstore,
2953 encode_inlined_item: ie,
2954 reachable: cx.reachable(),
2958 pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
2961 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2962 *ty != config::CrateTypeExecutable
2968 let encode_inlined_item: encoder::EncodeInlinedItem =
2969 box |ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii);
2971 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2972 let metadata = encoder::encode_metadata(encode_parms, krate);
2973 let mut compressed = encoder::metadata_encoding_version.to_vec();
2974 compressed.push_all(&match flate::deflate_bytes(&metadata) {
2975 Some(compressed) => compressed,
2976 None => cx.sess().fatal("failed to compress metadata"),
2978 let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
2979 let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
2980 let name = format!("rust_metadata_{}_{}",
2981 cx.link_meta().crate_name,
2982 cx.link_meta().crate_hash);
2983 let buf = CString::new(name).unwrap();
2984 let llglobal = unsafe {
2985 llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(),
2989 llvm::LLVMSetInitializer(llglobal, llconst);
2990 let name = loader::meta_section_name(cx.sess().target.target.options.is_like_osx);
2991 let name = CString::new(name).unwrap();
2992 llvm::LLVMSetSection(llglobal, name.as_ptr())
2997 /// Find any symbols that are defined in one compilation unit, but not declared
2998 /// in any other compilation unit. Give these symbols internal linkage.
2999 fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
3001 let mut declared = HashSet::new();
3003 let iter_globals = |llmod| {
3005 cur: llvm::LLVMGetFirstGlobal(llmod),
3006 step: llvm::LLVMGetNextGlobal,
3010 let iter_functions = |llmod| {
3012 cur: llvm::LLVMGetFirstFunction(llmod),
3013 step: llvm::LLVMGetNextFunction,
3017 // Collect all external declarations in all compilation units.
3018 for ccx in cx.iter() {
3019 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
3020 let linkage = llvm::LLVMGetLinkage(val);
3021 // We only care about external declarations (not definitions)
3022 // and available_externally definitions.
3023 if !(linkage == llvm::ExternalLinkage as c_uint &&
3024 llvm::LLVMIsDeclaration(val) != 0) &&
3025 !(linkage == llvm::AvailableExternallyLinkage as c_uint) {
3029 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
3030 .to_bytes().to_vec();
3031 declared.insert(name);
3035 // Examine each external definition. If the definition is not used in
3036 // any other compilation unit, and is not reachable from other crates,
3037 // then give it internal linkage.
3038 for ccx in cx.iter() {
3039 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
3040 // We only care about external definitions.
3041 if !(llvm::LLVMGetLinkage(val) == llvm::ExternalLinkage as c_uint &&
3042 llvm::LLVMIsDeclaration(val) == 0) {
3046 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
3047 .to_bytes().to_vec();
3048 if !declared.contains(&name) &&
3049 !reachable.contains(str::from_utf8(&name).unwrap()) {
3050 llvm::SetLinkage(val, llvm::InternalLinkage);
3059 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
3062 impl Iterator for ValueIter {
3063 type Item = ValueRef;
3065 fn next(&mut self) -> Option<ValueRef> {
3069 let step: unsafe extern "C" fn(ValueRef) -> ValueRef =
3070 mem::transmute_copy(&self.step);
3081 pub fn trans_crate<'tcx>(analysis: ty::CrateAnalysis<'tcx>)
3082 -> (ty::ctxt<'tcx>, CrateTranslation) {
3083 let ty::CrateAnalysis { ty_cx: tcx, export_map, reachable, name, .. } = analysis;
3084 let krate = tcx.map.krate();
3086 // Before we touch LLVM, make sure that multithreading is enabled.
3088 use std::sync::{Once, ONCE_INIT};
3089 static INIT: Once = ONCE_INIT;
3090 static mut POISONED: bool = false;
3092 if llvm::LLVMStartMultithreaded() != 1 {
3093 // use an extra bool to make sure that all future usage of LLVM
3094 // cannot proceed despite the Once not running more than once.
3100 tcx.sess.bug("couldn't enable multi-threaded LLVM");
3104 let link_meta = link::build_link_meta(&tcx.sess, krate, name);
3106 let codegen_units = tcx.sess.opts.cg.codegen_units;
3107 let shared_ccx = SharedCrateContext::new(&link_meta.crate_name[],
3116 let ccx = shared_ccx.get_ccx(0);
3118 // First, verify intrinsics.
3119 intrinsic::check_intrinsics(&ccx);
3121 // Next, translate the module.
3123 let _icx = push_ctxt("text");
3124 trans_mod(&ccx, &krate.module);
3128 for ccx in shared_ccx.iter() {
3129 glue::emit_tydescs(&ccx);
3130 if ccx.sess().opts.debuginfo != NoDebugInfo {
3131 debuginfo::finalize(&ccx);
3135 // Translate the metadata.
3136 let metadata = write_metadata(&shared_ccx, krate);
3138 if shared_ccx.sess().trans_stats() {
3139 let stats = shared_ccx.stats();
3140 println!("--- trans stats ---");
3141 println!("n_static_tydescs: {}", stats.n_static_tydescs.get());
3142 println!("n_glues_created: {}", stats.n_glues_created.get());
3143 println!("n_null_glues: {}", stats.n_null_glues.get());
3144 println!("n_real_glues: {}", stats.n_real_glues.get());
3146 println!("n_fns: {}", stats.n_fns.get());
3147 println!("n_monos: {}", stats.n_monos.get());
3148 println!("n_inlines: {}", stats.n_inlines.get());
3149 println!("n_closures: {}", stats.n_closures.get());
3150 println!("fn stats:");
3151 stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
3152 insns_b.cmp(&insns_a)
3154 for tuple in &*stats.fn_stats.borrow() {
3156 (ref name, insns) => {
3157 println!("{} insns, {}", insns, *name);
3162 if shared_ccx.sess().count_llvm_insns() {
3163 for (k, v) in &*shared_ccx.stats().llvm_insns.borrow() {
3164 println!("{:7} {}", *v, *k);
3168 let modules = shared_ccx.iter()
3169 .map(|ccx| ModuleTranslation { llcx: ccx.llcx(), llmod: ccx.llmod() })
3172 let mut reachable: Vec<String> = shared_ccx.reachable().iter().filter_map(|id| {
3173 shared_ccx.item_symbols().borrow().get(id).map(|s| s.to_string())
3176 // For the purposes of LTO, we add to the reachable set all of the upstream
3177 // reachable extern fns. These functions are all part of the public ABI of
3178 // the final product, so LTO needs to preserve them.
3179 shared_ccx.sess().cstore.iter_crate_data(|cnum, _| {
3180 let syms = csearch::get_reachable_extern_fns(&shared_ccx.sess().cstore, cnum);
3181 reachable.extend(syms.into_iter().map(|did| {
3182 csearch::get_symbol(&shared_ccx.sess().cstore, did)
3186 // Make sure that some other crucial symbols are not eliminated from the
3187 // module. This includes the main function, the crate map (used for debug
3188 // log settings and I/O), and finally the curious rust_stack_exhausted
3189 // symbol. This symbol is required for use by the libmorestack library that
3190 // we link in, so we must ensure that this symbol is not internalized (if
3191 // defined in the crate).
3192 reachable.push("main".to_string());
3193 reachable.push("rust_stack_exhausted".to_string());
3195 // referenced from .eh_frame section on some platforms
3196 reachable.push("rust_eh_personality".to_string());
3197 // referenced from rt/rust_try.ll
3198 reachable.push("rust_eh_personality_catch".to_string());
3200 if codegen_units > 1 {
3201 internalize_symbols(&shared_ccx, &reachable.iter().cloned().collect());
3204 let metadata_module = ModuleTranslation {
3205 llcx: shared_ccx.metadata_llcx(),
3206 llmod: shared_ccx.metadata_llmod(),
3208 let formats = shared_ccx.tcx().dependency_formats.borrow().clone();
3209 let no_builtins = attr::contains_name(&krate.attrs[], "no_builtins");
3211 let translation = CrateTranslation {
3213 metadata_module: metadata_module,
3216 reachable: reachable,
3217 crate_formats: formats,
3218 no_builtins: no_builtins,
3221 (shared_ccx.take_tcx(), translation)