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::t 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::t`s; for instance, tup(int, int,
24 // int) and rec(x=int, y=int, z=int) will have the same TypeRef.
26 #![allow(non_camel_case_types)]
28 use back::link::{mangle_exported_name};
29 use back::{link, abi};
31 use driver::config::{NoDebugInfo, FullDebugInfo};
32 use driver::session::Session;
33 use driver::driver::{CrateAnalysis, CrateTranslation};
35 use llvm::{ModuleRef, ValueRef, BasicBlockRef};
37 use metadata::{csearch, encoder, loader};
39 use middle::astencode;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::weak_lang_items;
43 use middle::subst::Subst;
44 use middle::trans::_match;
45 use middle::trans::adt;
46 use middle::trans::build::*;
47 use middle::trans::builder::{Builder, noname};
48 use middle::trans::callee;
49 use middle::trans::cleanup;
50 use middle::trans::cleanup::CleanupMethods;
51 use middle::trans::common::*;
52 use middle::trans::consts;
53 use middle::trans::controlflow;
54 use middle::trans::datum;
55 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
56 use middle::trans::debuginfo;
57 use middle::trans::expr;
58 use middle::trans::foreign;
59 use middle::trans::glue;
60 use middle::trans::inline;
61 use middle::trans::intrinsic;
62 use middle::trans::machine;
63 use middle::trans::machine::{llalign_of_min, llsize_of, llsize_of_real};
64 use middle::trans::meth;
65 use middle::trans::monomorphize;
66 use middle::trans::tvec;
67 use middle::trans::type_::Type;
68 use middle::trans::type_of;
69 use middle::trans::type_of::*;
70 use middle::trans::value::Value;
73 use util::common::indenter;
74 use util::ppaux::{Repr, ty_to_string};
75 use util::sha2::Sha256;
76 use util::nodemap::NodeMap;
78 use arena::TypedArena;
79 use libc::{c_uint, uint64_t};
80 use std::c_str::ToCStr;
81 use std::cell::{Cell, RefCell};
83 use std::{i8, i16, i32, i64};
85 use syntax::abi::{X86, X86_64, Arm, Mips, Mipsel, Rust, RustIntrinsic};
86 use syntax::ast_util::{local_def, is_local};
87 use syntax::attr::AttrMetaMethods;
89 use syntax::codemap::Span;
90 use syntax::parse::token::InternedString;
91 use syntax::visit::Visitor;
93 use syntax::{ast, ast_util, ast_map};
97 local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)
99 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
100 match task_local_insn_key.get() {
101 Some(ctx) => blk(ctx.borrow().as_slice()),
106 pub fn init_insn_ctxt() {
107 task_local_insn_key.replace(Some(RefCell::new(Vec::new())));
110 pub struct _InsnCtxt {
111 _cannot_construct_outside_of_this_module: ()
115 impl Drop for _InsnCtxt {
117 match task_local_insn_key.get() {
118 Some(ctx) => { ctx.borrow_mut().pop(); }
124 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
125 debug!("new InsnCtxt: {}", s);
126 match task_local_insn_key.get() {
127 Some(ctx) => ctx.borrow_mut().push(s),
130 _InsnCtxt { _cannot_construct_outside_of_this_module: () }
133 pub struct StatRecorder<'a> {
134 ccx: &'a CrateContext,
135 name: Option<String>,
140 impl<'a> StatRecorder<'a> {
141 pub fn new(ccx: &'a CrateContext, name: String) -> StatRecorder<'a> {
142 let start = if ccx.sess().trans_stats() {
143 time::precise_time_ns()
147 let istart = ccx.stats.n_llvm_insns.get();
158 impl<'a> Drop for StatRecorder<'a> {
160 if self.ccx.sess().trans_stats() {
161 let end = time::precise_time_ns();
162 let elapsed = ((end - self.start) / 1_000_000) as uint;
163 let iend = self.ccx.stats.n_llvm_insns.get();
164 self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
166 iend - self.istart));
167 self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
168 // Reset LLVM insn count to avoid compound costs.
169 self.ccx.stats.n_llvm_insns.set(self.istart);
174 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
175 fn decl_fn(ccx: &CrateContext, name: &str, cc: llvm::CallConv,
176 ty: Type, output: ty::t) -> ValueRef {
178 let llfn: ValueRef = name.with_c_str(|buf| {
180 llvm::LLVMGetOrInsertFunction(ccx.llmod, buf, ty.to_ref())
184 match ty::get(output).sty {
185 // functions returning bottom may unwind, but can never return normally
188 llvm::LLVMAddFunctionAttribute(llfn,
189 llvm::FunctionIndex as c_uint,
190 llvm::NoReturnAttribute as uint64_t)
196 llvm::SetFunctionCallConv(llfn, cc);
197 // Function addresses in Rust are never significant, allowing functions to be merged.
198 llvm::SetUnnamedAddr(llfn, true);
200 if ccx.is_split_stack_supported() {
201 set_split_stack(llfn);
207 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
208 pub fn decl_cdecl_fn(ccx: &CrateContext,
211 output: ty::t) -> ValueRef {
212 decl_fn(ccx, name, llvm::CCallConv, ty, output)
215 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
216 pub fn get_extern_fn(ccx: &CrateContext,
217 externs: &mut ExternMap,
223 match externs.find_equiv(&name) {
224 Some(n) => return *n,
227 let f = decl_fn(ccx, name, cc, ty, output);
228 externs.insert(name.to_string(), f);
232 fn get_extern_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str, did: ast::DefId) -> ValueRef {
233 match ccx.externs.borrow().find_equiv(&name) {
234 Some(n) => return *n,
238 let f = decl_rust_fn(ccx, fn_ty, name);
240 csearch::get_item_attrs(&ccx.sess().cstore, did, |attrs| {
241 set_llvm_fn_attrs(attrs.as_slice(), f)
244 ccx.externs.borrow_mut().insert(name.to_string(), f);
248 pub fn decl_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
249 let (inputs, output, has_env) = match ty::get(fn_ty).sty {
250 ty::ty_bare_fn(ref f) => (f.sig.inputs.clone(), f.sig.output, false),
251 ty::ty_closure(ref f) => (f.sig.inputs.clone(), f.sig.output, true),
252 _ => fail!("expected closure or fn")
255 let llfty = type_of_rust_fn(ccx, has_env, inputs.as_slice(), output);
256 let llfn = decl_fn(ccx, name, llvm::CCallConv, llfty, output);
257 let attrs = get_fn_llvm_attributes(ccx, fn_ty);
258 for &(idx, attr) in attrs.iter() {
260 llvm::LLVMAddFunctionAttribute(llfn, idx as c_uint, attr);
267 pub fn decl_internal_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
268 let llfn = decl_rust_fn(ccx, fn_ty, name);
269 llvm::SetLinkage(llfn, llvm::InternalLinkage);
273 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
274 name: &str, ty: Type) -> ValueRef {
275 match externs.find_equiv(&name) {
276 Some(n) => return *n,
280 let c = name.with_c_str(|buf| {
281 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
283 externs.insert(name.to_string(), c);
288 // Returns a pointer to the body for the box. The box may be an opaque
289 // box. The result will be casted to the type of body_t, if it is statically
291 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
292 let _icx = push_ctxt("at_box_body");
294 let ty = Type::at_box(ccx, type_of(ccx, body_t));
295 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
296 GEPi(bcx, boxptr, [0u, abi::box_field_body])
299 fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
300 match bcx.tcx().lang_items.require(it) {
303 bcx.sess().fatal(format!("allocation of `{}` {}",
304 bcx.ty_to_string(info_ty),
310 // The following malloc_raw_dyn* functions allocate a box to contain
311 // a given type, but with a potentially dynamic size.
313 pub fn malloc_raw_dyn<'a>(bcx: &'a Block<'a>,
318 let _icx = push_ctxt("malloc_raw_exchange");
322 let r = callee::trans_lang_call(bcx,
323 require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
327 let llty_ptr = type_of::type_of(ccx, ptr_ty);
328 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
331 pub fn malloc_raw_dyn_managed<'a>(
337 let _icx = push_ctxt("malloc_raw_managed");
340 let langcall = require_alloc_fn(bcx, t, alloc_fn);
342 // Grab the TypeRef type of box_ptr_ty.
343 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
344 let llty = type_of(ccx, box_ptr_ty);
345 let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
348 let drop_glue = glue::get_drop_glue(ccx, t);
349 let r = callee::trans_lang_call(
353 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
358 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
361 // Type descriptor and type glue stuff
363 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
364 match ccx.tydescs.borrow().find(&t) {
365 Some(inf) => return inf.clone(),
369 ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
370 let inf = Rc::new(glue::declare_tydesc(ccx, t));
372 ccx.tydescs.borrow_mut().insert(t, inf.clone());
376 #[allow(dead_code)] // useful
377 pub fn set_optimize_for_size(f: ValueRef) {
378 llvm::SetFunctionAttribute(f, llvm::OptimizeForSizeAttribute)
381 pub fn set_no_inline(f: ValueRef) {
382 llvm::SetFunctionAttribute(f, llvm::NoInlineAttribute)
385 #[allow(dead_code)] // useful
386 pub fn set_no_unwind(f: ValueRef) {
387 llvm::SetFunctionAttribute(f, llvm::NoUnwindAttribute)
390 // Tell LLVM to emit the information necessary to unwind the stack for the
392 pub fn set_uwtable(f: ValueRef) {
393 llvm::SetFunctionAttribute(f, llvm::UWTableAttribute)
396 pub fn set_inline_hint(f: ValueRef) {
397 llvm::SetFunctionAttribute(f, llvm::InlineHintAttribute)
400 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
402 // Set the inline hint if there is one
403 match find_inline_attr(attrs) {
404 InlineHint => set_inline_hint(llfn),
405 InlineAlways => set_always_inline(llfn),
406 InlineNever => set_no_inline(llfn),
407 InlineNone => { /* fallthrough */ }
410 // Add the no-split-stack attribute if requested
411 if contains_name(attrs, "no_split_stack") {
412 unset_split_stack(llfn);
415 if contains_name(attrs, "cold") {
417 llvm::LLVMAddFunctionAttribute(llfn,
418 llvm::FunctionIndex as c_uint,
419 llvm::ColdAttribute as uint64_t)
424 pub fn set_always_inline(f: ValueRef) {
425 llvm::SetFunctionAttribute(f, llvm::AlwaysInlineAttribute)
428 pub fn set_split_stack(f: ValueRef) {
429 "split-stack".with_c_str(|buf| {
430 unsafe { llvm::LLVMAddFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
434 pub fn unset_split_stack(f: ValueRef) {
435 "split-stack".with_c_str(|buf| {
436 unsafe { llvm::LLVMRemoveFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
440 // Double-check that we never ask LLVM to declare the same symbol twice. It
441 // silently mangles such symbols, breaking our linkage model.
442 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) {
443 if ccx.all_llvm_symbols.borrow().contains(&sym) {
444 ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).as_slice());
446 ccx.all_llvm_symbols.borrow_mut().insert(sym);
450 pub fn get_res_dtor(ccx: &CrateContext,
453 parent_id: ast::DefId,
454 substs: &subst::Substs)
456 let _icx = push_ctxt("trans_res_dtor");
457 let did = if did.krate != ast::LOCAL_CRATE {
458 inline::maybe_instantiate_inline(ccx, did)
463 if !substs.types.is_empty() {
464 assert_eq!(did.krate, ast::LOCAL_CRATE);
466 let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, substs);
467 let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, vtables, None);
470 } else if did.krate == ast::LOCAL_CRATE {
471 get_item_val(ccx, did.node)
474 let name = csearch::get_symbol(&ccx.sess().cstore, did);
475 let class_ty = ty::lookup_item_type(tcx, parent_id).ty.subst(tcx, substs);
476 let llty = type_of_dtor(ccx, class_ty);
477 let dtor_ty = ty::mk_ctor_fn(ccx.tcx(), ast::DUMMY_NODE_ID,
478 [glue::get_drop_glue_type(ccx, t)], ty::mk_nil());
480 &mut *ccx.externs.borrow_mut(),
488 // Structural comparison: a rather involved form of glue.
489 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
490 if cx.sess().opts.cg.save_temps {
493 llvm::LLVMSetValueName(v, buf)
500 // Used only for creating scalar comparison glue.
501 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
503 pub fn compare_scalar_types<'a>(
510 let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
512 match ty::get(t).sty {
513 ty::ty_nil => f(nil_type),
514 ty::ty_bool | ty::ty_ptr(_) |
515 ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
516 ty::ty_int(_) => f(signed_int),
517 ty::ty_float(_) => f(floating_point),
518 // Should never get here, because t is scalar.
519 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
524 // A helper function to do the actual comparison of scalar values.
525 pub fn compare_scalar_values<'a>(
532 let _icx = push_ctxt("compare_scalar_values");
533 fn die(cx: &Block) -> ! {
534 cx.sess().bug("compare_scalar_values: must be a comparison operator");
538 // We don't need to do actual comparisons for nil.
539 // () == () holds but () < () does not.
541 ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(cx.ccx(), true),
542 ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(cx.ccx(), false),
543 // refinements would be nice
549 ast::BiEq => llvm::RealOEQ,
550 ast::BiNe => llvm::RealUNE,
551 ast::BiLt => llvm::RealOLT,
552 ast::BiLe => llvm::RealOLE,
553 ast::BiGt => llvm::RealOGT,
554 ast::BiGe => llvm::RealOGE,
557 return FCmp(cx, cmp, lhs, rhs);
561 ast::BiEq => llvm::IntEQ,
562 ast::BiNe => llvm::IntNE,
563 ast::BiLt => llvm::IntSLT,
564 ast::BiLe => llvm::IntSLE,
565 ast::BiGt => llvm::IntSGT,
566 ast::BiGe => llvm::IntSGE,
569 return ICmp(cx, cmp, lhs, rhs);
573 ast::BiEq => llvm::IntEQ,
574 ast::BiNe => llvm::IntNE,
575 ast::BiLt => llvm::IntULT,
576 ast::BiLe => llvm::IntULE,
577 ast::BiGt => llvm::IntUGT,
578 ast::BiGe => llvm::IntUGE,
581 return ICmp(cx, cmp, lhs, rhs);
586 pub fn compare_simd_types(
594 match ty::get(t).sty {
596 // The comparison operators for floating point vectors are challenging.
597 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
598 // then bitcast to a floating point vector, the result will be `-NaN`
599 // for each truth value. Because of this they are unsupported.
600 cx.sess().bug("compare_simd_types: comparison operators \
601 not supported for floating point SIMD types")
603 ty::ty_uint(_) | ty::ty_int(_) => {
605 ast::BiEq => llvm::IntEQ,
606 ast::BiNe => llvm::IntNE,
607 ast::BiLt => llvm::IntSLT,
608 ast::BiLe => llvm::IntSLE,
609 ast::BiGt => llvm::IntSGT,
610 ast::BiGe => llvm::IntSGE,
611 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
613 let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
614 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
615 // to get the correctly sized type. This will compile to a single instruction
616 // once the IR is converted to assembly if the SIMD instruction is supported
617 // by the target architecture.
618 SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
620 _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
624 pub type val_and_ty_fn<'r,'b> =
625 |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
627 // Iterates through the elements of a structural type.
628 pub fn iter_structural_ty<'r,
633 f: val_and_ty_fn<'r,'b>)
635 let _icx = push_ctxt("iter_structural_ty");
642 variant: &ty::VariantInfo,
643 substs: &subst::Substs,
644 f: val_and_ty_fn<'r,'b>)
646 let _icx = push_ctxt("iter_variant");
650 for (i, &arg) in variant.args.iter().enumerate() {
652 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
653 arg.subst(tcx, substs));
659 match ty::get(t).sty {
660 ty::ty_struct(..) => {
661 let repr = adt::represent_type(cx.ccx(), t);
662 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
663 for (i, field_ty) in field_tys.iter().enumerate() {
664 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, discr, i);
665 cx = f(cx, llfld_a, field_ty.mt.ty);
669 ty::ty_vec(_, Some(n)) => {
670 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
671 let (base, len) = tvec::get_fixed_base_and_byte_len(cx, av, unit_ty, n);
672 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
674 ty::ty_tup(ref args) => {
675 let repr = adt::represent_type(cx.ccx(), t);
676 for (i, arg) in args.iter().enumerate() {
677 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, 0, i);
678 cx = f(cx, llfld_a, *arg);
681 ty::ty_enum(tid, ref substs) => {
685 let repr = adt::represent_type(ccx, t);
686 let variants = ty::enum_variants(ccx.tcx(), tid);
687 let n_variants = (*variants).len();
689 // NB: we must hit the discriminant first so that structural
690 // comparison know not to proceed when the discriminants differ.
692 match adt::trans_switch(cx, &*repr, av) {
693 (_match::single, None) => {
694 cx = iter_variant(cx, &*repr, av, &**variants.get(0),
697 (_match::switch, Some(lldiscrim_a)) => {
698 cx = f(cx, lldiscrim_a, ty::mk_int());
699 let unr_cx = fcx.new_temp_block("enum-iter-unr");
701 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
703 let next_cx = fcx.new_temp_block("enum-iter-next");
705 for variant in (*variants).iter() {
708 format!("enum-iter-variant-{}",
709 variant.disr_val.to_string().as_slice())
711 match adt::trans_case(cx, &*repr, variant.disr_val) {
712 _match::single_result(r) => {
713 AddCase(llswitch, r.val, variant_cx.llbb)
715 _ => ccx.sess().unimpl("value from adt::trans_case \
716 in iter_structural_ty")
719 iter_variant(variant_cx,
725 Br(variant_cx, next_cx.llbb);
729 _ => ccx.sess().unimpl("value from adt::trans_switch \
730 in iter_structural_ty")
733 _ => cx.sess().unimpl("type in iter_structural_ty")
738 pub fn cast_shift_expr_rhs<'a>(
744 cast_shift_rhs(op, lhs, rhs,
745 |a,b| Trunc(cx, a, b),
746 |a,b| ZExt(cx, a, b))
749 pub fn cast_shift_const_rhs(op: ast::BinOp,
750 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
751 cast_shift_rhs(op, lhs, rhs,
752 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
753 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
756 pub fn cast_shift_rhs(op: ast::BinOp,
759 trunc: |ValueRef, Type| -> ValueRef,
760 zext: |ValueRef, Type| -> ValueRef)
762 // Shifts may have any size int on the rhs
764 if ast_util::is_shift_binop(op) {
765 let mut rhs_llty = val_ty(rhs);
766 let mut lhs_llty = val_ty(lhs);
767 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
768 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
769 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
770 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
773 } else if lhs_sz > rhs_sz {
774 // FIXME (#1877: If shifting by negative
775 // values becomes not undefined then this is wrong.
786 pub fn fail_if_zero_or_overflows<'a>(
794 let (zero_text, overflow_text) = if divrem == ast::BiDiv {
795 ("attempted to divide by zero",
796 "attempted to divide with overflow")
798 ("attempted remainder with a divisor of zero",
799 "attempted remainder with overflow")
801 let (is_zero, is_signed) = match ty::get(rhs_t).sty {
803 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
804 (ICmp(cx, llvm::IntEQ, rhs, zero), true)
807 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
808 (ICmp(cx, llvm::IntEQ, rhs, zero), false)
811 cx.sess().bug(format!("fail-if-zero on unexpected type: {}",
812 ty_to_string(cx.tcx(), rhs_t)).as_slice());
815 let bcx = with_cond(cx, is_zero, |bcx| {
816 controlflow::trans_fail(bcx, span, InternedString::new(zero_text))
819 // To quote LLVM's documentation for the sdiv instruction:
821 // Division by zero leads to undefined behavior. Overflow also leads
822 // to undefined behavior; this is a rare case, but can occur, for
823 // example, by doing a 32-bit division of -2147483648 by -1.
825 // In order to avoid undefined behavior, we perform runtime checks for
826 // signed division/remainder which would trigger overflow. For unsigned
827 // integers, no action beyond checking for zero need be taken.
829 let (llty, min) = match ty::get(rhs_t).sty {
831 let llty = Type::int_from_ty(cx.ccx(), t);
833 ast::TyI if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
834 ast::TyI => i64::MIN as u64,
835 ast::TyI8 => i8::MIN as u64,
836 ast::TyI16 => i16::MIN as u64,
837 ast::TyI32 => i32::MIN as u64,
838 ast::TyI64 => i64::MIN as u64,
844 let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
845 C_integral(llty, -1, false));
846 with_cond(bcx, minus_one, |bcx| {
847 let is_min = ICmp(bcx, llvm::IntEQ, lhs,
848 C_integral(llty, min, true));
849 with_cond(bcx, is_min, |bcx| {
850 controlflow::trans_fail(bcx, span,
851 InternedString::new(overflow_text))
859 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
860 let name = csearch::get_symbol(&ccx.sess().cstore, did);
861 match ty::get(t).sty {
862 ty::ty_bare_fn(ref fn_ty) => {
863 match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
864 ccx.sess().targ_cfg.arch) {
866 get_extern_rust_fn(ccx, t, name.as_slice(), did)
868 Some(RustIntrinsic) => {
869 ccx.sess().bug("unexpected intrinsic in trans_external_path")
872 foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
873 name.as_slice(), None)
877 ty::ty_closure(_) => {
878 get_extern_rust_fn(ccx, t, name.as_slice(), did)
881 let llty = type_of(ccx, t);
882 get_extern_const(&mut *ccx.externs.borrow_mut(),
893 llargs: Vec<ValueRef> ,
895 call_info: Option<NodeInfo>)
896 -> (ValueRef, &'a Block<'a>) {
897 let _icx = push_ctxt("invoke_");
898 if bcx.unreachable.get() {
899 return (C_null(Type::i8(bcx.ccx())), bcx);
902 let attributes = get_fn_llvm_attributes(bcx.ccx(), fn_ty);
904 match bcx.opt_node_id {
906 debug!("invoke at ???");
909 debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
913 if need_invoke(bcx) {
914 debug!("invoking {} at {}", llfn, bcx.llbb);
915 for &llarg in llargs.iter() {
916 debug!("arg: {}", llarg);
918 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
919 let landing_pad = bcx.fcx.get_landing_pad();
922 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
923 None => debuginfo::clear_source_location(bcx.fcx)
926 let llresult = Invoke(bcx,
931 attributes.as_slice());
932 return (llresult, normal_bcx);
934 debug!("calling {} at {}", llfn, bcx.llbb);
935 for &llarg in llargs.iter() {
936 debug!("arg: {}", llarg);
940 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
941 None => debuginfo::clear_source_location(bcx.fcx)
944 let llresult = Call(bcx, llfn, llargs.as_slice(), attributes.as_slice());
945 return (llresult, bcx);
949 pub fn need_invoke(bcx: &Block) -> bool {
950 if bcx.sess().no_landing_pads() {
954 // Avoid using invoke if we are already inside a landing pad.
959 bcx.fcx.needs_invoke()
962 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
963 let _icx = push_ctxt("load_if_immediate");
964 if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
968 pub fn load_ty(cx: &Block, ptr: ValueRef, t: ty::t) -> ValueRef {
970 * Helper for loading values from memory. Does the necessary conversion if
971 * the in-memory type differs from the type used for SSA values. Also
972 * handles various special cases where the type gives us better information
973 * about what we are loading.
975 if type_is_zero_size(cx.ccx(), t) {
976 C_undef(type_of::type_of(cx.ccx(), t))
977 } else if ty::type_is_bool(t) {
978 Trunc(cx, LoadRangeAssert(cx, ptr, 0, 2, llvm::False), Type::i1(cx.ccx()))
979 } else if ty::type_is_char(t) {
980 // a char is a unicode codepoint, and so takes values from 0
981 // to 0x10FFFF inclusive only.
982 LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
988 pub fn store_ty(cx: &Block, v: ValueRef, dst: ValueRef, t: ty::t) {
990 * Helper for storing values in memory. Does the necessary conversion if
991 * the in-memory type differs from the type used for SSA values.
993 if ty::type_is_bool(t) {
994 Store(cx, ZExt(cx, v, Type::i8(cx.ccx())), dst);
1000 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
1001 match local.pat.node {
1002 ast::PatWild => true, _ => false
1006 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
1008 debug!("init_local(bcx={}, local.id={:?})", bcx.to_str(), local.id);
1009 let _indenter = indenter();
1010 let _icx = push_ctxt("init_local");
1011 _match::store_local(bcx, local)
1014 pub fn raw_block<'a>(
1015 fcx: &'a FunctionContext<'a>,
1017 llbb: BasicBlockRef)
1019 Block::new(llbb, is_lpad, None, fcx)
1022 pub fn with_cond<'a>(
1025 f: |&'a Block<'a>| -> &'a Block<'a>)
1027 let _icx = push_ctxt("with_cond");
1029 let next_cx = fcx.new_temp_block("next");
1030 let cond_cx = fcx.new_temp_block("cond");
1031 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1032 let after_cx = f(cond_cx);
1033 if !after_cx.terminated.get() {
1034 Br(after_cx, next_cx.llbb);
1039 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1040 let _icx = push_ctxt("call_memcpy");
1042 let key = match ccx.sess().targ_cfg.arch {
1043 X86 | Arm | Mips | Mipsel => "llvm.memcpy.p0i8.p0i8.i32",
1044 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1046 let memcpy = ccx.get_intrinsic(&key);
1047 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1048 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1049 let size = IntCast(cx, n_bytes, ccx.int_type);
1050 let align = C_i32(ccx, align as i32);
1051 let volatile = C_bool(ccx, false);
1052 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1055 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1056 let _icx = push_ctxt("memcpy_ty");
1057 let ccx = bcx.ccx();
1058 if ty::type_is_structural(t) {
1059 let llty = type_of::type_of(ccx, t);
1060 let llsz = llsize_of(ccx, llty);
1061 let llalign = llalign_of_min(ccx, llty);
1062 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1064 Store(bcx, Load(bcx, src), dst);
1068 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1069 if cx.unreachable.get() { return; }
1070 let _icx = push_ctxt("zero_mem");
1073 let llty = type_of::type_of(ccx, t);
1074 memzero(&B(bcx), llptr, llty);
1077 // Always use this function instead of storing a zero constant to the memory
1078 // in question. If you store a zero constant, LLVM will drown in vreg
1079 // allocation for large data structures, and the generated code will be
1080 // awful. (A telltale sign of this is large quantities of
1081 // `mov [byte ptr foo],0` in the generated code.)
1082 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1083 let _icx = push_ctxt("memzero");
1086 let intrinsic_key = match ccx.sess().targ_cfg.arch {
1087 X86 | Arm | Mips | Mipsel => "llvm.memset.p0i8.i32",
1088 X86_64 => "llvm.memset.p0i8.i64"
1091 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1092 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1093 let llzeroval = C_u8(ccx, 0);
1094 let size = machine::llsize_of(ccx, ty);
1095 let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1096 let volatile = C_bool(ccx, false);
1097 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1100 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1101 let _icx = push_ctxt("alloc_ty");
1102 let ccx = bcx.ccx();
1103 let ty = type_of::type_of(ccx, t);
1104 assert!(!ty::type_has_params(t));
1105 let val = alloca(bcx, ty, name);
1109 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1110 alloca_maybe_zeroed(cx, ty, name, false)
1113 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1114 let _icx = push_ctxt("alloca");
1115 if cx.unreachable.get() {
1117 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1120 debuginfo::clear_source_location(cx.fcx);
1121 let p = Alloca(cx, ty, name);
1123 let b = cx.fcx.ccx.builder();
1124 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1130 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1131 let _icx = push_ctxt("arrayalloca");
1132 if cx.unreachable.get() {
1134 return llvm::LLVMGetUndef(ty.to_ref());
1137 debuginfo::clear_source_location(cx.fcx);
1138 return ArrayAlloca(cx, ty, v);
1141 // Creates and returns space for, or returns the argument representing, the
1142 // slot where the return value of the function must go.
1143 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1146 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1147 llvm::LLVMGetParam(fcx.llfn, 0)
1149 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1150 AllocaFcx(fcx, lloutputtype, "__make_return_pointer")
1155 // NB: must keep 4 fns in sync:
1158 // - create_datums_for_fn_args.
1162 // Be warned! You must call `init_function` before doing anything with the
1163 // returned function context.
1164 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1169 param_substs: &'a param_substs,
1171 block_arena: &'a TypedArena<Block<'a>>)
1172 -> FunctionContext<'a> {
1173 param_substs.validate();
1175 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1179 ccx.tcx.map.path_to_string(id).to_string()
1181 id, param_substs.repr(ccx.tcx()));
1183 let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1184 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1185 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1187 let mut fcx = FunctionContext {
1190 llretptr: Cell::new(None),
1191 alloca_insert_pt: Cell::new(None),
1192 llreturn: Cell::new(None),
1193 personality: Cell::new(None),
1194 caller_expects_out_pointer: uses_outptr,
1195 llargs: RefCell::new(NodeMap::new()),
1196 lllocals: RefCell::new(NodeMap::new()),
1197 llupvars: RefCell::new(NodeMap::new()),
1199 param_substs: param_substs,
1201 block_arena: block_arena,
1203 debug_context: debug_context,
1204 scopes: RefCell::new(Vec::new())
1208 fcx.llenv = Some(unsafe {
1209 llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1216 /// Performs setup on a newly created function, creating the entry scope block
1217 /// and allocating space for the return pointer.
1218 pub fn init_function<'a>(fcx: &'a FunctionContext<'a>,
1220 output_type: ty::t) -> &'a Block<'a> {
1221 let entry_bcx = fcx.new_temp_block("entry-block");
1223 // Use a dummy instruction as the insertion point for all allocas.
1224 // This is later removed in FunctionContext::cleanup.
1225 fcx.alloca_insert_pt.set(Some(unsafe {
1226 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1227 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1230 // This shouldn't need to recompute the return type,
1231 // as new_fn_ctxt did it already.
1232 let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1234 if !return_type_is_void(fcx.ccx, substd_output_type) {
1235 // If the function returns nil/bot, there is no real return
1236 // value, so do not set `llretptr`.
1237 if !skip_retptr || fcx.caller_expects_out_pointer {
1238 // Otherwise, we normally allocate the llretptr, unless we
1239 // have been instructed to skip it for immediate return
1241 fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1248 // NB: must keep 4 fns in sync:
1251 // - create_datums_for_fn_args.
1255 pub fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1256 use middle::trans::datum::{ByRef, ByValue};
1259 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1263 // work around bizarre resolve errors
1264 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1265 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1267 // create_datums_for_fn_args: creates rvalue datums for each of the
1268 // incoming function arguments. These will later be stored into
1269 // appropriate lvalue datums.
1270 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1272 -> Vec<RvalueDatum> {
1273 let _icx = push_ctxt("create_datums_for_fn_args");
1275 // Return an array wrapping the ValueRefs that we get from
1276 // llvm::LLVMGetParam for each argument into datums.
1277 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1278 let llarg = unsafe {
1279 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1281 datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1285 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1286 arg_scope: cleanup::CustomScopeIndex,
1289 arg_datums: Vec<RvalueDatum> )
1291 debug!("copy_args_to_allocas");
1293 let _icx = push_ctxt("copy_args_to_allocas");
1296 let arg_scope_id = cleanup::CustomScope(arg_scope);
1298 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1299 // For certain mode/type combinations, the raw llarg values are passed
1300 // by value. However, within the fn body itself, we want to always
1301 // have all locals and arguments be by-ref so that we can cancel the
1302 // cleanup and for better interaction with LLVM's debug info. So, if
1303 // the argument would be passed by value, we store it into an alloca.
1304 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1305 // the event it's not truly needed.
1307 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1309 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1310 debuginfo::create_argument_metadata(bcx, &args[i]);
1317 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1318 // and builds the return block.
1319 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1320 last_bcx: &'a Block<'a>,
1322 let _icx = push_ctxt("finish_fn");
1324 // This shouldn't need to recompute the return type,
1325 // as new_fn_ctxt did it already.
1326 let substd_retty = retty.substp(fcx.ccx.tcx(), fcx.param_substs);
1328 let ret_cx = match fcx.llreturn.get() {
1330 if !last_bcx.terminated.get() {
1331 Br(last_bcx, llreturn);
1333 raw_block(fcx, false, llreturn)
1337 build_return_block(fcx, ret_cx, substd_retty);
1338 debuginfo::clear_source_location(fcx);
1342 // Builds the return block for a function.
1343 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block, retty: ty::t) {
1344 // Return the value if this function immediate; otherwise, return void.
1345 if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1346 return RetVoid(ret_cx);
1349 let retptr = Value(fcx.llretptr.get().unwrap());
1350 let retval = match retptr.get_dominating_store(ret_cx) {
1351 // If there's only a single store to the ret slot, we can directly return
1352 // the value that was stored and omit the store and the alloca
1354 let retval = s.get_operand(0).unwrap().get();
1355 s.erase_from_parent();
1357 if retptr.has_no_uses() {
1358 retptr.erase_from_parent();
1361 if ty::type_is_bool(retty) {
1362 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1367 // Otherwise, load the return value from the ret slot
1368 None => load_ty(ret_cx, fcx.llretptr.get().unwrap(), retty)
1371 Ret(ret_cx, retval);
1374 // trans_closure: Builds an LLVM function out of a source function.
1375 // If the function closes over its environment a closure will be
1377 pub fn trans_closure(ccx: &CrateContext,
1381 param_substs: ¶m_substs,
1383 _attributes: &[ast::Attribute],
1385 maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1386 ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1388 let _icx = push_ctxt("trans_closure");
1389 set_uwtable(llfndecl);
1391 debug!("trans_closure(..., param_substs={})",
1392 param_substs.repr(ccx.tcx()));
1394 let has_env = match ty::get(ty::node_id_to_type(ccx.tcx(), id)).sty {
1395 ty::ty_closure(_) => true,
1399 let arena = TypedArena::new();
1400 let fcx = new_fn_ctxt(ccx,
1408 let mut bcx = init_function(&fcx, false, output_type);
1410 // cleanup scope for the incoming arguments
1411 let arg_scope = fcx.push_custom_cleanup_scope();
1413 let block_ty = node_id_type(bcx, body.id);
1415 // Set up arguments to the function.
1416 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1417 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1419 bcx = copy_args_to_allocas(&fcx,
1422 decl.inputs.as_slice(),
1425 bcx = maybe_load_env(bcx);
1427 // Up until here, IR instructions for this function have explicitly not been annotated with
1428 // source code location, so we don't step into call setup code. From here on, source location
1429 // emitting should be enabled.
1430 debuginfo::start_emitting_source_locations(&fcx);
1432 let dest = match fcx.llretptr.get() {
1433 Some(e) => {expr::SaveIn(e)}
1435 assert!(type_is_zero_size(bcx.ccx(), block_ty))
1440 // This call to trans_block is the place where we bridge between
1441 // translation calls that don't have a return value (trans_crate,
1442 // trans_mod, trans_item, et cetera) and those that do
1443 // (trans_block, trans_expr, et cetera).
1444 bcx = controlflow::trans_block(bcx, body, dest);
1446 match fcx.llreturn.get() {
1448 Br(bcx, fcx.return_exit_block());
1449 fcx.pop_custom_cleanup_scope(arg_scope);
1452 // Microoptimization writ large: avoid creating a separate
1453 // llreturn basic block
1454 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1458 // Put return block after all other blocks.
1459 // This somewhat improves single-stepping experience in debugger.
1461 let llreturn = fcx.llreturn.get();
1462 for &llreturn in llreturn.iter() {
1463 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1467 // Insert the mandatory first few basic blocks before lltop.
1468 finish_fn(&fcx, bcx, output_type);
1471 // trans_fn: creates an LLVM function corresponding to a source language
1473 pub fn trans_fn(ccx: &CrateContext,
1477 param_substs: ¶m_substs,
1479 attrs: &[ast::Attribute]) {
1480 let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_string(id).to_string());
1481 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1482 let _icx = push_ctxt("trans_fn");
1483 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
1484 trans_closure(ccx, decl, body, llfndecl,
1485 param_substs, id, attrs, output_type, |bcx| bcx);
1488 pub fn trans_enum_variant(ccx: &CrateContext,
1489 _enum_id: ast::NodeId,
1490 variant: &ast::Variant,
1491 _args: &[ast::VariantArg],
1493 param_substs: ¶m_substs,
1494 llfndecl: ValueRef) {
1495 let _icx = push_ctxt("trans_enum_variant");
1497 trans_enum_variant_or_tuple_like_struct(
1505 pub fn trans_tuple_struct(ccx: &CrateContext,
1506 _fields: &[ast::StructField],
1507 ctor_id: ast::NodeId,
1508 param_substs: ¶m_substs,
1509 llfndecl: ValueRef) {
1510 let _icx = push_ctxt("trans_tuple_struct");
1512 trans_enum_variant_or_tuple_like_struct(
1520 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1521 ctor_id: ast::NodeId,
1523 param_substs: ¶m_substs,
1524 llfndecl: ValueRef) {
1525 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1526 let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
1528 let result_ty = match ty::get(ctor_ty).sty {
1529 ty::ty_bare_fn(ref bft) => bft.sig.output,
1530 _ => ccx.sess().bug(
1531 format!("trans_enum_variant_or_tuple_like_struct: \
1532 unexpected ctor return type {}",
1533 ty_to_string(ccx.tcx(), ctor_ty)).as_slice())
1536 let arena = TypedArena::new();
1537 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1538 param_substs, None, &arena);
1539 let bcx = init_function(&fcx, false, result_ty);
1541 let arg_tys = ty::ty_fn_args(ctor_ty);
1543 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1545 if !type_is_zero_size(fcx.ccx, result_ty) {
1546 let repr = adt::represent_type(ccx, result_ty);
1547 adt::trans_start_init(bcx, &*repr, fcx.llretptr.get().unwrap(), disr);
1548 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1549 let lldestptr = adt::trans_field_ptr(bcx,
1551 fcx.llretptr.get().unwrap(),
1554 arg_datum.store_to(bcx, lldestptr);
1558 finish_fn(&fcx, bcx, result_ty);
1561 fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1562 sp: Span, id: ast::NodeId, vi: &[Rc<ty::VariantInfo>],
1564 for variant in enum_definition.variants.iter() {
1565 let disr_val = vi[*i].disr_val;
1568 match variant.node.kind {
1569 ast::TupleVariantKind(ref args) if args.len() > 0 => {
1570 let llfn = get_item_val(ccx, variant.node.id);
1571 trans_enum_variant(ccx, id, &**variant, args.as_slice(),
1572 disr_val, ¶m_substs::empty(), llfn);
1574 ast::TupleVariantKind(_) => {
1577 ast::StructVariantKind(struct_def) => {
1578 trans_struct_def(ccx, struct_def);
1583 enum_variant_size_lint(ccx, enum_definition, sp, id);
1586 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
1587 let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
1589 let levels = ccx.tcx.node_lint_levels.borrow();
1590 let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCE);
1591 let lvlsrc = match levels.find(&(id, lint_id)) {
1592 None | Some(&(lint::Allow, _)) => return,
1593 Some(&lvlsrc) => lvlsrc,
1596 let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
1598 adt::General(_, ref variants) => {
1599 for var in variants.iter() {
1601 for field in var.fields.iter().skip(1) {
1602 // skip the discriminant
1603 size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
1608 _ => { /* its size is either constant or unimportant */ }
1611 let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
1612 |(l, s, li), (idx, &size)|
1615 } else if size > s {
1622 // we only warn if the largest variant is at least thrice as large as
1623 // the second-largest.
1624 if largest > slargest * 3 && slargest > 0 {
1625 // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
1626 // pass for the latter already ran.
1627 lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCE,
1629 format!("enum variant is more than three times larger \
1630 ({} bytes) than the next largest (ignoring padding)",
1631 largest).as_slice());
1633 ccx.sess().span_note(enum_def.variants.get(largest_index).span,
1634 "this variant is the largest");
1638 pub struct TransItemVisitor<'a> {
1639 pub ccx: &'a CrateContext,
1642 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1643 fn visit_item(&mut self, i: &ast::Item, _:()) {
1644 trans_item(self.ccx, i);
1648 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1649 let _icx = push_ctxt("trans_item");
1651 ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
1653 let llfndecl = get_item_val(ccx, item.id);
1654 foreign::trans_rust_fn_with_foreign_abi(
1655 ccx, &**decl, &**body, item.attrs.as_slice(), llfndecl, item.id);
1656 } else if !generics.is_type_parameterized() {
1657 let llfn = get_item_val(ccx, item.id);
1662 ¶m_substs::empty(),
1664 item.attrs.as_slice());
1666 // Be sure to travel more than just one layer deep to catch nested
1667 // items in blocks and such.
1668 let mut v = TransItemVisitor{ ccx: ccx };
1669 v.visit_block(&**body, ());
1672 ast::ItemImpl(ref generics, _, _, ref ms) => {
1673 meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1675 ast::ItemMod(ref m) => {
1678 ast::ItemEnum(ref enum_definition, ref generics) => {
1679 if !generics.is_type_parameterized() {
1680 let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1682 trans_enum_def(ccx, enum_definition, item.span, item.id, vi.as_slice(), &mut i);
1685 ast::ItemStatic(_, m, ref expr) => {
1686 // Recurse on the expression to catch items in blocks
1687 let mut v = TransItemVisitor{ ccx: ccx };
1688 v.visit_expr(&**expr, ());
1689 consts::trans_const(ccx, m, item.id);
1690 // Do static_assert checking. It can't really be done much earlier
1691 // because we need to get the value of the bool out of LLVM
1692 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1693 if m == ast::MutMutable {
1694 ccx.sess().span_fatal(expr.span,
1695 "cannot have static_assert on a mutable \
1699 let v = ccx.const_values.borrow().get_copy(&item.id);
1701 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1702 ccx.sess().span_fatal(expr.span, "static assertion failed");
1707 ast::ItemForeignMod(ref foreign_mod) => {
1708 foreign::trans_foreign_mod(ccx, foreign_mod);
1710 ast::ItemStruct(struct_def, ref generics) => {
1711 if !generics.is_type_parameterized() {
1712 trans_struct_def(ccx, struct_def);
1715 ast::ItemTrait(..) => {
1716 // Inside of this trait definition, we won't be actually translating any
1717 // functions, but the trait still needs to be walked. Otherwise default
1718 // methods with items will not get translated and will cause ICE's when
1719 // metadata time comes around.
1720 let mut v = TransItemVisitor{ ccx: ccx };
1721 visit::walk_item(&mut v, item, ());
1723 _ => {/* fall through */ }
1727 pub fn trans_struct_def(ccx: &CrateContext, struct_def: Gc<ast::StructDef>) {
1728 // If this is a tuple-like struct, translate the constructor.
1729 match struct_def.ctor_id {
1730 // We only need to translate a constructor if there are fields;
1731 // otherwise this is a unit-like struct.
1732 Some(ctor_id) if struct_def.fields.len() > 0 => {
1733 let llfndecl = get_item_val(ccx, ctor_id);
1734 trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1735 ctor_id, ¶m_substs::empty(), llfndecl);
1737 Some(_) | None => {}
1741 // Translate a module. Doing this amounts to translating the items in the
1742 // module; there ends up being no artifact (aside from linkage names) of
1743 // separate modules in the compiled program. That's because modules exist
1744 // only as a convenience for humans working with the code, to organize names
1745 // and control visibility.
1746 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1747 let _icx = push_ctxt("trans_mod");
1748 for item in m.items.iter() {
1749 trans_item(ccx, &**item);
1753 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
1755 ccx.item_symbols.borrow_mut().insert(node_id, sym);
1757 if !ccx.reachable.contains(&node_id) {
1758 llvm::SetLinkage(llfn, llvm::InternalLinkage);
1761 // The stack exhaustion lang item shouldn't have a split stack because
1762 // otherwise it would continue to be exhausted (bad), and both it and the
1763 // eh_personality functions need to be externally linkable.
1764 let def = ast_util::local_def(node_id);
1765 if ccx.tcx.lang_items.stack_exhausted() == Some(def) {
1766 unset_split_stack(llfn);
1767 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
1769 if ccx.tcx.lang_items.eh_personality() == Some(def) {
1770 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
1774 if is_entry_fn(ccx.sess(), node_id) {
1775 create_entry_wrapper(ccx, sp, llfn);
1779 fn register_fn(ccx: &CrateContext,
1782 node_id: ast::NodeId,
1785 match ty::get(node_type).sty {
1786 ty::ty_bare_fn(ref f) => {
1787 assert!(f.abi == Rust);
1789 _ => fail!("expected bare rust fn")
1792 let llfn = decl_rust_fn(ccx, node_type, sym.as_slice());
1793 finish_register_fn(ccx, sp, sym, node_id, llfn);
1797 pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t) -> Vec<(uint, u64)> {
1798 use middle::ty::{BrAnon, ReLateBound};
1800 let (fn_sig, has_env) = match ty::get(fn_ty).sty {
1801 ty::ty_closure(ref f) => (f.sig.clone(), true),
1802 ty::ty_bare_fn(ref f) => (f.sig.clone(), false),
1803 _ => fail!("expected closure or function.")
1806 // Since index 0 is the return value of the llvm func, we start
1807 // at either 1 or 2 depending on whether there's an env slot or not
1808 let mut first_arg_offset = if has_env { 2 } else { 1 };
1809 let mut attrs = Vec::new();
1810 let ret_ty = fn_sig.output;
1812 // A function pointer is called without the declaration
1813 // available, so we have to apply any attributes with ABI
1814 // implications directly to the call instruction. Right now,
1815 // the only attribute we need to worry about is `sret`.
1816 if type_of::return_uses_outptr(ccx, ret_ty) {
1817 attrs.push((1, llvm::StructRetAttribute as u64));
1819 // The outptr can be noalias and nocapture because it's entirely
1820 // invisible to the program. We can also mark it as nonnull
1821 attrs.push((1, llvm::NoAliasAttribute as u64));
1822 attrs.push((1, llvm::NoCaptureAttribute as u64));
1823 attrs.push((1, llvm::NonNullAttribute as u64));
1825 // Add one more since there's an outptr
1826 first_arg_offset += 1;
1828 // The `noalias` attribute on the return value is useful to a
1829 // function ptr caller.
1830 match ty::get(ret_ty).sty {
1831 // `~` pointer return values never alias because ownership
1833 ty::ty_uniq(it) if match ty::get(it).sty {
1834 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
1837 attrs.push((llvm::ReturnIndex as uint, llvm::NoAliasAttribute as u64));
1842 // We can also mark the return value as `nonnull` in certain cases
1843 match ty::get(ret_ty).sty {
1844 // These are not really pointers but pairs, (pointer, len)
1846 ty::ty_rptr(_, ty::mt { ty: it, .. }) if match ty::get(it).sty {
1847 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
1849 ty::ty_uniq(_) | ty::ty_rptr(_, _) => {
1850 attrs.push((llvm::ReturnIndex as uint, llvm::NonNullAttribute as u64));
1855 match ty::get(ret_ty).sty {
1857 attrs.push((llvm::ReturnIndex as uint, llvm::ZExtAttribute as u64));
1863 for (idx, &t) in fn_sig.inputs.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
1864 match ty::get(t).sty {
1865 // this needs to be first to prevent fat pointers from falling through
1866 _ if !type_is_immediate(ccx, t) => {
1867 // For non-immediate arguments the callee gets its own copy of
1868 // the value on the stack, so there are no aliases. It's also
1869 // program-invisible so can't possibly capture
1870 attrs.push((idx, llvm::NoAliasAttribute as u64));
1871 attrs.push((idx, llvm::NoCaptureAttribute as u64));
1872 attrs.push((idx, llvm::NonNullAttribute as u64));
1875 attrs.push((idx, llvm::ZExtAttribute as u64));
1877 // `~` pointer parameters never alias because ownership is transferred
1879 attrs.push((idx, llvm::NoAliasAttribute as u64));
1880 attrs.push((idx, llvm::NonNullAttribute as u64));
1882 // `&mut` pointer parameters never alias other parameters, or mutable global data
1883 ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable => {
1884 attrs.push((idx, llvm::NoAliasAttribute as u64));
1885 attrs.push((idx, llvm::NonNullAttribute as u64));
1887 ReLateBound(_, BrAnon(_)) => {
1888 attrs.push((idx, llvm::NoCaptureAttribute as u64));
1893 // When a reference in an argument has no named lifetime, it's impossible for that
1894 // reference to escape this function (returned or stored beyond the call by a closure).
1895 ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
1896 attrs.push((idx, llvm::NoCaptureAttribute as u64));
1897 attrs.push((idx, llvm::NonNullAttribute as u64));
1899 // & pointer parameters are never null
1900 ty::ty_rptr(_, _) => {
1901 attrs.push((idx, llvm::NonNullAttribute as u64));
1910 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1911 pub fn register_fn_llvmty(ccx: &CrateContext,
1914 node_id: ast::NodeId,
1916 llfty: Type) -> ValueRef {
1917 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1919 let llfn = decl_fn(ccx, sym.as_slice(), cc, llfty, ty::mk_nil());
1920 finish_register_fn(ccx, sp, sym, node_id, llfn);
1924 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1925 match *sess.entry_fn.borrow() {
1926 Some((entry_id, _)) => node_id == entry_id,
1931 // Create a _rust_main(args: ~[str]) function which will be called from the
1932 // runtime rust_start function
1933 pub fn create_entry_wrapper(ccx: &CrateContext,
1935 main_llfn: ValueRef) {
1936 let et = ccx.sess().entry_type.get().unwrap();
1938 config::EntryMain => {
1939 create_entry_fn(ccx, main_llfn, true);
1941 config::EntryStart => create_entry_fn(ccx, main_llfn, false),
1942 config::EntryNone => {} // Do nothing.
1945 fn create_entry_fn(ccx: &CrateContext,
1946 rust_main: ValueRef,
1947 use_start_lang_item: bool) {
1948 let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
1951 let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil());
1952 let llbb = "top".with_c_str(|buf| {
1954 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1957 let bld = ccx.builder.b;
1959 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1961 let (start_fn, args) = if use_start_lang_item {
1962 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1964 Err(s) => { ccx.sess().fatal(s.as_slice()); }
1966 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1967 get_item_val(ccx, start_def_id.node)
1969 let start_fn_type = csearch::get_type(ccx.tcx(),
1971 trans_external_path(ccx, start_def_id, start_fn_type)
1975 let opaque_rust_main = "rust_main".with_c_str(|buf| {
1976 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
1981 llvm::LLVMGetParam(llfn, 0),
1982 llvm::LLVMGetParam(llfn, 1)
1987 debug!("using user-defined start fn");
1989 llvm::LLVMGetParam(llfn, 0 as c_uint),
1990 llvm::LLVMGetParam(llfn, 1 as c_uint)
1996 let result = llvm::LLVMBuildCall(bld,
1999 args.len() as c_uint,
2002 llvm::LLVMBuildRet(bld, result);
2007 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
2008 ty: ty::t, attrs: &[ast::Attribute]) -> String {
2009 match attr::first_attr_value_str_by_name(attrs, "export_name") {
2010 // Use provided name
2011 Some(name) => name.get().to_string(),
2013 _ => ccx.tcx.map.with_path(id, |mut path| {
2014 if attr::contains_name(attrs, "no_mangle") {
2016 path.last().unwrap().to_string()
2018 match weak_lang_items::link_name(attrs) {
2019 Some(name) => name.get().to_string(),
2021 // Usual name mangling
2022 mangle_exported_name(ccx, path, ty, id)
2030 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2031 debug!("get_item_val(id=`{:?}`)", id);
2033 match ccx.item_vals.borrow().find_copy(&id) {
2034 Some(v) => return v,
2038 let mut foreign = false;
2039 let item = ccx.tcx.map.get(id);
2040 let val = match item {
2041 ast_map::NodeItem(i) => {
2042 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2043 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
2045 let v = match i.node {
2046 ast::ItemStatic(_, mutbl, ref expr) => {
2047 // If this static came from an external crate, then
2048 // we need to get the symbol from csearch instead of
2049 // using the current crate's name/version
2050 // information in the hash of the symbol
2051 debug!("making {}", sym);
2052 let (sym, is_local) = {
2053 match ccx.external_srcs.borrow().find(&i.id) {
2055 debug!("but found in other crate...");
2056 (csearch::get_symbol(&ccx.sess().cstore,
2063 // We need the translated value here, because for enums the
2064 // LLVM type is not fully determined by the Rust type.
2065 let (v, inlineable) = consts::const_expr(ccx, &**expr, is_local);
2066 ccx.const_values.borrow_mut().insert(id, v);
2067 let mut inlineable = inlineable;
2070 let llty = llvm::LLVMTypeOf(v);
2071 let g = sym.as_slice().with_c_str(|buf| {
2072 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2075 if !ccx.reachable.contains(&id) {
2076 llvm::SetLinkage(g, llvm::InternalLinkage);
2079 // Apply the `unnamed_addr` attribute if
2081 if !ast_util::static_has_significant_address(
2083 i.attrs.as_slice()) {
2084 llvm::SetUnnamedAddr(g, true);
2086 // This is a curious case where we must make
2087 // all of these statics inlineable. If a
2088 // global is not tagged as `#[inline(never)]`,
2089 // then LLVM won't coalesce globals unless they
2090 // have an internal linkage type. This means that
2091 // external crates cannot use this global.
2092 // This is a problem for things like inner
2093 // statics in generic functions, because the
2094 // function will be inlined into another
2095 // crate and then attempt to link to the
2096 // static in the original crate, only to
2097 // find that it's not there. On the other
2098 // side of inlining, the crates knows to
2099 // not declare this static as
2100 // available_externally (because it isn't)
2104 if attr::contains_name(i.attrs.as_slice(),
2106 llvm::set_thread_local(g, true);
2110 debug!("{} not inlined", sym);
2111 ccx.non_inlineable_statics.borrow_mut()
2115 ccx.item_symbols.borrow_mut().insert(i.id, sym);
2120 ast::ItemFn(_, _, abi, _, _) => {
2121 let llfn = if abi == Rust {
2122 register_fn(ccx, i.span, sym, i.id, ty)
2124 foreign::register_rust_fn_with_foreign_abi(ccx,
2129 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2133 _ => fail!("get_item_val: weird result in table")
2136 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
2138 Some(sect) => unsafe {
2139 sect.get().with_c_str(|buf| {
2140 llvm::LLVMSetSection(v, buf);
2149 ast_map::NodeTraitMethod(trait_method) => {
2150 debug!("get_item_val(): processing a NodeTraitMethod");
2151 match *trait_method {
2152 ast::Required(_) => {
2153 ccx.sess().bug("unexpected variant: required trait method in \
2156 ast::Provided(m) => {
2157 register_method(ccx, id, &*m)
2162 ast_map::NodeMethod(m) => {
2163 register_method(ccx, id, &*m)
2166 ast_map::NodeForeignItem(ni) => {
2170 ast::ForeignItemFn(..) => {
2171 let abi = ccx.tcx.map.get_foreign_abi(id);
2172 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2173 let name = foreign::link_name(&*ni);
2174 foreign::register_foreign_item_fn(ccx, abi, ty,
2175 name.get().as_slice(),
2178 ast::ForeignItemStatic(..) => {
2179 foreign::register_static(ccx, &*ni)
2184 ast_map::NodeVariant(ref v) => {
2186 let args = match v.node.kind {
2187 ast::TupleVariantKind(ref args) => args,
2188 ast::StructVariantKind(_) => {
2189 fail!("struct variant kind unexpected in get_item_val")
2192 assert!(args.len() != 0u);
2193 let ty = ty::node_id_to_type(ccx.tcx(), id);
2194 let parent = ccx.tcx.map.get_parent(id);
2195 let enm = ccx.tcx.map.expect_item(parent);
2196 let sym = exported_name(ccx,
2199 enm.attrs.as_slice());
2201 llfn = match enm.node {
2202 ast::ItemEnum(_, _) => {
2203 register_fn(ccx, (*v).span, sym, id, ty)
2205 _ => fail!("NodeVariant, shouldn't happen")
2207 set_inline_hint(llfn);
2211 ast_map::NodeStructCtor(struct_def) => {
2212 // Only register the constructor if this is a tuple-like struct.
2213 let ctor_id = match struct_def.ctor_id {
2215 ccx.sess().bug("attempt to register a constructor of \
2216 a non-tuple-like struct")
2218 Some(ctor_id) => ctor_id,
2220 let parent = ccx.tcx.map.get_parent(id);
2221 let struct_item = ccx.tcx.map.expect_item(parent);
2222 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2223 let sym = exported_name(ccx,
2228 let llfn = register_fn(ccx, struct_item.span,
2230 set_inline_hint(llfn);
2235 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2236 variant).as_slice())
2240 // foreign items (extern fns and extern statics) don't have internal
2241 // linkage b/c that doesn't quite make sense. Otherwise items can
2242 // have internal linkage if they're not reachable.
2243 if !foreign && !ccx.reachable.contains(&id) {
2244 llvm::SetLinkage(val, llvm::InternalLinkage);
2247 ccx.item_vals.borrow_mut().insert(id, val);
2251 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2252 m: &ast::Method) -> ValueRef {
2253 let mty = ty::node_id_to_type(ccx.tcx(), id);
2255 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2257 let llfn = register_fn(ccx, m.span, sym, id, mty);
2258 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2262 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2264 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2268 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2269 -> encoder::EncodeParams<'r> {
2270 encoder::EncodeParams {
2271 diag: cx.sess().diagnostic(),
2273 reexports2: &cx.exp_map2,
2274 item_symbols: &cx.item_symbols,
2275 non_inlineable_statics: &cx.non_inlineable_statics,
2276 link_meta: &cx.link_meta,
2277 cstore: &cx.sess().cstore,
2278 encode_inlined_item: ie,
2279 reachable: &cx.reachable,
2283 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2286 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2287 *ty != config::CrateTypeExecutable
2293 let encode_inlined_item: encoder::EncodeInlinedItem =
2294 |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
2296 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2297 let metadata = encoder::encode_metadata(encode_parms, krate);
2298 let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2299 .append(match flate::deflate_bytes(metadata.as_slice()) {
2300 Some(compressed) => compressed,
2302 cx.sess().fatal("failed to compress metadata")
2305 let llmeta = C_bytes(cx, compressed.as_slice());
2306 let llconst = C_struct(cx, [llmeta], false);
2307 let name = format!("rust_metadata_{}_{}",
2308 cx.link_meta.crate_name,
2309 cx.link_meta.crate_hash);
2310 let llglobal = name.with_c_str(|buf| {
2312 llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2316 llvm::LLVMSetInitializer(llglobal, llconst);
2317 let name = loader::meta_section_name(cx.sess().targ_cfg.os);
2318 name.unwrap_or("rust_metadata").with_c_str(|buf| {
2319 llvm::LLVMSetSection(llglobal, buf)
2325 pub fn trans_crate(krate: ast::Crate,
2326 analysis: CrateAnalysis) -> (ty::ctxt, CrateTranslation) {
2327 let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, name, .. } = analysis;
2329 // Before we touch LLVM, make sure that multithreading is enabled.
2331 use std::sync::{Once, ONCE_INIT};
2332 static mut INIT: Once = ONCE_INIT;
2333 static mut POISONED: bool = false;
2335 if llvm::LLVMStartMultithreaded() != 1 {
2336 // use an extra bool to make sure that all future usage of LLVM
2337 // cannot proceed despite the Once not running more than once.
2343 tcx.sess.bug("couldn't enable multi-threaded LLVM");
2347 let link_meta = link::build_link_meta(&tcx.sess, &krate, name);
2349 // Append ".rs" to crate name as LLVM module identifier.
2351 // LLVM code generator emits a ".file filename" directive
2352 // for ELF backends. Value of the "filename" is set as the
2353 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2354 // crashes if the module identifier is same as other symbols
2355 // such as a function name in the module.
2356 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2357 let mut llmod_id = link_meta.crate_name.clone();
2358 llmod_id.push_str(".rs");
2360 let ccx = CrateContext::new(llmod_id.as_slice(), tcx, exp_map2,
2361 Sha256::new(), link_meta, reachable);
2363 // First, verify intrinsics.
2364 intrinsic::check_intrinsics(&ccx);
2366 // Next, translate the module.
2368 let _icx = push_ctxt("text");
2369 trans_mod(&ccx, &krate.module);
2372 glue::emit_tydescs(&ccx);
2373 if ccx.sess().opts.debuginfo != NoDebugInfo {
2374 debuginfo::finalize(&ccx);
2377 // Translate the metadata.
2378 let metadata = write_metadata(&ccx, &krate);
2379 if ccx.sess().trans_stats() {
2380 println!("--- trans stats ---");
2381 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2382 println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2383 println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2384 println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2386 println!("n_fns: {}", ccx.stats.n_fns.get());
2387 println!("n_monos: {}", ccx.stats.n_monos.get());
2388 println!("n_inlines: {}", ccx.stats.n_inlines.get());
2389 println!("n_closures: {}", ccx.stats.n_closures.get());
2390 println!("fn stats:");
2391 ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2392 insns_b.cmp(&insns_a)
2394 for tuple in ccx.stats.fn_stats.borrow().iter() {
2396 (ref name, ms, insns) => {
2397 println!("{} insns, {} ms, {}", insns, ms, *name);
2402 if ccx.sess().count_llvm_insns() {
2403 for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2404 println!("{:7u} {}", *v, *k);
2408 let llcx = ccx.llcx;
2409 let link_meta = ccx.link_meta.clone();
2410 let llmod = ccx.llmod;
2412 let mut reachable: Vec<String> = ccx.reachable.iter().filter_map(|id| {
2413 ccx.item_symbols.borrow().find(id).map(|s| s.to_string())
2416 // For the purposes of LTO, we add to the reachable set all of the upstream
2417 // reachable extern fns. These functions are all part of the public ABI of
2418 // the final product, so LTO needs to preserve them.
2419 ccx.sess().cstore.iter_crate_data(|cnum, _| {
2420 let syms = csearch::get_reachable_extern_fns(&ccx.sess().cstore, cnum);
2421 reachable.extend(syms.move_iter().map(|did| {
2422 csearch::get_symbol(&ccx.sess().cstore, did)
2426 // Make sure that some other crucial symbols are not eliminated from the
2427 // module. This includes the main function, the crate map (used for debug
2428 // log settings and I/O), and finally the curious rust_stack_exhausted
2429 // symbol. This symbol is required for use by the libmorestack library that
2430 // we link in, so we must ensure that this symbol is not internalized (if
2431 // defined in the crate).
2432 reachable.push("main".to_string());
2433 reachable.push("rust_stack_exhausted".to_string());
2435 // referenced from .eh_frame section on some platforms
2436 reachable.push("rust_eh_personality".to_string());
2437 // referenced from rt/rust_try.ll
2438 reachable.push("rust_eh_personality_catch".to_string());
2440 let metadata_module = ccx.metadata_llmod;
2441 let formats = ccx.tcx.dependency_formats.borrow().clone();
2442 let no_builtins = attr::contains_name(krate.attrs.as_slice(), "no_builtins");
2444 (ccx.tcx, CrateTranslation {
2448 metadata_module: metadata_module,
2450 reachable: reachable,
2451 crate_formats: formats,
2452 no_builtins: no_builtins,