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::driver::{CrateAnalysis, CrateTranslation};
33 use driver::session::Session;
35 use llvm::{BasicBlockRef, ModuleRef, ValueRef, Vector, get_param};
37 use metadata::{csearch, encoder, loader};
38 use middle::astencode;
39 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::weak_lang_items;
42 use middle::subst::Subst;
43 use middle::trans::_match;
44 use middle::trans::adt;
45 use middle::trans::build::*;
46 use middle::trans::builder::{Builder, noname};
47 use middle::trans::callee;
48 use middle::trans::cleanup;
49 use middle::trans::cleanup::CleanupMethods;
50 use middle::trans::common::*;
51 use middle::trans::consts;
52 use middle::trans::controlflow;
53 use middle::trans::datum;
54 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
55 use middle::trans::debuginfo;
56 use middle::trans::expr;
57 use middle::trans::foreign;
58 use middle::trans::glue;
59 use middle::trans::inline;
60 use middle::trans::intrinsic;
61 use middle::trans::machine;
62 use middle::trans::machine::{llalign_of_min, llsize_of, llsize_of_real};
63 use middle::trans::meth;
64 use middle::trans::monomorphize;
65 use middle::trans::tvec;
66 use middle::trans::type_::Type;
67 use middle::trans::type_of;
68 use middle::trans::type_of::*;
69 use middle::trans::value::Value;
72 use util::common::indenter;
73 use util::ppaux::{Repr, ty_to_string};
74 use util::sha2::Sha256;
75 use util::nodemap::NodeMap;
77 use arena::TypedArena;
78 use libc::{c_uint, uint64_t};
79 use std::c_str::ToCStr;
80 use std::cell::{Cell, RefCell};
82 use std::{i8, i16, i32, i64};
84 use syntax::abi::{X86, X86_64, Arm, Mips, Mipsel, Rust, RustCall};
85 use syntax::abi::{RustIntrinsic, Abi};
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 if ccx.tcx.sess.opts.cg.no_redzone {
198 llvm::LLVMAddFunctionAttribute(llfn,
199 llvm::FunctionIndex as c_uint,
200 llvm::NoRedZoneAttribute as uint64_t)
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() {
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::t) -> ValueRef {
220 decl_fn(ccx, name, llvm::CCallConv, ty, 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.find_equiv(&name) {
232 Some(n) => return *n,
235 let f = decl_fn(ccx, name, cc, ty, output);
236 externs.insert(name.to_string(), f);
240 fn get_extern_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str, did: ast::DefId) -> ValueRef {
241 match ccx.externs.borrow().find_equiv(&name) {
242 Some(n) => return *n,
246 let f = decl_rust_fn(ccx, fn_ty, name);
248 csearch::get_item_attrs(&ccx.sess().cstore, did, |attrs| {
249 set_llvm_fn_attrs(attrs.as_slice(), f)
252 ccx.externs.borrow_mut().insert(name.to_string(), f);
256 pub fn decl_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
257 let (inputs, output, abi, env) = match ty::get(fn_ty).sty {
258 ty::ty_bare_fn(ref f) => {
259 (f.sig.inputs.clone(), f.sig.output, f.abi, None)
261 ty::ty_closure(ref f) => {
262 (f.sig.inputs.clone(), f.sig.output, f.abi, Some(Type::i8p(ccx)))
264 ty::ty_unboxed_closure(closure_did) => {
265 let unboxed_closure_types = ccx.tcx
266 .unboxed_closure_types
268 let function_type = unboxed_closure_types.get(&closure_did);
269 let llenvironment_type = type_of(ccx, fn_ty).ptr_to();
270 (function_type.sig.inputs.clone(),
271 function_type.sig.output,
273 Some(llenvironment_type))
275 _ => fail!("expected closure or fn")
278 let llfty = type_of_rust_fn(ccx, env, inputs.as_slice(), output, abi);
279 debug!("decl_rust_fn(input count={},type={})",
281 ccx.tn.type_to_string(llfty));
283 let llfn = decl_fn(ccx, name, llvm::CCallConv, llfty, output);
284 let attrs = get_fn_llvm_attributes(ccx, fn_ty);
285 for &(idx, attr) in attrs.iter() {
287 llvm::LLVMAddFunctionAttribute(llfn, idx as c_uint, attr);
294 pub fn decl_internal_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
295 let llfn = decl_rust_fn(ccx, fn_ty, name);
296 llvm::SetLinkage(llfn, llvm::InternalLinkage);
300 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
301 name: &str, ty: Type) -> ValueRef {
302 match externs.find_equiv(&name) {
303 Some(n) => return *n,
307 let c = name.with_c_str(|buf| {
308 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
310 externs.insert(name.to_string(), c);
315 // Returns a pointer to the body for the box. The box may be an opaque
316 // box. The result will be casted to the type of body_t, if it is statically
318 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
319 let _icx = push_ctxt("at_box_body");
321 let ty = Type::at_box(ccx, type_of(ccx, body_t));
322 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
323 GEPi(bcx, boxptr, [0u, abi::box_field_body])
326 fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
327 match bcx.tcx().lang_items.require(it) {
330 bcx.sess().fatal(format!("allocation of `{}` {}",
331 bcx.ty_to_string(info_ty),
337 // The following malloc_raw_dyn* functions allocate a box to contain
338 // a given type, but with a potentially dynamic size.
340 pub fn malloc_raw_dyn<'a>(bcx: &'a Block<'a>,
345 let _icx = push_ctxt("malloc_raw_exchange");
349 let r = callee::trans_lang_call(bcx,
350 require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
354 let llty_ptr = type_of::type_of(ccx, ptr_ty);
355 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
358 pub fn malloc_raw_dyn_managed<'a>(
364 let _icx = push_ctxt("malloc_raw_managed");
367 let langcall = require_alloc_fn(bcx, t, alloc_fn);
369 // Grab the TypeRef type of box_ptr_ty.
370 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
371 let llty = type_of(ccx, box_ptr_ty);
372 let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
375 let drop_glue = glue::get_drop_glue(ccx, t);
376 let r = callee::trans_lang_call(
380 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
385 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
388 // Type descriptor and type glue stuff
390 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
391 match ccx.tydescs.borrow().find(&t) {
392 Some(inf) => return inf.clone(),
396 ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
397 let inf = Rc::new(glue::declare_tydesc(ccx, t));
399 ccx.tydescs.borrow_mut().insert(t, inf.clone());
403 #[allow(dead_code)] // useful
404 pub fn set_optimize_for_size(f: ValueRef) {
405 llvm::SetFunctionAttribute(f, llvm::OptimizeForSizeAttribute)
408 pub fn set_no_inline(f: ValueRef) {
409 llvm::SetFunctionAttribute(f, llvm::NoInlineAttribute)
412 #[allow(dead_code)] // useful
413 pub fn set_no_unwind(f: ValueRef) {
414 llvm::SetFunctionAttribute(f, llvm::NoUnwindAttribute)
417 // Tell LLVM to emit the information necessary to unwind the stack for the
419 pub fn set_uwtable(f: ValueRef) {
420 llvm::SetFunctionAttribute(f, llvm::UWTableAttribute)
423 pub fn set_inline_hint(f: ValueRef) {
424 llvm::SetFunctionAttribute(f, llvm::InlineHintAttribute)
427 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
429 // Set the inline hint if there is one
430 match find_inline_attr(attrs) {
431 InlineHint => set_inline_hint(llfn),
432 InlineAlways => set_always_inline(llfn),
433 InlineNever => set_no_inline(llfn),
434 InlineNone => { /* fallthrough */ }
437 // Add the no-split-stack attribute if requested
438 if contains_name(attrs, "no_split_stack") {
439 unset_split_stack(llfn);
442 if contains_name(attrs, "cold") {
444 llvm::LLVMAddFunctionAttribute(llfn,
445 llvm::FunctionIndex as c_uint,
446 llvm::ColdAttribute as uint64_t)
451 pub fn set_always_inline(f: ValueRef) {
452 llvm::SetFunctionAttribute(f, llvm::AlwaysInlineAttribute)
455 pub fn set_split_stack(f: ValueRef) {
456 "split-stack".with_c_str(|buf| {
457 unsafe { llvm::LLVMAddFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
461 pub fn unset_split_stack(f: ValueRef) {
462 "split-stack".with_c_str(|buf| {
463 unsafe { llvm::LLVMRemoveFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
467 // Double-check that we never ask LLVM to declare the same symbol twice. It
468 // silently mangles such symbols, breaking our linkage model.
469 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) {
470 if ccx.all_llvm_symbols.borrow().contains(&sym) {
471 ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).as_slice());
473 ccx.all_llvm_symbols.borrow_mut().insert(sym);
477 pub fn get_res_dtor(ccx: &CrateContext,
480 parent_id: ast::DefId,
481 substs: &subst::Substs)
483 let _icx = push_ctxt("trans_res_dtor");
484 let did = if did.krate != ast::LOCAL_CRATE {
485 inline::maybe_instantiate_inline(ccx, did)
490 if !substs.types.is_empty() {
491 assert_eq!(did.krate, ast::LOCAL_CRATE);
493 let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, substs);
494 let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, vtables, None);
497 } else if did.krate == ast::LOCAL_CRATE {
498 get_item_val(ccx, did.node)
501 let name = csearch::get_symbol(&ccx.sess().cstore, did);
502 let class_ty = ty::lookup_item_type(tcx, parent_id).ty.subst(tcx, substs);
503 let llty = type_of_dtor(ccx, class_ty);
504 let dtor_ty = ty::mk_ctor_fn(ccx.tcx(), ast::DUMMY_NODE_ID,
505 [glue::get_drop_glue_type(ccx, t)], ty::mk_nil());
507 &mut *ccx.externs.borrow_mut(),
515 // Structural comparison: a rather involved form of glue.
516 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
517 if cx.sess().opts.cg.save_temps {
520 llvm::LLVMSetValueName(v, buf)
527 // Used only for creating scalar comparison glue.
528 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
530 pub fn compare_scalar_types<'a>(
537 let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
539 match ty::get(t).sty {
540 ty::ty_nil => f(nil_type),
541 ty::ty_bool | ty::ty_ptr(_) |
542 ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
543 ty::ty_int(_) => f(signed_int),
544 ty::ty_float(_) => f(floating_point),
545 // Should never get here, because t is scalar.
546 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
551 // A helper function to do the actual comparison of scalar values.
552 pub fn compare_scalar_values<'a>(
559 let _icx = push_ctxt("compare_scalar_values");
560 fn die(cx: &Block) -> ! {
561 cx.sess().bug("compare_scalar_values: must be a comparison operator");
565 // We don't need to do actual comparisons for nil.
566 // () == () holds but () < () does not.
568 ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(cx.ccx(), true),
569 ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(cx.ccx(), false),
570 // refinements would be nice
576 ast::BiEq => llvm::RealOEQ,
577 ast::BiNe => llvm::RealUNE,
578 ast::BiLt => llvm::RealOLT,
579 ast::BiLe => llvm::RealOLE,
580 ast::BiGt => llvm::RealOGT,
581 ast::BiGe => llvm::RealOGE,
584 return FCmp(cx, cmp, lhs, rhs);
588 ast::BiEq => llvm::IntEQ,
589 ast::BiNe => llvm::IntNE,
590 ast::BiLt => llvm::IntSLT,
591 ast::BiLe => llvm::IntSLE,
592 ast::BiGt => llvm::IntSGT,
593 ast::BiGe => llvm::IntSGE,
596 return ICmp(cx, cmp, lhs, rhs);
600 ast::BiEq => llvm::IntEQ,
601 ast::BiNe => llvm::IntNE,
602 ast::BiLt => llvm::IntULT,
603 ast::BiLe => llvm::IntULE,
604 ast::BiGt => llvm::IntUGT,
605 ast::BiGe => llvm::IntUGE,
608 return ICmp(cx, cmp, lhs, rhs);
613 pub fn compare_simd_types(
621 match ty::get(t).sty {
623 // The comparison operators for floating point vectors are challenging.
624 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
625 // then bitcast to a floating point vector, the result will be `-NaN`
626 // for each truth value. Because of this they are unsupported.
627 cx.sess().bug("compare_simd_types: comparison operators \
628 not supported for floating point SIMD types")
630 ty::ty_uint(_) | ty::ty_int(_) => {
632 ast::BiEq => llvm::IntEQ,
633 ast::BiNe => llvm::IntNE,
634 ast::BiLt => llvm::IntSLT,
635 ast::BiLe => llvm::IntSLE,
636 ast::BiGt => llvm::IntSGT,
637 ast::BiGe => llvm::IntSGE,
638 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
640 let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
641 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
642 // to get the correctly sized type. This will compile to a single instruction
643 // once the IR is converted to assembly if the SIMD instruction is supported
644 // by the target architecture.
645 SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
647 _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
651 pub type val_and_ty_fn<'r,'b> =
652 |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
654 // Iterates through the elements of a structural type.
655 pub fn iter_structural_ty<'r,
660 f: val_and_ty_fn<'r,'b>)
662 let _icx = push_ctxt("iter_structural_ty");
669 variant: &ty::VariantInfo,
670 substs: &subst::Substs,
671 f: val_and_ty_fn<'r,'b>)
673 let _icx = push_ctxt("iter_variant");
677 for (i, &arg) in variant.args.iter().enumerate() {
679 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
680 arg.subst(tcx, substs));
686 match ty::get(t).sty {
687 ty::ty_struct(..) => {
688 let repr = adt::represent_type(cx.ccx(), t);
689 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
690 for (i, field_ty) in field_tys.iter().enumerate() {
691 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, discr, i);
692 cx = f(cx, llfld_a, field_ty.mt.ty);
696 ty::ty_unboxed_closure(def_id) => {
697 let repr = adt::represent_type(cx.ccx(), t);
698 let upvars = ty::unboxed_closure_upvars(cx.tcx(), def_id);
699 for (i, upvar) in upvars.iter().enumerate() {
700 let llupvar = adt::trans_field_ptr(cx, &*repr, av, 0, i);
701 cx = f(cx, llupvar, upvar.ty);
704 ty::ty_vec(_, Some(n)) => {
705 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
706 let (base, len) = tvec::get_fixed_base_and_byte_len(cx, av, unit_ty, n);
707 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
709 ty::ty_tup(ref args) => {
710 let repr = adt::represent_type(cx.ccx(), t);
711 for (i, arg) in args.iter().enumerate() {
712 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, 0, i);
713 cx = f(cx, llfld_a, *arg);
716 ty::ty_enum(tid, ref substs) => {
720 let repr = adt::represent_type(ccx, t);
721 let variants = ty::enum_variants(ccx.tcx(), tid);
722 let n_variants = (*variants).len();
724 // NB: we must hit the discriminant first so that structural
725 // comparison know not to proceed when the discriminants differ.
727 match adt::trans_switch(cx, &*repr, av) {
728 (_match::single, None) => {
729 cx = iter_variant(cx, &*repr, av, &**variants.get(0),
732 (_match::switch, Some(lldiscrim_a)) => {
733 cx = f(cx, lldiscrim_a, ty::mk_int());
734 let unr_cx = fcx.new_temp_block("enum-iter-unr");
736 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
738 let next_cx = fcx.new_temp_block("enum-iter-next");
740 for variant in (*variants).iter() {
743 format!("enum-iter-variant-{}",
744 variant.disr_val.to_string().as_slice())
746 match adt::trans_case(cx, &*repr, variant.disr_val) {
747 _match::single_result(r) => {
748 AddCase(llswitch, r.val, variant_cx.llbb)
750 _ => ccx.sess().unimpl("value from adt::trans_case \
751 in iter_structural_ty")
754 iter_variant(variant_cx,
760 Br(variant_cx, next_cx.llbb);
764 _ => ccx.sess().unimpl("value from adt::trans_switch \
765 in iter_structural_ty")
768 _ => cx.sess().unimpl("type in iter_structural_ty")
773 pub fn cast_shift_expr_rhs<'a>(
779 cast_shift_rhs(op, lhs, rhs,
780 |a,b| Trunc(cx, a, b),
781 |a,b| ZExt(cx, a, b))
784 pub fn cast_shift_const_rhs(op: ast::BinOp,
785 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
786 cast_shift_rhs(op, lhs, rhs,
787 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
788 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
791 pub fn cast_shift_rhs(op: ast::BinOp,
794 trunc: |ValueRef, Type| -> ValueRef,
795 zext: |ValueRef, Type| -> ValueRef)
797 // Shifts may have any size int on the rhs
799 if ast_util::is_shift_binop(op) {
800 let mut rhs_llty = val_ty(rhs);
801 let mut lhs_llty = val_ty(lhs);
802 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
803 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
804 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
805 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
808 } else if lhs_sz > rhs_sz {
809 // FIXME (#1877: If shifting by negative
810 // values becomes not undefined then this is wrong.
821 pub fn fail_if_zero_or_overflows<'a>(
829 let (zero_text, overflow_text) = if divrem == ast::BiDiv {
830 ("attempted to divide by zero",
831 "attempted to divide with overflow")
833 ("attempted remainder with a divisor of zero",
834 "attempted remainder with overflow")
836 let (is_zero, is_signed) = match ty::get(rhs_t).sty {
838 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
839 (ICmp(cx, llvm::IntEQ, rhs, zero), true)
842 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
843 (ICmp(cx, llvm::IntEQ, rhs, zero), false)
846 cx.sess().bug(format!("fail-if-zero on unexpected type: {}",
847 ty_to_string(cx.tcx(), rhs_t)).as_slice());
850 let bcx = with_cond(cx, is_zero, |bcx| {
851 controlflow::trans_fail(bcx, span, InternedString::new(zero_text))
854 // To quote LLVM's documentation for the sdiv instruction:
856 // Division by zero leads to undefined behavior. Overflow also leads
857 // to undefined behavior; this is a rare case, but can occur, for
858 // example, by doing a 32-bit division of -2147483648 by -1.
860 // In order to avoid undefined behavior, we perform runtime checks for
861 // signed division/remainder which would trigger overflow. For unsigned
862 // integers, no action beyond checking for zero need be taken.
864 let (llty, min) = match ty::get(rhs_t).sty {
866 let llty = Type::int_from_ty(cx.ccx(), t);
868 ast::TyI if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
869 ast::TyI => i64::MIN as u64,
870 ast::TyI8 => i8::MIN as u64,
871 ast::TyI16 => i16::MIN as u64,
872 ast::TyI32 => i32::MIN as u64,
873 ast::TyI64 => i64::MIN as u64,
879 let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
880 C_integral(llty, -1, false));
881 with_cond(bcx, minus_one, |bcx| {
882 let is_min = ICmp(bcx, llvm::IntEQ, lhs,
883 C_integral(llty, min, true));
884 with_cond(bcx, is_min, |bcx| {
885 controlflow::trans_fail(bcx, span,
886 InternedString::new(overflow_text))
894 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
895 let name = csearch::get_symbol(&ccx.sess().cstore, did);
896 match ty::get(t).sty {
897 ty::ty_bare_fn(ref fn_ty) => {
898 match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
899 ccx.sess().targ_cfg.arch) {
900 Some(Rust) | Some(RustCall) => {
901 get_extern_rust_fn(ccx, t, name.as_slice(), did)
903 Some(RustIntrinsic) => {
904 ccx.sess().bug("unexpected intrinsic in trans_external_path")
907 foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
908 name.as_slice(), None)
912 ty::ty_closure(_) => {
913 get_extern_rust_fn(ccx, t, name.as_slice(), did)
916 let llty = type_of(ccx, t);
917 get_extern_const(&mut *ccx.externs.borrow_mut(),
928 llargs: Vec<ValueRef> ,
930 call_info: Option<NodeInfo>)
931 -> (ValueRef, &'a Block<'a>) {
932 let _icx = push_ctxt("invoke_");
933 if bcx.unreachable.get() {
934 return (C_null(Type::i8(bcx.ccx())), bcx);
937 let attributes = get_fn_llvm_attributes(bcx.ccx(), fn_ty);
939 match bcx.opt_node_id {
941 debug!("invoke at ???");
944 debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
948 if need_invoke(bcx) {
949 debug!("invoking {} at {}", llfn, bcx.llbb);
950 for &llarg in llargs.iter() {
951 debug!("arg: {}", llarg);
953 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
954 let landing_pad = bcx.fcx.get_landing_pad();
957 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
958 None => debuginfo::clear_source_location(bcx.fcx)
961 let llresult = Invoke(bcx,
966 attributes.as_slice());
967 return (llresult, normal_bcx);
969 debug!("calling {} at {}", llfn, bcx.llbb);
970 for &llarg in llargs.iter() {
971 debug!("arg: {}", llarg);
975 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
976 None => debuginfo::clear_source_location(bcx.fcx)
979 let llresult = Call(bcx, llfn, llargs.as_slice(), attributes.as_slice());
980 return (llresult, bcx);
984 pub fn need_invoke(bcx: &Block) -> bool {
985 if bcx.sess().no_landing_pads() {
989 // Avoid using invoke if we are already inside a landing pad.
994 bcx.fcx.needs_invoke()
997 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
998 let _icx = push_ctxt("load_if_immediate");
999 if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
1003 pub fn load_ty(cx: &Block, ptr: ValueRef, t: ty::t) -> ValueRef {
1005 * Helper for loading values from memory. Does the necessary conversion if
1006 * the in-memory type differs from the type used for SSA values. Also
1007 * handles various special cases where the type gives us better information
1008 * about what we are loading.
1010 if type_is_zero_size(cx.ccx(), t) {
1011 C_undef(type_of::type_of(cx.ccx(), t))
1012 } else if ty::type_is_bool(t) {
1013 Trunc(cx, LoadRangeAssert(cx, ptr, 0, 2, llvm::False), Type::i1(cx.ccx()))
1014 } else if ty::type_is_char(t) {
1015 // a char is a unicode codepoint, and so takes values from 0
1016 // to 0x10FFFF inclusive only.
1017 LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
1023 pub fn store_ty(cx: &Block, v: ValueRef, dst: ValueRef, t: ty::t) {
1025 * Helper for storing values in memory. Does the necessary conversion if
1026 * the in-memory type differs from the type used for SSA values.
1028 if ty::type_is_bool(t) {
1029 Store(cx, ZExt(cx, v, Type::i8(cx.ccx())), dst);
1035 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
1036 match local.pat.node {
1037 ast::PatWild => true, _ => false
1041 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
1043 debug!("init_local(bcx={}, local.id={:?})", bcx.to_str(), local.id);
1044 let _indenter = indenter();
1045 let _icx = push_ctxt("init_local");
1046 _match::store_local(bcx, local)
1049 pub fn raw_block<'a>(
1050 fcx: &'a FunctionContext<'a>,
1052 llbb: BasicBlockRef)
1054 Block::new(llbb, is_lpad, None, fcx)
1057 pub fn with_cond<'a>(
1060 f: |&'a Block<'a>| -> &'a Block<'a>)
1062 let _icx = push_ctxt("with_cond");
1064 let next_cx = fcx.new_temp_block("next");
1065 let cond_cx = fcx.new_temp_block("cond");
1066 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1067 let after_cx = f(cond_cx);
1068 if !after_cx.terminated.get() {
1069 Br(after_cx, next_cx.llbb);
1074 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1075 let _icx = push_ctxt("call_memcpy");
1077 let key = match ccx.sess().targ_cfg.arch {
1078 X86 | Arm | Mips | Mipsel => "llvm.memcpy.p0i8.p0i8.i32",
1079 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1081 let memcpy = ccx.get_intrinsic(&key);
1082 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1083 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1084 let size = IntCast(cx, n_bytes, ccx.int_type);
1085 let align = C_i32(ccx, align as i32);
1086 let volatile = C_bool(ccx, false);
1087 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1090 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1091 let _icx = push_ctxt("memcpy_ty");
1092 let ccx = bcx.ccx();
1093 if ty::type_is_structural(t) {
1094 let llty = type_of::type_of(ccx, t);
1095 let llsz = llsize_of(ccx, llty);
1096 let llalign = llalign_of_min(ccx, llty);
1097 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1099 Store(bcx, Load(bcx, src), dst);
1103 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1104 if cx.unreachable.get() { return; }
1105 let _icx = push_ctxt("zero_mem");
1108 let llty = type_of::type_of(ccx, t);
1109 memzero(&B(bcx), llptr, llty);
1112 // Always use this function instead of storing a zero constant to the memory
1113 // in question. If you store a zero constant, LLVM will drown in vreg
1114 // allocation for large data structures, and the generated code will be
1115 // awful. (A telltale sign of this is large quantities of
1116 // `mov [byte ptr foo],0` in the generated code.)
1117 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1118 let _icx = push_ctxt("memzero");
1121 let intrinsic_key = match ccx.sess().targ_cfg.arch {
1122 X86 | Arm | Mips | Mipsel => "llvm.memset.p0i8.i32",
1123 X86_64 => "llvm.memset.p0i8.i64"
1126 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1127 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1128 let llzeroval = C_u8(ccx, 0);
1129 let size = machine::llsize_of(ccx, ty);
1130 let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1131 let volatile = C_bool(ccx, false);
1132 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1135 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1136 let _icx = push_ctxt("alloc_ty");
1137 let ccx = bcx.ccx();
1138 let ty = type_of::type_of(ccx, t);
1139 assert!(!ty::type_has_params(t));
1140 let val = alloca(bcx, ty, name);
1144 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1145 alloca_maybe_zeroed(cx, ty, name, false)
1148 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1149 let _icx = push_ctxt("alloca");
1150 if cx.unreachable.get() {
1152 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1155 debuginfo::clear_source_location(cx.fcx);
1156 let p = Alloca(cx, ty, name);
1158 let b = cx.fcx.ccx.builder();
1159 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1165 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1166 let _icx = push_ctxt("arrayalloca");
1167 if cx.unreachable.get() {
1169 return llvm::LLVMGetUndef(ty.to_ref());
1172 debuginfo::clear_source_location(cx.fcx);
1173 return ArrayAlloca(cx, ty, v);
1176 // Creates and returns space for, or returns the argument representing, the
1177 // slot where the return value of the function must go.
1178 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1180 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1181 get_param(fcx.llfn, 0)
1183 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1184 AllocaFcx(fcx, lloutputtype, "__make_return_pointer")
1188 // NB: must keep 4 fns in sync:
1191 // - create_datums_for_fn_args.
1195 // Be warned! You must call `init_function` before doing anything with the
1196 // returned function context.
1197 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1202 param_substs: &'a param_substs,
1204 block_arena: &'a TypedArena<Block<'a>>)
1205 -> FunctionContext<'a> {
1206 param_substs.validate();
1208 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1212 ccx.tcx.map.path_to_string(id).to_string()
1214 id, param_substs.repr(ccx.tcx()));
1216 let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1217 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1218 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1220 let mut fcx = FunctionContext {
1223 llretptr: Cell::new(None),
1224 alloca_insert_pt: Cell::new(None),
1225 llreturn: Cell::new(None),
1226 personality: Cell::new(None),
1227 caller_expects_out_pointer: uses_outptr,
1228 llargs: RefCell::new(NodeMap::new()),
1229 lllocals: RefCell::new(NodeMap::new()),
1230 llupvars: RefCell::new(NodeMap::new()),
1232 param_substs: param_substs,
1234 block_arena: block_arena,
1236 debug_context: debug_context,
1237 scopes: RefCell::new(Vec::new())
1241 fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1247 /// Performs setup on a newly created function, creating the entry scope block
1248 /// and allocating space for the return pointer.
1249 pub fn init_function<'a>(fcx: &'a FunctionContext<'a>,
1251 output_type: ty::t) -> &'a Block<'a> {
1252 let entry_bcx = fcx.new_temp_block("entry-block");
1254 // Use a dummy instruction as the insertion point for all allocas.
1255 // This is later removed in FunctionContext::cleanup.
1256 fcx.alloca_insert_pt.set(Some(unsafe {
1257 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1258 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1261 // This shouldn't need to recompute the return type,
1262 // as new_fn_ctxt did it already.
1263 let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1265 if !return_type_is_void(fcx.ccx, substd_output_type) {
1266 // If the function returns nil/bot, there is no real return
1267 // value, so do not set `llretptr`.
1268 if !skip_retptr || fcx.caller_expects_out_pointer {
1269 // Otherwise, we normally allocate the llretptr, unless we
1270 // have been instructed to skip it for immediate return
1272 fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1279 // NB: must keep 4 fns in sync:
1282 // - create_datums_for_fn_args.
1286 pub fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1287 use middle::trans::datum::{ByRef, ByValue};
1290 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1294 // work around bizarre resolve errors
1295 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1296 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1298 // create_datums_for_fn_args: creates rvalue datums for each of the
1299 // incoming function arguments. These will later be stored into
1300 // appropriate lvalue datums.
1301 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1303 -> Vec<RvalueDatum> {
1304 let _icx = push_ctxt("create_datums_for_fn_args");
1306 // Return an array wrapping the ValueRefs that we get from `get_param` for
1307 // each argument into datums.
1308 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1309 let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1310 datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1314 /// Creates rvalue datums for each of the incoming function arguments and
1315 /// tuples the arguments. These will later be stored into appropriate lvalue
1317 fn create_datums_for_fn_args_under_call_abi<
1319 mut bcx: &'a Block<'a>,
1320 arg_scope: cleanup::CustomScopeIndex,
1322 -> Vec<RvalueDatum> {
1323 let mut result = Vec::new();
1324 for (i, &arg_ty) in arg_tys.iter().enumerate() {
1325 if i < arg_tys.len() - 1 {
1326 // Regular argument.
1327 let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1328 result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1333 // This is the last argument. Tuple it.
1334 match ty::get(arg_ty).sty {
1335 ty::ty_tup(ref tupled_arg_tys) => {
1336 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1339 datum::lvalue_scratch_datum(bcx,
1343 tuple_args_scope_id,
1348 for (j, &tupled_arg_ty) in
1349 tupled_arg_tys.iter().enumerate() {
1351 get_param(bcx.fcx.llfn,
1352 bcx.fcx.arg_pos(i + j) as c_uint);
1353 let lldest = GEPi(bcx, llval, [0, j]);
1354 let datum = datum::Datum::new(
1357 arg_kind(bcx.fcx, tupled_arg_ty));
1358 bcx = datum.store_to(bcx, lldest);
1362 let tuple = unpack_datum!(bcx,
1363 tuple.to_expr_datum()
1364 .to_rvalue_datum(bcx,
1369 let mode = datum::Rvalue::new(datum::ByValue);
1370 result.push(datum::Datum::new(C_nil(bcx.ccx()),
1375 bcx.tcx().sess.bug("last argument of a function with \
1376 `rust-call` ABI isn't a tuple?!")
1385 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1386 arg_scope: cleanup::CustomScopeIndex,
1389 arg_datums: Vec<RvalueDatum> )
1391 debug!("copy_args_to_allocas");
1393 let _icx = push_ctxt("copy_args_to_allocas");
1396 let arg_scope_id = cleanup::CustomScope(arg_scope);
1398 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1399 // For certain mode/type combinations, the raw llarg values are passed
1400 // by value. However, within the fn body itself, we want to always
1401 // have all locals and arguments be by-ref so that we can cancel the
1402 // cleanup and for better interaction with LLVM's debug info. So, if
1403 // the argument would be passed by value, we store it into an alloca.
1404 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1405 // the event it's not truly needed.
1407 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1409 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1410 debuginfo::create_argument_metadata(bcx, &args[i]);
1417 fn copy_unboxed_closure_args_to_allocas<'a>(
1418 mut bcx: &'a Block<'a>,
1419 arg_scope: cleanup::CustomScopeIndex,
1421 arg_datums: Vec<RvalueDatum>,
1422 monomorphized_arg_types: &[ty::t])
1424 let _icx = push_ctxt("copy_unboxed_closure_args_to_allocas");
1425 let arg_scope_id = cleanup::CustomScope(arg_scope);
1427 assert_eq!(arg_datums.len(), 1);
1429 let arg_datum = arg_datums.move_iter().next().unwrap();
1431 // Untuple the rest of the arguments.
1434 arg_datum.to_lvalue_datum_in_scope(bcx,
1437 let empty = Vec::new();
1438 let untupled_arg_types = match ty::get(monomorphized_arg_types[0]).sty {
1439 ty::ty_tup(ref types) => types.as_slice(),
1440 ty::ty_nil => empty.as_slice(),
1442 bcx.tcx().sess.span_bug(args[0].pat.span,
1443 "first arg to `rust-call` ABI function \
1447 for j in range(0, args.len()) {
1448 let tuple_element_type = untupled_arg_types[j];
1449 let tuple_element_datum =
1450 tuple_datum.get_element(tuple_element_type,
1451 |llval| GEPi(bcx, llval, [0, j]));
1452 let tuple_element_datum = tuple_element_datum.to_expr_datum();
1453 let tuple_element_datum =
1455 tuple_element_datum.to_rvalue_datum(bcx,
1457 bcx = _match::store_arg(bcx,
1459 tuple_element_datum,
1462 if bcx.fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1463 debuginfo::create_argument_metadata(bcx, &args[j]);
1470 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1471 // and builds the return block.
1472 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1473 last_bcx: &'a Block<'a>,
1475 let _icx = push_ctxt("finish_fn");
1477 // This shouldn't need to recompute the return type,
1478 // as new_fn_ctxt did it already.
1479 let substd_retty = retty.substp(fcx.ccx.tcx(), fcx.param_substs);
1481 let ret_cx = match fcx.llreturn.get() {
1483 if !last_bcx.terminated.get() {
1484 Br(last_bcx, llreturn);
1486 raw_block(fcx, false, llreturn)
1490 build_return_block(fcx, ret_cx, substd_retty);
1491 debuginfo::clear_source_location(fcx);
1495 // Builds the return block for a function.
1496 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block, retty: ty::t) {
1497 // Return the value if this function immediate; otherwise, return void.
1498 if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1499 return RetVoid(ret_cx);
1502 let retptr = Value(fcx.llretptr.get().unwrap());
1503 let retval = match retptr.get_dominating_store(ret_cx) {
1504 // If there's only a single store to the ret slot, we can directly return
1505 // the value that was stored and omit the store and the alloca
1507 let retval = s.get_operand(0).unwrap().get();
1508 s.erase_from_parent();
1510 if retptr.has_no_uses() {
1511 retptr.erase_from_parent();
1514 if ty::type_is_bool(retty) {
1515 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1520 // Otherwise, load the return value from the ret slot
1521 None => load_ty(ret_cx, fcx.llretptr.get().unwrap(), retty)
1524 Ret(ret_cx, retval);
1527 #[deriving(Clone, Eq, PartialEq)]
1528 pub enum IsUnboxedClosureFlag {
1533 // trans_closure: Builds an LLVM function out of a source function.
1534 // If the function closes over its environment a closure will be
1536 pub fn trans_closure(ccx: &CrateContext,
1540 param_substs: ¶m_substs,
1542 _attributes: &[ast::Attribute],
1543 arg_types: Vec<ty::t>,
1547 is_unboxed_closure: IsUnboxedClosureFlag,
1548 maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1549 ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1551 let _icx = push_ctxt("trans_closure");
1552 set_uwtable(llfndecl);
1554 debug!("trans_closure(..., param_substs={})",
1555 param_substs.repr(ccx.tcx()));
1557 let arena = TypedArena::new();
1558 let fcx = new_fn_ctxt(ccx,
1566 let mut bcx = init_function(&fcx, false, output_type);
1568 // cleanup scope for the incoming arguments
1569 let arg_scope = fcx.push_custom_cleanup_scope();
1571 let block_ty = node_id_type(bcx, body.id);
1573 // Set up arguments to the function.
1574 let monomorphized_arg_types =
1576 .map(|at| monomorphize_type(bcx, *at))
1577 .collect::<Vec<_>>();
1578 for monomorphized_arg_type in monomorphized_arg_types.iter() {
1579 debug!("trans_closure: monomorphized_arg_type: {}",
1580 ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1582 debug!("trans_closure: function lltype: {}",
1583 bcx.fcx.ccx.tn.val_to_string(bcx.fcx.llfn));
1585 let arg_datums = if abi != RustCall {
1586 create_datums_for_fn_args(&fcx,
1587 monomorphized_arg_types.as_slice())
1589 create_datums_for_fn_args_under_call_abi(
1592 monomorphized_arg_types.as_slice())
1595 bcx = match is_unboxed_closure {
1596 NotUnboxedClosure => {
1597 copy_args_to_allocas(&fcx,
1600 decl.inputs.as_slice(),
1603 IsUnboxedClosure => {
1604 copy_unboxed_closure_args_to_allocas(
1607 decl.inputs.as_slice(),
1609 monomorphized_arg_types.as_slice())
1613 bcx = maybe_load_env(bcx);
1615 // Up until here, IR instructions for this function have explicitly not been annotated with
1616 // source code location, so we don't step into call setup code. From here on, source location
1617 // emitting should be enabled.
1618 debuginfo::start_emitting_source_locations(&fcx);
1620 let dest = match fcx.llretptr.get() {
1621 Some(e) => {expr::SaveIn(e)}
1623 assert!(type_is_zero_size(bcx.ccx(), block_ty))
1628 // This call to trans_block is the place where we bridge between
1629 // translation calls that don't have a return value (trans_crate,
1630 // trans_mod, trans_item, et cetera) and those that do
1631 // (trans_block, trans_expr, et cetera).
1632 bcx = controlflow::trans_block(bcx, body, dest);
1634 match fcx.llreturn.get() {
1636 Br(bcx, fcx.return_exit_block());
1637 fcx.pop_custom_cleanup_scope(arg_scope);
1640 // Microoptimization writ large: avoid creating a separate
1641 // llreturn basic block
1642 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1646 // Put return block after all other blocks.
1647 // This somewhat improves single-stepping experience in debugger.
1649 let llreturn = fcx.llreturn.get();
1650 for &llreturn in llreturn.iter() {
1651 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1655 // Insert the mandatory first few basic blocks before lltop.
1656 finish_fn(&fcx, bcx, output_type);
1659 // trans_fn: creates an LLVM function corresponding to a source language
1661 pub fn trans_fn(ccx: &CrateContext,
1665 param_substs: ¶m_substs,
1667 attrs: &[ast::Attribute]) {
1668 let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_string(id).to_string());
1669 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1670 let _icx = push_ctxt("trans_fn");
1671 let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1672 let arg_types = ty::ty_fn_args(fn_ty);
1673 let output_type = ty::ty_fn_ret(fn_ty);
1674 let abi = ty::ty_fn_abi(fn_ty);
1690 pub fn trans_enum_variant(ccx: &CrateContext,
1691 _enum_id: ast::NodeId,
1692 variant: &ast::Variant,
1693 _args: &[ast::VariantArg],
1695 param_substs: ¶m_substs,
1696 llfndecl: ValueRef) {
1697 let _icx = push_ctxt("trans_enum_variant");
1699 trans_enum_variant_or_tuple_like_struct(
1707 pub fn trans_tuple_struct(ccx: &CrateContext,
1708 _fields: &[ast::StructField],
1709 ctor_id: ast::NodeId,
1710 param_substs: ¶m_substs,
1711 llfndecl: ValueRef) {
1712 let _icx = push_ctxt("trans_tuple_struct");
1714 trans_enum_variant_or_tuple_like_struct(
1722 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1723 ctor_id: ast::NodeId,
1725 param_substs: ¶m_substs,
1726 llfndecl: ValueRef) {
1727 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1728 let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
1730 let result_ty = match ty::get(ctor_ty).sty {
1731 ty::ty_bare_fn(ref bft) => bft.sig.output,
1732 _ => ccx.sess().bug(
1733 format!("trans_enum_variant_or_tuple_like_struct: \
1734 unexpected ctor return type {}",
1735 ty_to_string(ccx.tcx(), ctor_ty)).as_slice())
1738 let arena = TypedArena::new();
1739 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1740 param_substs, None, &arena);
1741 let bcx = init_function(&fcx, false, result_ty);
1743 let arg_tys = ty::ty_fn_args(ctor_ty);
1745 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1747 if !type_is_zero_size(fcx.ccx, result_ty) {
1748 let repr = adt::represent_type(ccx, result_ty);
1749 adt::trans_start_init(bcx, &*repr, fcx.llretptr.get().unwrap(), disr);
1750 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1751 let lldestptr = adt::trans_field_ptr(bcx,
1753 fcx.llretptr.get().unwrap(),
1756 arg_datum.store_to(bcx, lldestptr);
1760 finish_fn(&fcx, bcx, result_ty);
1763 fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1764 sp: Span, id: ast::NodeId, vi: &[Rc<ty::VariantInfo>],
1766 for variant in enum_definition.variants.iter() {
1767 let disr_val = vi[*i].disr_val;
1770 match variant.node.kind {
1771 ast::TupleVariantKind(ref args) if args.len() > 0 => {
1772 let llfn = get_item_val(ccx, variant.node.id);
1773 trans_enum_variant(ccx, id, &**variant, args.as_slice(),
1774 disr_val, ¶m_substs::empty(), llfn);
1776 ast::TupleVariantKind(_) => {
1779 ast::StructVariantKind(struct_def) => {
1780 trans_struct_def(ccx, struct_def);
1785 enum_variant_size_lint(ccx, enum_definition, sp, id);
1788 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
1789 let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
1791 let levels = ccx.tcx.node_lint_levels.borrow();
1792 let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCE);
1793 let lvlsrc = match levels.find(&(id, lint_id)) {
1794 None | Some(&(lint::Allow, _)) => return,
1795 Some(&lvlsrc) => lvlsrc,
1798 let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
1800 adt::General(_, ref variants) => {
1801 for var in variants.iter() {
1803 for field in var.fields.iter().skip(1) {
1804 // skip the discriminant
1805 size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
1810 _ => { /* its size is either constant or unimportant */ }
1813 let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
1814 |(l, s, li), (idx, &size)|
1817 } else if size > s {
1824 // we only warn if the largest variant is at least thrice as large as
1825 // the second-largest.
1826 if largest > slargest * 3 && slargest > 0 {
1827 // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
1828 // pass for the latter already ran.
1829 lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCE,
1831 format!("enum variant is more than three times larger \
1832 ({} bytes) than the next largest (ignoring padding)",
1833 largest).as_slice());
1835 ccx.sess().span_note(enum_def.variants.get(largest_index).span,
1836 "this variant is the largest");
1840 pub struct TransItemVisitor<'a> {
1841 pub ccx: &'a CrateContext,
1844 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1845 fn visit_item(&mut self, i: &ast::Item, _:()) {
1846 trans_item(self.ccx, i);
1850 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1851 let _icx = push_ctxt("trans_item");
1853 ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
1855 let llfndecl = get_item_val(ccx, item.id);
1856 foreign::trans_rust_fn_with_foreign_abi(
1857 ccx, &**decl, &**body, item.attrs.as_slice(), llfndecl, item.id);
1858 } else if !generics.is_type_parameterized() {
1859 let llfn = get_item_val(ccx, item.id);
1864 ¶m_substs::empty(),
1866 item.attrs.as_slice());
1868 // Be sure to travel more than just one layer deep to catch nested
1869 // items in blocks and such.
1870 let mut v = TransItemVisitor{ ccx: ccx };
1871 v.visit_block(&**body, ());
1874 ast::ItemImpl(ref generics, _, _, ref ms) => {
1875 meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1877 ast::ItemMod(ref m) => {
1880 ast::ItemEnum(ref enum_definition, ref generics) => {
1881 if !generics.is_type_parameterized() {
1882 let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1884 trans_enum_def(ccx, enum_definition, item.span, item.id, vi.as_slice(), &mut i);
1887 ast::ItemStatic(_, m, ref expr) => {
1888 // Recurse on the expression to catch items in blocks
1889 let mut v = TransItemVisitor{ ccx: ccx };
1890 v.visit_expr(&**expr, ());
1891 consts::trans_const(ccx, m, item.id);
1892 // Do static_assert checking. It can't really be done much earlier
1893 // because we need to get the value of the bool out of LLVM
1894 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1895 if m == ast::MutMutable {
1896 ccx.sess().span_fatal(expr.span,
1897 "cannot have static_assert on a mutable \
1901 let v = ccx.const_values.borrow().get_copy(&item.id);
1903 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1904 ccx.sess().span_fatal(expr.span, "static assertion failed");
1909 ast::ItemForeignMod(ref foreign_mod) => {
1910 foreign::trans_foreign_mod(ccx, foreign_mod);
1912 ast::ItemStruct(struct_def, ref generics) => {
1913 if !generics.is_type_parameterized() {
1914 trans_struct_def(ccx, struct_def);
1917 ast::ItemTrait(..) => {
1918 // Inside of this trait definition, we won't be actually translating any
1919 // functions, but the trait still needs to be walked. Otherwise default
1920 // methods with items will not get translated and will cause ICE's when
1921 // metadata time comes around.
1922 let mut v = TransItemVisitor{ ccx: ccx };
1923 visit::walk_item(&mut v, item, ());
1925 _ => {/* fall through */ }
1929 pub fn trans_struct_def(ccx: &CrateContext, struct_def: Gc<ast::StructDef>) {
1930 // If this is a tuple-like struct, translate the constructor.
1931 match struct_def.ctor_id {
1932 // We only need to translate a constructor if there are fields;
1933 // otherwise this is a unit-like struct.
1934 Some(ctor_id) if struct_def.fields.len() > 0 => {
1935 let llfndecl = get_item_val(ccx, ctor_id);
1936 trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1937 ctor_id, ¶m_substs::empty(), llfndecl);
1939 Some(_) | None => {}
1943 // Translate a module. Doing this amounts to translating the items in the
1944 // module; there ends up being no artifact (aside from linkage names) of
1945 // separate modules in the compiled program. That's because modules exist
1946 // only as a convenience for humans working with the code, to organize names
1947 // and control visibility.
1948 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1949 let _icx = push_ctxt("trans_mod");
1950 for item in m.items.iter() {
1951 trans_item(ccx, &**item);
1955 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
1957 ccx.item_symbols.borrow_mut().insert(node_id, sym);
1959 if !ccx.reachable.contains(&node_id) {
1960 llvm::SetLinkage(llfn, llvm::InternalLinkage);
1963 // The stack exhaustion lang item shouldn't have a split stack because
1964 // otherwise it would continue to be exhausted (bad), and both it and the
1965 // eh_personality functions need to be externally linkable.
1966 let def = ast_util::local_def(node_id);
1967 if ccx.tcx.lang_items.stack_exhausted() == Some(def) {
1968 unset_split_stack(llfn);
1969 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
1971 if ccx.tcx.lang_items.eh_personality() == Some(def) {
1972 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
1976 if is_entry_fn(ccx.sess(), node_id) {
1977 create_entry_wrapper(ccx, sp, llfn);
1981 fn register_fn(ccx: &CrateContext,
1984 node_id: ast::NodeId,
1987 match ty::get(node_type).sty {
1988 ty::ty_bare_fn(ref f) => {
1989 assert!(f.abi == Rust || f.abi == RustCall);
1991 _ => fail!("expected bare rust fn")
1994 let llfn = decl_rust_fn(ccx, node_type, sym.as_slice());
1995 finish_register_fn(ccx, sp, sym, node_id, llfn);
1999 pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t)
2000 -> Vec<(uint, u64)> {
2001 use middle::ty::{BrAnon, ReLateBound};
2003 let (fn_sig, abi, has_env) = match ty::get(fn_ty).sty {
2004 ty::ty_closure(ref f) => (f.sig.clone(), f.abi, true),
2005 ty::ty_bare_fn(ref f) => (f.sig.clone(), f.abi, false),
2006 ty::ty_unboxed_closure(closure_did) => {
2007 let unboxed_closure_types = ccx.tcx
2008 .unboxed_closure_types
2010 let function_type = unboxed_closure_types.get(&closure_did);
2011 (function_type.sig.clone(), RustCall, true)
2013 _ => fail!("expected closure or function.")
2016 // These have an odd calling convention, so we skip them for now.
2018 // FIXME(pcwalton): We don't have to skip them; just untuple the result.
2019 if abi == RustCall {
2023 // Since index 0 is the return value of the llvm func, we start
2024 // at either 1 or 2 depending on whether there's an env slot or not
2025 let mut first_arg_offset = if has_env { 2 } else { 1 };
2026 let mut attrs = Vec::new();
2027 let ret_ty = fn_sig.output;
2029 // A function pointer is called without the declaration
2030 // available, so we have to apply any attributes with ABI
2031 // implications directly to the call instruction. Right now,
2032 // the only attribute we need to worry about is `sret`.
2033 if type_of::return_uses_outptr(ccx, ret_ty) {
2034 attrs.push((1, llvm::StructRetAttribute as u64));
2036 // The outptr can be noalias and nocapture because it's entirely
2037 // invisible to the program. We can also mark it as nonnull
2038 attrs.push((1, llvm::NoAliasAttribute as u64));
2039 attrs.push((1, llvm::NoCaptureAttribute as u64));
2040 attrs.push((1, llvm::NonNullAttribute as u64));
2042 // Add one more since there's an outptr
2043 first_arg_offset += 1;
2045 // The `noalias` attribute on the return value is useful to a
2046 // function ptr caller.
2047 match ty::get(ret_ty).sty {
2048 // `~` pointer return values never alias because ownership
2050 ty::ty_uniq(it) if match ty::get(it).sty {
2051 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
2054 attrs.push((llvm::ReturnIndex as uint, llvm::NoAliasAttribute as u64));
2059 // We can also mark the return value as `nonnull` in certain cases
2060 match ty::get(ret_ty).sty {
2061 // These are not really pointers but pairs, (pointer, len)
2063 ty::ty_rptr(_, ty::mt { ty: it, .. }) if match ty::get(it).sty {
2064 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
2066 ty::ty_uniq(_) | ty::ty_rptr(_, _) => {
2067 attrs.push((llvm::ReturnIndex as uint, llvm::NonNullAttribute as u64));
2072 match ty::get(ret_ty).sty {
2074 attrs.push((llvm::ReturnIndex as uint, llvm::ZExtAttribute as u64));
2080 for (idx, &t) in fn_sig.inputs.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
2081 match ty::get(t).sty {
2082 // this needs to be first to prevent fat pointers from falling through
2083 _ if !type_is_immediate(ccx, t) => {
2084 // For non-immediate arguments the callee gets its own copy of
2085 // the value on the stack, so there are no aliases. It's also
2086 // program-invisible so can't possibly capture
2087 attrs.push((idx, llvm::NoAliasAttribute as u64));
2088 attrs.push((idx, llvm::NoCaptureAttribute as u64));
2089 attrs.push((idx, llvm::NonNullAttribute as u64));
2092 attrs.push((idx, llvm::ZExtAttribute as u64));
2094 // `~` pointer parameters never alias because ownership is transferred
2096 attrs.push((idx, llvm::NoAliasAttribute as u64));
2097 attrs.push((idx, llvm::NonNullAttribute as u64));
2099 // `&mut` pointer parameters never alias other parameters, or mutable global data
2100 ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable => {
2101 attrs.push((idx, llvm::NoAliasAttribute as u64));
2102 attrs.push((idx, llvm::NonNullAttribute as u64));
2104 ReLateBound(_, BrAnon(_)) => {
2105 attrs.push((idx, llvm::NoCaptureAttribute as u64));
2110 // When a reference in an argument has no named lifetime, it's impossible for that
2111 // reference to escape this function (returned or stored beyond the call by a closure).
2112 ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
2113 attrs.push((idx, llvm::NoCaptureAttribute as u64));
2114 attrs.push((idx, llvm::NonNullAttribute as u64));
2116 // & pointer parameters are never null
2117 ty::ty_rptr(_, _) => {
2118 attrs.push((idx, llvm::NonNullAttribute as u64));
2127 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2128 pub fn register_fn_llvmty(ccx: &CrateContext,
2131 node_id: ast::NodeId,
2133 llfty: Type) -> ValueRef {
2134 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2136 let llfn = decl_fn(ccx, sym.as_slice(), cc, llfty, ty::mk_nil());
2137 finish_register_fn(ccx, sp, sym, node_id, llfn);
2141 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2142 match *sess.entry_fn.borrow() {
2143 Some((entry_id, _)) => node_id == entry_id,
2148 // Create a _rust_main(args: ~[str]) function which will be called from the
2149 // runtime rust_start function
2150 pub fn create_entry_wrapper(ccx: &CrateContext,
2152 main_llfn: ValueRef) {
2153 let et = ccx.sess().entry_type.get().unwrap();
2155 config::EntryMain => {
2156 create_entry_fn(ccx, main_llfn, true);
2158 config::EntryStart => create_entry_fn(ccx, main_llfn, false),
2159 config::EntryNone => {} // Do nothing.
2162 fn create_entry_fn(ccx: &CrateContext,
2163 rust_main: ValueRef,
2164 use_start_lang_item: bool) {
2165 let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
2168 let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil());
2169 let llbb = "top".with_c_str(|buf| {
2171 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2174 let bld = ccx.builder.b;
2176 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2178 let (start_fn, args) = if use_start_lang_item {
2179 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2181 Err(s) => { ccx.sess().fatal(s.as_slice()); }
2183 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2184 get_item_val(ccx, start_def_id.node)
2186 let start_fn_type = csearch::get_type(ccx.tcx(),
2188 trans_external_path(ccx, start_def_id, start_fn_type)
2192 let opaque_rust_main = "rust_main".with_c_str(|buf| {
2193 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
2204 debug!("using user-defined start fn");
2206 get_param(llfn, 0 as c_uint),
2207 get_param(llfn, 1 as c_uint)
2213 let result = llvm::LLVMBuildCall(bld,
2216 args.len() as c_uint,
2219 llvm::LLVMBuildRet(bld, result);
2224 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
2225 ty: ty::t, attrs: &[ast::Attribute]) -> String {
2226 match attr::first_attr_value_str_by_name(attrs, "export_name") {
2227 // Use provided name
2228 Some(name) => name.get().to_string(),
2230 _ => ccx.tcx.map.with_path(id, |mut path| {
2231 if attr::contains_name(attrs, "no_mangle") {
2233 path.last().unwrap().to_string()
2235 match weak_lang_items::link_name(attrs) {
2236 Some(name) => name.get().to_string(),
2238 // Usual name mangling
2239 mangle_exported_name(ccx, path, ty, id)
2247 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2248 debug!("get_item_val(id=`{:?}`)", id);
2250 match ccx.item_vals.borrow().find_copy(&id) {
2251 Some(v) => return v,
2255 let mut foreign = false;
2256 let item = ccx.tcx.map.get(id);
2257 let val = match item {
2258 ast_map::NodeItem(i) => {
2259 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2260 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
2262 let v = match i.node {
2263 ast::ItemStatic(_, mutbl, ref expr) => {
2264 // If this static came from an external crate, then
2265 // we need to get the symbol from csearch instead of
2266 // using the current crate's name/version
2267 // information in the hash of the symbol
2268 debug!("making {}", sym);
2269 let (sym, is_local) = {
2270 match ccx.external_srcs.borrow().find(&i.id) {
2272 debug!("but found in other crate...");
2273 (csearch::get_symbol(&ccx.sess().cstore,
2280 // We need the translated value here, because for enums the
2281 // LLVM type is not fully determined by the Rust type.
2282 let (v, inlineable) = consts::const_expr(ccx, &**expr, is_local);
2283 ccx.const_values.borrow_mut().insert(id, v);
2284 let mut inlineable = inlineable;
2287 let llty = llvm::LLVMTypeOf(v);
2288 let g = sym.as_slice().with_c_str(|buf| {
2289 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2292 if !ccx.reachable.contains(&id) {
2293 llvm::SetLinkage(g, llvm::InternalLinkage);
2296 // Apply the `unnamed_addr` attribute if
2298 if !ast_util::static_has_significant_address(
2300 i.attrs.as_slice()) {
2301 llvm::SetUnnamedAddr(g, true);
2303 // This is a curious case where we must make
2304 // all of these statics inlineable. If a
2305 // global is not tagged as `#[inline(never)]`,
2306 // then LLVM won't coalesce globals unless they
2307 // have an internal linkage type. This means that
2308 // external crates cannot use this global.
2309 // This is a problem for things like inner
2310 // statics in generic functions, because the
2311 // function will be inlined into another
2312 // crate and then attempt to link to the
2313 // static in the original crate, only to
2314 // find that it's not there. On the other
2315 // side of inlining, the crates knows to
2316 // not declare this static as
2317 // available_externally (because it isn't)
2321 if attr::contains_name(i.attrs.as_slice(),
2323 llvm::set_thread_local(g, true);
2327 debug!("{} not inlined", sym);
2328 ccx.non_inlineable_statics.borrow_mut()
2332 ccx.item_symbols.borrow_mut().insert(i.id, sym);
2337 ast::ItemFn(_, _, abi, _, _) => {
2338 let llfn = if abi == Rust {
2339 register_fn(ccx, i.span, sym, i.id, ty)
2341 foreign::register_rust_fn_with_foreign_abi(ccx,
2346 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2350 _ => fail!("get_item_val: weird result in table")
2353 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
2355 Some(sect) => unsafe {
2356 sect.get().with_c_str(|buf| {
2357 llvm::LLVMSetSection(v, buf);
2366 ast_map::NodeTraitMethod(trait_method) => {
2367 debug!("get_item_val(): processing a NodeTraitMethod");
2368 match *trait_method {
2369 ast::Required(_) => {
2370 ccx.sess().bug("unexpected variant: required trait method in \
2373 ast::Provided(m) => {
2374 register_method(ccx, id, &*m)
2379 ast_map::NodeMethod(m) => {
2380 register_method(ccx, id, &*m)
2383 ast_map::NodeForeignItem(ni) => {
2387 ast::ForeignItemFn(..) => {
2388 let abi = ccx.tcx.map.get_foreign_abi(id);
2389 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2390 let name = foreign::link_name(&*ni);
2391 foreign::register_foreign_item_fn(ccx, abi, ty,
2392 name.get().as_slice(),
2395 ast::ForeignItemStatic(..) => {
2396 foreign::register_static(ccx, &*ni)
2401 ast_map::NodeVariant(ref v) => {
2403 let args = match v.node.kind {
2404 ast::TupleVariantKind(ref args) => args,
2405 ast::StructVariantKind(_) => {
2406 fail!("struct variant kind unexpected in get_item_val")
2409 assert!(args.len() != 0u);
2410 let ty = ty::node_id_to_type(ccx.tcx(), id);
2411 let parent = ccx.tcx.map.get_parent(id);
2412 let enm = ccx.tcx.map.expect_item(parent);
2413 let sym = exported_name(ccx,
2416 enm.attrs.as_slice());
2418 llfn = match enm.node {
2419 ast::ItemEnum(_, _) => {
2420 register_fn(ccx, (*v).span, sym, id, ty)
2422 _ => fail!("NodeVariant, shouldn't happen")
2424 set_inline_hint(llfn);
2428 ast_map::NodeStructCtor(struct_def) => {
2429 // Only register the constructor if this is a tuple-like struct.
2430 let ctor_id = match struct_def.ctor_id {
2432 ccx.sess().bug("attempt to register a constructor of \
2433 a non-tuple-like struct")
2435 Some(ctor_id) => ctor_id,
2437 let parent = ccx.tcx.map.get_parent(id);
2438 let struct_item = ccx.tcx.map.expect_item(parent);
2439 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2440 let sym = exported_name(ccx,
2445 let llfn = register_fn(ccx, struct_item.span,
2447 set_inline_hint(llfn);
2452 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2453 variant).as_slice())
2457 // foreign items (extern fns and extern statics) don't have internal
2458 // linkage b/c that doesn't quite make sense. Otherwise items can
2459 // have internal linkage if they're not reachable.
2460 if !foreign && !ccx.reachable.contains(&id) {
2461 llvm::SetLinkage(val, llvm::InternalLinkage);
2464 ccx.item_vals.borrow_mut().insert(id, val);
2468 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2469 m: &ast::Method) -> ValueRef {
2470 let mty = ty::node_id_to_type(ccx.tcx(), id);
2472 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2474 let llfn = register_fn(ccx, m.span, sym, id, mty);
2475 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2479 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2481 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2485 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2486 -> encoder::EncodeParams<'r> {
2487 encoder::EncodeParams {
2488 diag: cx.sess().diagnostic(),
2490 reexports2: &cx.exp_map2,
2491 item_symbols: &cx.item_symbols,
2492 non_inlineable_statics: &cx.non_inlineable_statics,
2493 link_meta: &cx.link_meta,
2494 cstore: &cx.sess().cstore,
2495 encode_inlined_item: ie,
2496 reachable: &cx.reachable,
2500 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2503 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2504 *ty != config::CrateTypeExecutable
2510 let encode_inlined_item: encoder::EncodeInlinedItem =
2511 |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
2513 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2514 let metadata = encoder::encode_metadata(encode_parms, krate);
2515 let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2516 .append(match flate::deflate_bytes(metadata.as_slice()) {
2517 Some(compressed) => compressed,
2519 cx.sess().fatal("failed to compress metadata")
2522 let llmeta = C_bytes(cx, compressed.as_slice());
2523 let llconst = C_struct(cx, [llmeta], false);
2524 let name = format!("rust_metadata_{}_{}",
2525 cx.link_meta.crate_name,
2526 cx.link_meta.crate_hash);
2527 let llglobal = name.with_c_str(|buf| {
2529 llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2533 llvm::LLVMSetInitializer(llglobal, llconst);
2534 let name = loader::meta_section_name(cx.sess().targ_cfg.os);
2535 name.unwrap_or("rust_metadata").with_c_str(|buf| {
2536 llvm::LLVMSetSection(llglobal, buf)
2542 pub fn trans_crate(krate: ast::Crate,
2543 analysis: CrateAnalysis) -> (ty::ctxt, CrateTranslation) {
2544 let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, name, .. } = analysis;
2546 // Before we touch LLVM, make sure that multithreading is enabled.
2548 use std::sync::{Once, ONCE_INIT};
2549 static mut INIT: Once = ONCE_INIT;
2550 static mut POISONED: bool = false;
2552 if llvm::LLVMStartMultithreaded() != 1 {
2553 // use an extra bool to make sure that all future usage of LLVM
2554 // cannot proceed despite the Once not running more than once.
2560 tcx.sess.bug("couldn't enable multi-threaded LLVM");
2564 let link_meta = link::build_link_meta(&tcx.sess, &krate, name);
2566 // Append ".rs" to crate name as LLVM module identifier.
2568 // LLVM code generator emits a ".file filename" directive
2569 // for ELF backends. Value of the "filename" is set as the
2570 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2571 // crashes if the module identifier is same as other symbols
2572 // such as a function name in the module.
2573 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2574 let mut llmod_id = link_meta.crate_name.clone();
2575 llmod_id.push_str(".rs");
2577 let ccx = CrateContext::new(llmod_id.as_slice(), tcx, exp_map2,
2578 Sha256::new(), link_meta, reachable);
2580 // First, verify intrinsics.
2581 intrinsic::check_intrinsics(&ccx);
2583 // Next, translate the module.
2585 let _icx = push_ctxt("text");
2586 trans_mod(&ccx, &krate.module);
2589 glue::emit_tydescs(&ccx);
2590 if ccx.sess().opts.debuginfo != NoDebugInfo {
2591 debuginfo::finalize(&ccx);
2594 // Translate the metadata.
2595 let metadata = write_metadata(&ccx, &krate);
2596 if ccx.sess().trans_stats() {
2597 println!("--- trans stats ---");
2598 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2599 println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2600 println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2601 println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2603 println!("n_fns: {}", ccx.stats.n_fns.get());
2604 println!("n_monos: {}", ccx.stats.n_monos.get());
2605 println!("n_inlines: {}", ccx.stats.n_inlines.get());
2606 println!("n_closures: {}", ccx.stats.n_closures.get());
2607 println!("fn stats:");
2608 ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2609 insns_b.cmp(&insns_a)
2611 for tuple in ccx.stats.fn_stats.borrow().iter() {
2613 (ref name, ms, insns) => {
2614 println!("{} insns, {} ms, {}", insns, ms, *name);
2619 if ccx.sess().count_llvm_insns() {
2620 for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2621 println!("{:7u} {}", *v, *k);
2625 let llcx = ccx.llcx;
2626 let link_meta = ccx.link_meta.clone();
2627 let llmod = ccx.llmod;
2629 let mut reachable: Vec<String> = ccx.reachable.iter().filter_map(|id| {
2630 ccx.item_symbols.borrow().find(id).map(|s| s.to_string())
2633 // For the purposes of LTO, we add to the reachable set all of the upstream
2634 // reachable extern fns. These functions are all part of the public ABI of
2635 // the final product, so LTO needs to preserve them.
2636 ccx.sess().cstore.iter_crate_data(|cnum, _| {
2637 let syms = csearch::get_reachable_extern_fns(&ccx.sess().cstore, cnum);
2638 reachable.extend(syms.move_iter().map(|did| {
2639 csearch::get_symbol(&ccx.sess().cstore, did)
2643 // Make sure that some other crucial symbols are not eliminated from the
2644 // module. This includes the main function, the crate map (used for debug
2645 // log settings and I/O), and finally the curious rust_stack_exhausted
2646 // symbol. This symbol is required for use by the libmorestack library that
2647 // we link in, so we must ensure that this symbol is not internalized (if
2648 // defined in the crate).
2649 reachable.push("main".to_string());
2650 reachable.push("rust_stack_exhausted".to_string());
2652 // referenced from .eh_frame section on some platforms
2653 reachable.push("rust_eh_personality".to_string());
2654 // referenced from rt/rust_try.ll
2655 reachable.push("rust_eh_personality_catch".to_string());
2657 let metadata_module = ccx.metadata_llmod;
2658 let formats = ccx.tcx.dependency_formats.borrow().clone();
2659 let no_builtins = attr::contains_name(krate.attrs.as_slice(), "no_builtins");
2661 (ccx.tcx, CrateTranslation {
2665 metadata_module: metadata_module,
2667 reachable: reachable,
2668 crate_formats: formats,
2669 no_builtins: no_builtins,