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};
83 use syntax::abi::{X86, X86_64, Arm, Mips, Mipsel, Rust, RustCall};
84 use syntax::abi::{RustIntrinsic, Abi};
85 use syntax::ast_util::{local_def, is_local};
86 use syntax::attr::AttrMetaMethods;
88 use syntax::codemap::Span;
89 use syntax::parse::token::InternedString;
90 use syntax::visit::Visitor;
92 use syntax::{ast, ast_util, ast_map};
96 local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)
98 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
99 match task_local_insn_key.get() {
100 Some(ctx) => blk(ctx.borrow().as_slice()),
105 pub fn init_insn_ctxt() {
106 task_local_insn_key.replace(Some(RefCell::new(Vec::new())));
109 pub struct _InsnCtxt {
110 _cannot_construct_outside_of_this_module: ()
114 impl Drop for _InsnCtxt {
116 match task_local_insn_key.get() {
117 Some(ctx) => { ctx.borrow_mut().pop(); }
123 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
124 debug!("new InsnCtxt: {}", s);
125 match task_local_insn_key.get() {
126 Some(ctx) => ctx.borrow_mut().push(s),
129 _InsnCtxt { _cannot_construct_outside_of_this_module: () }
132 pub struct StatRecorder<'a> {
133 ccx: &'a CrateContext,
134 name: Option<String>,
139 impl<'a> StatRecorder<'a> {
140 pub fn new(ccx: &'a CrateContext, name: String) -> StatRecorder<'a> {
141 let start = if ccx.sess().trans_stats() {
142 time::precise_time_ns()
146 let istart = ccx.stats.n_llvm_insns.get();
157 impl<'a> Drop for StatRecorder<'a> {
159 if self.ccx.sess().trans_stats() {
160 let end = time::precise_time_ns();
161 let elapsed = ((end - self.start) / 1_000_000) as uint;
162 let iend = self.ccx.stats.n_llvm_insns.get();
163 self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
165 iend - self.istart));
166 self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
167 // Reset LLVM insn count to avoid compound costs.
168 self.ccx.stats.n_llvm_insns.set(self.istart);
173 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
174 fn decl_fn(ccx: &CrateContext, name: &str, cc: llvm::CallConv,
175 ty: Type, output: ty::t) -> ValueRef {
177 let llfn: ValueRef = name.with_c_str(|buf| {
179 llvm::LLVMGetOrInsertFunction(ccx.llmod, buf, ty.to_ref())
183 match ty::get(output).sty {
184 // functions returning bottom may unwind, but can never return normally
187 llvm::LLVMAddFunctionAttribute(llfn,
188 llvm::FunctionIndex as c_uint,
189 llvm::NoReturnAttribute as uint64_t)
195 if ccx.tcx.sess.opts.cg.no_redzone {
197 llvm::LLVMAddFunctionAttribute(llfn,
198 llvm::FunctionIndex as c_uint,
199 llvm::NoRedZoneAttribute as uint64_t)
203 llvm::SetFunctionCallConv(llfn, cc);
204 // Function addresses in Rust are never significant, allowing functions to be merged.
205 llvm::SetUnnamedAddr(llfn, true);
207 if ccx.is_split_stack_supported() {
208 set_split_stack(llfn);
214 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
215 pub fn decl_cdecl_fn(ccx: &CrateContext,
218 output: ty::t) -> ValueRef {
219 decl_fn(ccx, name, llvm::CCallConv, ty, output)
222 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
223 pub fn get_extern_fn(ccx: &CrateContext,
224 externs: &mut ExternMap,
230 match externs.find_equiv(&name) {
231 Some(n) => return *n,
234 let f = decl_fn(ccx, name, cc, ty, output);
235 externs.insert(name.to_string(), f);
239 fn get_extern_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str, did: ast::DefId) -> ValueRef {
240 match ccx.externs.borrow().find_equiv(&name) {
241 Some(n) => return *n,
245 let f = decl_rust_fn(ccx, fn_ty, name);
247 csearch::get_item_attrs(&ccx.sess().cstore, did, |attrs| {
248 set_llvm_fn_attrs(attrs.as_slice(), f)
251 ccx.externs.borrow_mut().insert(name.to_string(), f);
255 pub fn decl_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
256 let (inputs, output, abi, env) = match ty::get(fn_ty).sty {
257 ty::ty_bare_fn(ref f) => {
258 (f.sig.inputs.clone(), f.sig.output, f.abi, None)
260 ty::ty_closure(ref f) => {
261 (f.sig.inputs.clone(), f.sig.output, f.abi, Some(Type::i8p(ccx)))
263 ty::ty_unboxed_closure(closure_did) => {
264 let unboxed_closure_types = ccx.tcx
265 .unboxed_closure_types
267 let function_type = unboxed_closure_types.get(&closure_did);
268 let llenvironment_type = type_of(ccx, fn_ty).ptr_to();
269 (function_type.sig.inputs.clone(),
270 function_type.sig.output,
272 Some(llenvironment_type))
274 _ => fail!("expected closure or fn")
277 let llfty = type_of_rust_fn(ccx, env, inputs.as_slice(), output, abi);
278 debug!("decl_rust_fn(input count={},type={})",
280 ccx.tn.type_to_string(llfty));
282 let llfn = decl_fn(ccx, name, llvm::CCallConv, llfty, output);
283 let attrs = get_fn_llvm_attributes(ccx, fn_ty);
284 for &(idx, attr) in attrs.iter() {
286 llvm::LLVMAddFunctionAttribute(llfn, idx as c_uint, attr);
293 pub fn decl_internal_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
294 let llfn = decl_rust_fn(ccx, fn_ty, name);
295 llvm::SetLinkage(llfn, llvm::InternalLinkage);
299 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
300 name: &str, ty: Type) -> ValueRef {
301 match externs.find_equiv(&name) {
302 Some(n) => return *n,
306 let c = name.with_c_str(|buf| {
307 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
309 externs.insert(name.to_string(), c);
314 // Returns a pointer to the body for the box. The box may be an opaque
315 // box. The result will be casted to the type of body_t, if it is statically
317 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
318 let _icx = push_ctxt("at_box_body");
320 let ty = Type::at_box(ccx, type_of(ccx, body_t));
321 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
322 GEPi(bcx, boxptr, [0u, abi::box_field_body])
325 fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
326 match bcx.tcx().lang_items.require(it) {
329 bcx.sess().fatal(format!("allocation of `{}` {}",
330 bcx.ty_to_string(info_ty),
336 // The following malloc_raw_dyn* functions allocate a box to contain
337 // a given type, but with a potentially dynamic size.
339 pub fn malloc_raw_dyn<'a>(bcx: &'a Block<'a>,
344 let _icx = push_ctxt("malloc_raw_exchange");
348 let r = callee::trans_lang_call(bcx,
349 require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
353 let llty_ptr = type_of::type_of(ccx, ptr_ty);
354 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
357 pub fn malloc_raw_dyn_managed<'a>(
363 let _icx = push_ctxt("malloc_raw_managed");
366 let langcall = require_alloc_fn(bcx, t, alloc_fn);
368 // Grab the TypeRef type of box_ptr_ty.
369 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
370 let llty = type_of(ccx, box_ptr_ty);
371 let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
374 let drop_glue = glue::get_drop_glue(ccx, t);
375 let r = callee::trans_lang_call(
379 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
384 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
387 // Type descriptor and type glue stuff
389 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
390 match ccx.tydescs.borrow().find(&t) {
391 Some(inf) => return inf.clone(),
395 ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
396 let inf = Rc::new(glue::declare_tydesc(ccx, t));
398 ccx.tydescs.borrow_mut().insert(t, inf.clone());
402 #[allow(dead_code)] // useful
403 pub fn set_optimize_for_size(f: ValueRef) {
404 llvm::SetFunctionAttribute(f, llvm::OptimizeForSizeAttribute)
407 pub fn set_no_inline(f: ValueRef) {
408 llvm::SetFunctionAttribute(f, llvm::NoInlineAttribute)
411 #[allow(dead_code)] // useful
412 pub fn set_no_unwind(f: ValueRef) {
413 llvm::SetFunctionAttribute(f, llvm::NoUnwindAttribute)
416 // Tell LLVM to emit the information necessary to unwind the stack for the
418 pub fn set_uwtable(f: ValueRef) {
419 llvm::SetFunctionAttribute(f, llvm::UWTableAttribute)
422 pub fn set_inline_hint(f: ValueRef) {
423 llvm::SetFunctionAttribute(f, llvm::InlineHintAttribute)
426 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
428 // Set the inline hint if there is one
429 match find_inline_attr(attrs) {
430 InlineHint => set_inline_hint(llfn),
431 InlineAlways => set_always_inline(llfn),
432 InlineNever => set_no_inline(llfn),
433 InlineNone => { /* fallthrough */ }
436 // Add the no-split-stack attribute if requested
437 if contains_name(attrs, "no_split_stack") {
438 unset_split_stack(llfn);
441 if contains_name(attrs, "cold") {
443 llvm::LLVMAddFunctionAttribute(llfn,
444 llvm::FunctionIndex as c_uint,
445 llvm::ColdAttribute as uint64_t)
450 pub fn set_always_inline(f: ValueRef) {
451 llvm::SetFunctionAttribute(f, llvm::AlwaysInlineAttribute)
454 pub fn set_split_stack(f: ValueRef) {
455 "split-stack".with_c_str(|buf| {
456 unsafe { llvm::LLVMAddFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
460 pub fn unset_split_stack(f: ValueRef) {
461 "split-stack".with_c_str(|buf| {
462 unsafe { llvm::LLVMRemoveFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
466 // Double-check that we never ask LLVM to declare the same symbol twice. It
467 // silently mangles such symbols, breaking our linkage model.
468 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) {
469 if ccx.all_llvm_symbols.borrow().contains(&sym) {
470 ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).as_slice());
472 ccx.all_llvm_symbols.borrow_mut().insert(sym);
476 pub fn get_res_dtor(ccx: &CrateContext,
479 parent_id: ast::DefId,
480 substs: &subst::Substs)
482 let _icx = push_ctxt("trans_res_dtor");
483 let did = if did.krate != ast::LOCAL_CRATE {
484 inline::maybe_instantiate_inline(ccx, did)
489 if !substs.types.is_empty() {
490 assert_eq!(did.krate, ast::LOCAL_CRATE);
492 let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, substs);
493 let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, vtables, None);
496 } else if did.krate == ast::LOCAL_CRATE {
497 get_item_val(ccx, did.node)
500 let name = csearch::get_symbol(&ccx.sess().cstore, did);
501 let class_ty = ty::lookup_item_type(tcx, parent_id).ty.subst(tcx, substs);
502 let llty = type_of_dtor(ccx, class_ty);
503 let dtor_ty = ty::mk_ctor_fn(ccx.tcx(), ast::DUMMY_NODE_ID,
504 [glue::get_drop_glue_type(ccx, t)], ty::mk_nil());
506 &mut *ccx.externs.borrow_mut(),
514 // Structural comparison: a rather involved form of glue.
515 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
516 if cx.sess().opts.cg.save_temps {
519 llvm::LLVMSetValueName(v, buf)
526 // Used only for creating scalar comparison glue.
527 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
529 pub fn compare_scalar_types<'a>(
536 let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
538 match ty::get(t).sty {
539 ty::ty_nil => f(nil_type),
540 ty::ty_bool | ty::ty_ptr(_) |
541 ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
542 ty::ty_int(_) => f(signed_int),
543 ty::ty_float(_) => f(floating_point),
544 // Should never get here, because t is scalar.
545 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
550 // A helper function to do the actual comparison of scalar values.
551 pub fn compare_scalar_values<'a>(
558 let _icx = push_ctxt("compare_scalar_values");
559 fn die(cx: &Block) -> ! {
560 cx.sess().bug("compare_scalar_values: must be a comparison operator");
564 // We don't need to do actual comparisons for nil.
565 // () == () holds but () < () does not.
567 ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(cx.ccx(), true),
568 ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(cx.ccx(), false),
569 // refinements would be nice
575 ast::BiEq => llvm::RealOEQ,
576 ast::BiNe => llvm::RealUNE,
577 ast::BiLt => llvm::RealOLT,
578 ast::BiLe => llvm::RealOLE,
579 ast::BiGt => llvm::RealOGT,
580 ast::BiGe => llvm::RealOGE,
583 return FCmp(cx, cmp, lhs, rhs);
587 ast::BiEq => llvm::IntEQ,
588 ast::BiNe => llvm::IntNE,
589 ast::BiLt => llvm::IntSLT,
590 ast::BiLe => llvm::IntSLE,
591 ast::BiGt => llvm::IntSGT,
592 ast::BiGe => llvm::IntSGE,
595 return ICmp(cx, cmp, lhs, rhs);
599 ast::BiEq => llvm::IntEQ,
600 ast::BiNe => llvm::IntNE,
601 ast::BiLt => llvm::IntULT,
602 ast::BiLe => llvm::IntULE,
603 ast::BiGt => llvm::IntUGT,
604 ast::BiGe => llvm::IntUGE,
607 return ICmp(cx, cmp, lhs, rhs);
612 pub fn compare_simd_types(
620 match ty::get(t).sty {
622 // The comparison operators for floating point vectors are challenging.
623 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
624 // then bitcast to a floating point vector, the result will be `-NaN`
625 // for each truth value. Because of this they are unsupported.
626 cx.sess().bug("compare_simd_types: comparison operators \
627 not supported for floating point SIMD types")
629 ty::ty_uint(_) | ty::ty_int(_) => {
631 ast::BiEq => llvm::IntEQ,
632 ast::BiNe => llvm::IntNE,
633 ast::BiLt => llvm::IntSLT,
634 ast::BiLe => llvm::IntSLE,
635 ast::BiGt => llvm::IntSGT,
636 ast::BiGe => llvm::IntSGE,
637 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
639 let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
640 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
641 // to get the correctly sized type. This will compile to a single instruction
642 // once the IR is converted to assembly if the SIMD instruction is supported
643 // by the target architecture.
644 SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
646 _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
650 pub type val_and_ty_fn<'r,'b> =
651 |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
653 // Iterates through the elements of a structural type.
654 pub fn iter_structural_ty<'r,
659 f: val_and_ty_fn<'r,'b>)
661 let _icx = push_ctxt("iter_structural_ty");
668 variant: &ty::VariantInfo,
669 substs: &subst::Substs,
670 f: val_and_ty_fn<'r,'b>)
672 let _icx = push_ctxt("iter_variant");
676 for (i, &arg) in variant.args.iter().enumerate() {
678 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
679 arg.subst(tcx, substs));
685 match ty::get(t).sty {
686 ty::ty_struct(..) => {
687 let repr = adt::represent_type(cx.ccx(), t);
688 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
689 for (i, field_ty) in field_tys.iter().enumerate() {
690 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, discr, i);
691 cx = f(cx, llfld_a, field_ty.mt.ty);
695 ty::ty_unboxed_closure(def_id) => {
696 let repr = adt::represent_type(cx.ccx(), t);
697 let upvars = ty::unboxed_closure_upvars(cx.tcx(), def_id);
698 for (i, upvar) in upvars.iter().enumerate() {
699 let llupvar = adt::trans_field_ptr(cx, &*repr, av, 0, i);
700 cx = f(cx, llupvar, upvar.ty);
703 ty::ty_vec(_, Some(n)) => {
704 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
705 let (base, len) = tvec::get_fixed_base_and_byte_len(cx, av, unit_ty, n);
706 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
708 ty::ty_tup(ref args) => {
709 let repr = adt::represent_type(cx.ccx(), t);
710 for (i, arg) in args.iter().enumerate() {
711 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, 0, i);
712 cx = f(cx, llfld_a, *arg);
715 ty::ty_enum(tid, ref substs) => {
719 let repr = adt::represent_type(ccx, t);
720 let variants = ty::enum_variants(ccx.tcx(), tid);
721 let n_variants = (*variants).len();
723 // NB: we must hit the discriminant first so that structural
724 // comparison know not to proceed when the discriminants differ.
726 match adt::trans_switch(cx, &*repr, av) {
727 (_match::single, None) => {
728 cx = iter_variant(cx, &*repr, av, &**variants.get(0),
731 (_match::switch, Some(lldiscrim_a)) => {
732 cx = f(cx, lldiscrim_a, ty::mk_int());
733 let unr_cx = fcx.new_temp_block("enum-iter-unr");
735 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
737 let next_cx = fcx.new_temp_block("enum-iter-next");
739 for variant in (*variants).iter() {
742 format!("enum-iter-variant-{}",
743 variant.disr_val.to_string().as_slice())
745 match adt::trans_case(cx, &*repr, variant.disr_val) {
746 _match::single_result(r) => {
747 AddCase(llswitch, r.val, variant_cx.llbb)
749 _ => ccx.sess().unimpl("value from adt::trans_case \
750 in iter_structural_ty")
753 iter_variant(variant_cx,
759 Br(variant_cx, next_cx.llbb);
763 _ => ccx.sess().unimpl("value from adt::trans_switch \
764 in iter_structural_ty")
767 _ => cx.sess().unimpl("type in iter_structural_ty")
772 pub fn cast_shift_expr_rhs<'a>(
778 cast_shift_rhs(op, lhs, rhs,
779 |a,b| Trunc(cx, a, b),
780 |a,b| ZExt(cx, a, b))
783 pub fn cast_shift_const_rhs(op: ast::BinOp,
784 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
785 cast_shift_rhs(op, lhs, rhs,
786 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
787 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
790 pub fn cast_shift_rhs(op: ast::BinOp,
793 trunc: |ValueRef, Type| -> ValueRef,
794 zext: |ValueRef, Type| -> ValueRef)
796 // Shifts may have any size int on the rhs
798 if ast_util::is_shift_binop(op) {
799 let mut rhs_llty = val_ty(rhs);
800 let mut lhs_llty = val_ty(lhs);
801 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
802 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
803 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
804 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
807 } else if lhs_sz > rhs_sz {
808 // FIXME (#1877: If shifting by negative
809 // values becomes not undefined then this is wrong.
820 pub fn fail_if_zero_or_overflows<'a>(
828 let (zero_text, overflow_text) = if divrem == ast::BiDiv {
829 ("attempted to divide by zero",
830 "attempted to divide with overflow")
832 ("attempted remainder with a divisor of zero",
833 "attempted remainder with overflow")
835 let (is_zero, is_signed) = match ty::get(rhs_t).sty {
837 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
838 (ICmp(cx, llvm::IntEQ, rhs, zero), true)
841 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
842 (ICmp(cx, llvm::IntEQ, rhs, zero), false)
845 cx.sess().bug(format!("fail-if-zero on unexpected type: {}",
846 ty_to_string(cx.tcx(), rhs_t)).as_slice());
849 let bcx = with_cond(cx, is_zero, |bcx| {
850 controlflow::trans_fail(bcx, span, InternedString::new(zero_text))
853 // To quote LLVM's documentation for the sdiv instruction:
855 // Division by zero leads to undefined behavior. Overflow also leads
856 // to undefined behavior; this is a rare case, but can occur, for
857 // example, by doing a 32-bit division of -2147483648 by -1.
859 // In order to avoid undefined behavior, we perform runtime checks for
860 // signed division/remainder which would trigger overflow. For unsigned
861 // integers, no action beyond checking for zero need be taken.
863 let (llty, min) = match ty::get(rhs_t).sty {
865 let llty = Type::int_from_ty(cx.ccx(), t);
867 ast::TyI if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
868 ast::TyI => i64::MIN as u64,
869 ast::TyI8 => i8::MIN as u64,
870 ast::TyI16 => i16::MIN as u64,
871 ast::TyI32 => i32::MIN as u64,
872 ast::TyI64 => i64::MIN as u64,
878 let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
879 C_integral(llty, -1, false));
880 with_cond(bcx, minus_one, |bcx| {
881 let is_min = ICmp(bcx, llvm::IntEQ, lhs,
882 C_integral(llty, min, true));
883 with_cond(bcx, is_min, |bcx| {
884 controlflow::trans_fail(bcx, span,
885 InternedString::new(overflow_text))
893 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
894 let name = csearch::get_symbol(&ccx.sess().cstore, did);
895 match ty::get(t).sty {
896 ty::ty_bare_fn(ref fn_ty) => {
897 match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
898 ccx.sess().targ_cfg.arch) {
899 Some(Rust) | Some(RustCall) => {
900 get_extern_rust_fn(ccx, t, name.as_slice(), did)
902 Some(RustIntrinsic) => {
903 ccx.sess().bug("unexpected intrinsic in trans_external_path")
906 foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
907 name.as_slice(), None)
911 ty::ty_closure(_) => {
912 get_extern_rust_fn(ccx, t, name.as_slice(), did)
915 let llty = type_of(ccx, t);
916 get_extern_const(&mut *ccx.externs.borrow_mut(),
927 llargs: Vec<ValueRef> ,
929 call_info: Option<NodeInfo>)
930 -> (ValueRef, &'a Block<'a>) {
931 let _icx = push_ctxt("invoke_");
932 if bcx.unreachable.get() {
933 return (C_null(Type::i8(bcx.ccx())), bcx);
936 let attributes = get_fn_llvm_attributes(bcx.ccx(), fn_ty);
938 match bcx.opt_node_id {
940 debug!("invoke at ???");
943 debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
947 if need_invoke(bcx) {
948 debug!("invoking {} at {}", llfn, bcx.llbb);
949 for &llarg in llargs.iter() {
950 debug!("arg: {}", llarg);
952 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
953 let landing_pad = bcx.fcx.get_landing_pad();
956 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
957 None => debuginfo::clear_source_location(bcx.fcx)
960 let llresult = Invoke(bcx,
965 attributes.as_slice());
966 return (llresult, normal_bcx);
968 debug!("calling {} at {}", llfn, bcx.llbb);
969 for &llarg in llargs.iter() {
970 debug!("arg: {}", llarg);
974 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
975 None => debuginfo::clear_source_location(bcx.fcx)
978 let llresult = Call(bcx, llfn, llargs.as_slice(), attributes.as_slice());
979 return (llresult, bcx);
983 pub fn need_invoke(bcx: &Block) -> bool {
984 if bcx.sess().no_landing_pads() {
988 // Avoid using invoke if we are already inside a landing pad.
993 bcx.fcx.needs_invoke()
996 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
997 let _icx = push_ctxt("load_if_immediate");
998 if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
1002 pub fn load_ty(cx: &Block, ptr: ValueRef, t: ty::t) -> ValueRef {
1004 * Helper for loading values from memory. Does the necessary conversion if
1005 * the in-memory type differs from the type used for SSA values. Also
1006 * handles various special cases where the type gives us better information
1007 * about what we are loading.
1009 if type_is_zero_size(cx.ccx(), t) {
1010 C_undef(type_of::type_of(cx.ccx(), t))
1011 } else if ty::type_is_bool(t) {
1012 Trunc(cx, LoadRangeAssert(cx, ptr, 0, 2, llvm::False), Type::i1(cx.ccx()))
1013 } else if ty::type_is_char(t) {
1014 // a char is a unicode codepoint, and so takes values from 0
1015 // to 0x10FFFF inclusive only.
1016 LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
1022 pub fn store_ty(cx: &Block, v: ValueRef, dst: ValueRef, t: ty::t) {
1024 * Helper for storing values in memory. Does the necessary conversion if
1025 * the in-memory type differs from the type used for SSA values.
1027 if ty::type_is_bool(t) {
1028 Store(cx, ZExt(cx, v, Type::i8(cx.ccx())), dst);
1034 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
1035 match local.pat.node {
1036 ast::PatWild => true, _ => false
1040 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
1042 debug!("init_local(bcx={}, local.id={:?})", bcx.to_str(), local.id);
1043 let _indenter = indenter();
1044 let _icx = push_ctxt("init_local");
1045 _match::store_local(bcx, local)
1048 pub fn raw_block<'a>(
1049 fcx: &'a FunctionContext<'a>,
1051 llbb: BasicBlockRef)
1053 Block::new(llbb, is_lpad, None, fcx)
1056 pub fn with_cond<'a>(
1059 f: |&'a Block<'a>| -> &'a Block<'a>)
1061 let _icx = push_ctxt("with_cond");
1063 let next_cx = fcx.new_temp_block("next");
1064 let cond_cx = fcx.new_temp_block("cond");
1065 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1066 let after_cx = f(cond_cx);
1067 if !after_cx.terminated.get() {
1068 Br(after_cx, next_cx.llbb);
1073 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1074 let _icx = push_ctxt("call_memcpy");
1076 let key = match ccx.sess().targ_cfg.arch {
1077 X86 | Arm | Mips | Mipsel => "llvm.memcpy.p0i8.p0i8.i32",
1078 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1080 let memcpy = ccx.get_intrinsic(&key);
1081 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1082 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1083 let size = IntCast(cx, n_bytes, ccx.int_type);
1084 let align = C_i32(ccx, align as i32);
1085 let volatile = C_bool(ccx, false);
1086 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1089 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1090 let _icx = push_ctxt("memcpy_ty");
1091 let ccx = bcx.ccx();
1092 if ty::type_is_structural(t) {
1093 let llty = type_of::type_of(ccx, t);
1094 let llsz = llsize_of(ccx, llty);
1095 let llalign = llalign_of_min(ccx, llty);
1096 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1098 Store(bcx, Load(bcx, src), dst);
1102 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1103 if cx.unreachable.get() { return; }
1104 let _icx = push_ctxt("zero_mem");
1107 let llty = type_of::type_of(ccx, t);
1108 memzero(&B(bcx), llptr, llty);
1111 // Always use this function instead of storing a zero constant to the memory
1112 // in question. If you store a zero constant, LLVM will drown in vreg
1113 // allocation for large data structures, and the generated code will be
1114 // awful. (A telltale sign of this is large quantities of
1115 // `mov [byte ptr foo],0` in the generated code.)
1116 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1117 let _icx = push_ctxt("memzero");
1120 let intrinsic_key = match ccx.sess().targ_cfg.arch {
1121 X86 | Arm | Mips | Mipsel => "llvm.memset.p0i8.i32",
1122 X86_64 => "llvm.memset.p0i8.i64"
1125 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1126 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1127 let llzeroval = C_u8(ccx, 0);
1128 let size = machine::llsize_of(ccx, ty);
1129 let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1130 let volatile = C_bool(ccx, false);
1131 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1134 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1135 let _icx = push_ctxt("alloc_ty");
1136 let ccx = bcx.ccx();
1137 let ty = type_of::type_of(ccx, t);
1138 assert!(!ty::type_has_params(t));
1139 let val = alloca(bcx, ty, name);
1143 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1144 alloca_maybe_zeroed(cx, ty, name, false)
1147 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1148 let _icx = push_ctxt("alloca");
1149 if cx.unreachable.get() {
1151 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1154 debuginfo::clear_source_location(cx.fcx);
1155 let p = Alloca(cx, ty, name);
1157 let b = cx.fcx.ccx.builder();
1158 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1164 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1165 let _icx = push_ctxt("arrayalloca");
1166 if cx.unreachable.get() {
1168 return llvm::LLVMGetUndef(ty.to_ref());
1171 debuginfo::clear_source_location(cx.fcx);
1172 return ArrayAlloca(cx, ty, v);
1175 // Creates and returns space for, or returns the argument representing, the
1176 // slot where the return value of the function must go.
1177 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1179 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1180 get_param(fcx.llfn, 0)
1182 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1183 AllocaFcx(fcx, lloutputtype, "__make_return_pointer")
1187 // NB: must keep 4 fns in sync:
1190 // - create_datums_for_fn_args.
1194 // Be warned! You must call `init_function` before doing anything with the
1195 // returned function context.
1196 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1201 param_substs: &'a param_substs,
1203 block_arena: &'a TypedArena<Block<'a>>)
1204 -> FunctionContext<'a> {
1205 param_substs.validate();
1207 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1211 ccx.tcx.map.path_to_string(id).to_string()
1213 id, param_substs.repr(ccx.tcx()));
1215 let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1216 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1217 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1219 let mut fcx = FunctionContext {
1222 llretptr: Cell::new(None),
1223 alloca_insert_pt: Cell::new(None),
1224 llreturn: Cell::new(None),
1225 personality: Cell::new(None),
1226 caller_expects_out_pointer: uses_outptr,
1227 llargs: RefCell::new(NodeMap::new()),
1228 lllocals: RefCell::new(NodeMap::new()),
1229 llupvars: RefCell::new(NodeMap::new()),
1231 param_substs: param_substs,
1233 block_arena: block_arena,
1235 debug_context: debug_context,
1236 scopes: RefCell::new(Vec::new())
1240 fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1246 /// Performs setup on a newly created function, creating the entry scope block
1247 /// and allocating space for the return pointer.
1248 pub fn init_function<'a>(fcx: &'a FunctionContext<'a>,
1250 output_type: ty::t) -> &'a Block<'a> {
1251 let entry_bcx = fcx.new_temp_block("entry-block");
1253 // Use a dummy instruction as the insertion point for all allocas.
1254 // This is later removed in FunctionContext::cleanup.
1255 fcx.alloca_insert_pt.set(Some(unsafe {
1256 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1257 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1260 // This shouldn't need to recompute the return type,
1261 // as new_fn_ctxt did it already.
1262 let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1264 if !return_type_is_void(fcx.ccx, substd_output_type) {
1265 // If the function returns nil/bot, there is no real return
1266 // value, so do not set `llretptr`.
1267 if !skip_retptr || fcx.caller_expects_out_pointer {
1268 // Otherwise, we normally allocate the llretptr, unless we
1269 // have been instructed to skip it for immediate return
1271 fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1278 // NB: must keep 4 fns in sync:
1281 // - create_datums_for_fn_args.
1285 pub fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1286 use middle::trans::datum::{ByRef, ByValue};
1289 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1293 // work around bizarre resolve errors
1294 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1295 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1297 // create_datums_for_fn_args: creates rvalue datums for each of the
1298 // incoming function arguments. These will later be stored into
1299 // appropriate lvalue datums.
1300 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1302 -> Vec<RvalueDatum> {
1303 let _icx = push_ctxt("create_datums_for_fn_args");
1305 // Return an array wrapping the ValueRefs that we get from `get_param` for
1306 // each argument into datums.
1307 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1308 let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1309 datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1313 /// Creates rvalue datums for each of the incoming function arguments and
1314 /// tuples the arguments. These will later be stored into appropriate lvalue
1316 fn create_datums_for_fn_args_under_call_abi<
1318 mut bcx: &'a Block<'a>,
1319 arg_scope: cleanup::CustomScopeIndex,
1321 -> Vec<RvalueDatum> {
1322 let mut result = Vec::new();
1323 for (i, &arg_ty) in arg_tys.iter().enumerate() {
1324 if i < arg_tys.len() - 1 {
1325 // Regular argument.
1326 let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1327 result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1332 // This is the last argument. Tuple it.
1333 match ty::get(arg_ty).sty {
1334 ty::ty_tup(ref tupled_arg_tys) => {
1335 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1338 datum::lvalue_scratch_datum(bcx,
1342 tuple_args_scope_id,
1347 for (j, &tupled_arg_ty) in
1348 tupled_arg_tys.iter().enumerate() {
1350 get_param(bcx.fcx.llfn,
1351 bcx.fcx.arg_pos(i + j) as c_uint);
1352 let lldest = GEPi(bcx, llval, [0, j]);
1353 let datum = datum::Datum::new(
1356 arg_kind(bcx.fcx, tupled_arg_ty));
1357 bcx = datum.store_to(bcx, lldest);
1361 let tuple = unpack_datum!(bcx,
1362 tuple.to_expr_datum()
1363 .to_rvalue_datum(bcx,
1368 let mode = datum::Rvalue::new(datum::ByValue);
1369 result.push(datum::Datum::new(C_nil(bcx.ccx()),
1374 bcx.tcx().sess.bug("last argument of a function with \
1375 `rust-call` ABI isn't a tuple?!")
1384 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1385 arg_scope: cleanup::CustomScopeIndex,
1388 arg_datums: Vec<RvalueDatum> )
1390 debug!("copy_args_to_allocas");
1392 let _icx = push_ctxt("copy_args_to_allocas");
1395 let arg_scope_id = cleanup::CustomScope(arg_scope);
1397 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1398 // For certain mode/type combinations, the raw llarg values are passed
1399 // by value. However, within the fn body itself, we want to always
1400 // have all locals and arguments be by-ref so that we can cancel the
1401 // cleanup and for better interaction with LLVM's debug info. So, if
1402 // the argument would be passed by value, we store it into an alloca.
1403 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1404 // the event it's not truly needed.
1406 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1408 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1409 debuginfo::create_argument_metadata(bcx, &args[i]);
1416 fn copy_unboxed_closure_args_to_allocas<'a>(
1417 mut bcx: &'a Block<'a>,
1418 arg_scope: cleanup::CustomScopeIndex,
1420 arg_datums: Vec<RvalueDatum>,
1421 monomorphized_arg_types: &[ty::t])
1423 let _icx = push_ctxt("copy_unboxed_closure_args_to_allocas");
1424 let arg_scope_id = cleanup::CustomScope(arg_scope);
1426 assert_eq!(arg_datums.len(), 1);
1428 let arg_datum = arg_datums.move_iter().next().unwrap();
1430 // Untuple the rest of the arguments.
1433 arg_datum.to_lvalue_datum_in_scope(bcx,
1436 let empty = Vec::new();
1437 let untupled_arg_types = match ty::get(monomorphized_arg_types[0]).sty {
1438 ty::ty_tup(ref types) => types.as_slice(),
1439 ty::ty_nil => empty.as_slice(),
1441 bcx.tcx().sess.span_bug(args[0].pat.span,
1442 "first arg to `rust-call` ABI function \
1446 for j in range(0, args.len()) {
1447 let tuple_element_type = untupled_arg_types[j];
1448 let tuple_element_datum =
1449 tuple_datum.get_element(tuple_element_type,
1450 |llval| GEPi(bcx, llval, [0, j]));
1451 let tuple_element_datum = tuple_element_datum.to_expr_datum();
1452 let tuple_element_datum =
1454 tuple_element_datum.to_rvalue_datum(bcx,
1456 bcx = _match::store_arg(bcx,
1458 tuple_element_datum,
1461 if bcx.fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1462 debuginfo::create_argument_metadata(bcx, &args[j]);
1469 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1470 // and builds the return block.
1471 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1472 last_bcx: &'a Block<'a>,
1474 let _icx = push_ctxt("finish_fn");
1476 // This shouldn't need to recompute the return type,
1477 // as new_fn_ctxt did it already.
1478 let substd_retty = retty.substp(fcx.ccx.tcx(), fcx.param_substs);
1480 let ret_cx = match fcx.llreturn.get() {
1482 if !last_bcx.terminated.get() {
1483 Br(last_bcx, llreturn);
1485 raw_block(fcx, false, llreturn)
1489 build_return_block(fcx, ret_cx, substd_retty);
1490 debuginfo::clear_source_location(fcx);
1494 // Builds the return block for a function.
1495 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block, retty: ty::t) {
1496 // Return the value if this function immediate; otherwise, return void.
1497 if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1498 return RetVoid(ret_cx);
1501 let retptr = Value(fcx.llretptr.get().unwrap());
1502 let retval = match retptr.get_dominating_store(ret_cx) {
1503 // If there's only a single store to the ret slot, we can directly return
1504 // the value that was stored and omit the store and the alloca
1506 let retval = s.get_operand(0).unwrap().get();
1507 s.erase_from_parent();
1509 if retptr.has_no_uses() {
1510 retptr.erase_from_parent();
1513 if ty::type_is_bool(retty) {
1514 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1519 // Otherwise, load the return value from the ret slot
1520 None => load_ty(ret_cx, fcx.llretptr.get().unwrap(), retty)
1523 Ret(ret_cx, retval);
1526 #[deriving(Clone, Eq, PartialEq)]
1527 pub enum IsUnboxedClosureFlag {
1532 // trans_closure: Builds an LLVM function out of a source function.
1533 // If the function closes over its environment a closure will be
1535 pub fn trans_closure(ccx: &CrateContext,
1539 param_substs: ¶m_substs,
1541 _attributes: &[ast::Attribute],
1542 arg_types: Vec<ty::t>,
1546 is_unboxed_closure: IsUnboxedClosureFlag,
1547 maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1548 ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1550 let _icx = push_ctxt("trans_closure");
1551 set_uwtable(llfndecl);
1553 debug!("trans_closure(..., param_substs={})",
1554 param_substs.repr(ccx.tcx()));
1556 let arena = TypedArena::new();
1557 let fcx = new_fn_ctxt(ccx,
1565 let mut bcx = init_function(&fcx, false, output_type);
1567 // cleanup scope for the incoming arguments
1568 let arg_scope = fcx.push_custom_cleanup_scope();
1570 let block_ty = node_id_type(bcx, body.id);
1572 // Set up arguments to the function.
1573 let monomorphized_arg_types =
1575 .map(|at| monomorphize_type(bcx, *at))
1576 .collect::<Vec<_>>();
1577 for monomorphized_arg_type in monomorphized_arg_types.iter() {
1578 debug!("trans_closure: monomorphized_arg_type: {}",
1579 ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1581 debug!("trans_closure: function lltype: {}",
1582 bcx.fcx.ccx.tn.val_to_string(bcx.fcx.llfn));
1584 let arg_datums = if abi != RustCall {
1585 create_datums_for_fn_args(&fcx,
1586 monomorphized_arg_types.as_slice())
1588 create_datums_for_fn_args_under_call_abi(
1591 monomorphized_arg_types.as_slice())
1594 bcx = match is_unboxed_closure {
1595 NotUnboxedClosure => {
1596 copy_args_to_allocas(&fcx,
1599 decl.inputs.as_slice(),
1602 IsUnboxedClosure => {
1603 copy_unboxed_closure_args_to_allocas(
1606 decl.inputs.as_slice(),
1608 monomorphized_arg_types.as_slice())
1612 bcx = maybe_load_env(bcx);
1614 // Up until here, IR instructions for this function have explicitly not been annotated with
1615 // source code location, so we don't step into call setup code. From here on, source location
1616 // emitting should be enabled.
1617 debuginfo::start_emitting_source_locations(&fcx);
1619 let dest = match fcx.llretptr.get() {
1620 Some(e) => {expr::SaveIn(e)}
1622 assert!(type_is_zero_size(bcx.ccx(), block_ty))
1627 // This call to trans_block is the place where we bridge between
1628 // translation calls that don't have a return value (trans_crate,
1629 // trans_mod, trans_item, et cetera) and those that do
1630 // (trans_block, trans_expr, et cetera).
1631 bcx = controlflow::trans_block(bcx, body, dest);
1633 match fcx.llreturn.get() {
1635 Br(bcx, fcx.return_exit_block());
1636 fcx.pop_custom_cleanup_scope(arg_scope);
1639 // Microoptimization writ large: avoid creating a separate
1640 // llreturn basic block
1641 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1645 // Put return block after all other blocks.
1646 // This somewhat improves single-stepping experience in debugger.
1648 let llreturn = fcx.llreturn.get();
1649 for &llreturn in llreturn.iter() {
1650 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1654 // Insert the mandatory first few basic blocks before lltop.
1655 finish_fn(&fcx, bcx, output_type);
1658 // trans_fn: creates an LLVM function corresponding to a source language
1660 pub fn trans_fn(ccx: &CrateContext,
1664 param_substs: ¶m_substs,
1666 attrs: &[ast::Attribute]) {
1667 let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_string(id).to_string());
1668 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1669 let _icx = push_ctxt("trans_fn");
1670 let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1671 let arg_types = ty::ty_fn_args(fn_ty);
1672 let output_type = ty::ty_fn_ret(fn_ty);
1673 let abi = ty::ty_fn_abi(fn_ty);
1689 pub fn trans_enum_variant(ccx: &CrateContext,
1690 _enum_id: ast::NodeId,
1691 variant: &ast::Variant,
1692 _args: &[ast::VariantArg],
1694 param_substs: ¶m_substs,
1695 llfndecl: ValueRef) {
1696 let _icx = push_ctxt("trans_enum_variant");
1698 trans_enum_variant_or_tuple_like_struct(
1706 pub fn trans_named_tuple_constructor<'a>(mut bcx: &'a Block<'a>,
1709 args: callee::CallArgs,
1710 dest: expr::Dest) -> Result<'a> {
1712 let ccx = bcx.fcx.ccx;
1715 let result_ty = match ty::get(ctor_ty).sty {
1716 ty::ty_bare_fn(ref bft) => bft.sig.output,
1717 _ => ccx.sess().bug(
1718 format!("trans_enum_variant_constructor: \
1719 unexpected ctor return type {}",
1720 ctor_ty.repr(tcx)).as_slice())
1723 // Get location to store the result. If the user does not care about
1724 // the result, just make a stack slot
1725 let llresult = match dest {
1726 expr::SaveIn(d) => d,
1728 if !type_is_zero_size(ccx, result_ty) {
1729 alloc_ty(bcx, result_ty, "constructor_result")
1731 C_undef(type_of::type_of(ccx, result_ty))
1736 if !type_is_zero_size(ccx, result_ty) {
1737 let repr = adt::represent_type(ccx, result_ty);
1740 callee::ArgExprs(exprs) => {
1741 let fields = exprs.iter().map(|x| *x).enumerate().collect::<Vec<_>>();
1742 bcx = expr::trans_adt(bcx, &*repr, disr, fields.as_slice(),
1743 None, expr::SaveIn(llresult));
1745 _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor")
1749 // If the caller doesn't care about the result
1750 // drop the temporary we made
1751 let bcx = match dest {
1752 expr::SaveIn(_) => bcx,
1753 expr::Ignore => glue::drop_ty(bcx, llresult, result_ty)
1756 Result::new(bcx, llresult)
1759 pub fn trans_tuple_struct(ccx: &CrateContext,
1760 _fields: &[ast::StructField],
1761 ctor_id: ast::NodeId,
1762 param_substs: ¶m_substs,
1763 llfndecl: ValueRef) {
1764 let _icx = push_ctxt("trans_tuple_struct");
1766 trans_enum_variant_or_tuple_like_struct(
1774 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1775 ctor_id: ast::NodeId,
1777 param_substs: ¶m_substs,
1778 llfndecl: ValueRef) {
1779 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1780 let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
1782 let result_ty = match ty::get(ctor_ty).sty {
1783 ty::ty_bare_fn(ref bft) => bft.sig.output,
1784 _ => ccx.sess().bug(
1785 format!("trans_enum_variant_or_tuple_like_struct: \
1786 unexpected ctor return type {}",
1787 ty_to_string(ccx.tcx(), ctor_ty)).as_slice())
1790 let arena = TypedArena::new();
1791 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1792 param_substs, None, &arena);
1793 let bcx = init_function(&fcx, false, result_ty);
1795 let arg_tys = ty::ty_fn_args(ctor_ty);
1797 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1799 if !type_is_zero_size(fcx.ccx, result_ty) {
1800 let repr = adt::represent_type(ccx, result_ty);
1801 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1802 let lldestptr = adt::trans_field_ptr(bcx,
1804 fcx.llretptr.get().unwrap(),
1807 arg_datum.store_to(bcx, lldestptr);
1809 adt::trans_set_discr(bcx, &*repr, fcx.llretptr.get().unwrap(), disr);
1812 finish_fn(&fcx, bcx, result_ty);
1815 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
1816 let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
1818 let levels = ccx.tcx.node_lint_levels.borrow();
1819 let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCE);
1820 let lvlsrc = match levels.find(&(id, lint_id)) {
1821 None | Some(&(lint::Allow, _)) => return,
1822 Some(&lvlsrc) => lvlsrc,
1825 let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
1827 adt::General(_, ref variants) => {
1828 for var in variants.iter() {
1830 for field in var.fields.iter().skip(1) {
1831 // skip the discriminant
1832 size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
1837 _ => { /* its size is either constant or unimportant */ }
1840 let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
1841 |(l, s, li), (idx, &size)|
1844 } else if size > s {
1851 // we only warn if the largest variant is at least thrice as large as
1852 // the second-largest.
1853 if largest > slargest * 3 && slargest > 0 {
1854 // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
1855 // pass for the latter already ran.
1856 lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCE,
1858 format!("enum variant is more than three times larger \
1859 ({} bytes) than the next largest (ignoring padding)",
1860 largest).as_slice());
1862 ccx.sess().span_note(enum_def.variants.get(largest_index).span,
1863 "this variant is the largest");
1867 pub struct TransItemVisitor<'a> {
1868 pub ccx: &'a CrateContext,
1871 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1872 fn visit_item(&mut self, i: &ast::Item, _:()) {
1873 trans_item(self.ccx, i);
1877 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1878 let _icx = push_ctxt("trans_item");
1880 ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
1882 let llfndecl = get_item_val(ccx, item.id);
1883 foreign::trans_rust_fn_with_foreign_abi(
1884 ccx, &**decl, &**body, item.attrs.as_slice(), llfndecl, item.id);
1885 } else if !generics.is_type_parameterized() {
1886 let llfn = get_item_val(ccx, item.id);
1891 ¶m_substs::empty(),
1893 item.attrs.as_slice());
1895 // Be sure to travel more than just one layer deep to catch nested
1896 // items in blocks and such.
1897 let mut v = TransItemVisitor{ ccx: ccx };
1898 v.visit_block(&**body, ());
1901 ast::ItemImpl(ref generics, _, _, ref ms) => {
1902 meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1904 ast::ItemMod(ref m) => {
1907 ast::ItemEnum(ref enum_definition, _) => {
1908 enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
1910 ast::ItemStatic(_, m, ref expr) => {
1911 // Recurse on the expression to catch items in blocks
1912 let mut v = TransItemVisitor{ ccx: ccx };
1913 v.visit_expr(&**expr, ());
1914 consts::trans_const(ccx, m, item.id);
1915 // Do static_assert checking. It can't really be done much earlier
1916 // because we need to get the value of the bool out of LLVM
1917 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1918 if m == ast::MutMutable {
1919 ccx.sess().span_fatal(expr.span,
1920 "cannot have static_assert on a mutable \
1924 let v = ccx.const_values.borrow().get_copy(&item.id);
1926 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1927 ccx.sess().span_fatal(expr.span, "static assertion failed");
1932 ast::ItemForeignMod(ref foreign_mod) => {
1933 foreign::trans_foreign_mod(ccx, foreign_mod);
1935 ast::ItemTrait(..) => {
1936 // Inside of this trait definition, we won't be actually translating any
1937 // functions, but the trait still needs to be walked. Otherwise default
1938 // methods with items will not get translated and will cause ICE's when
1939 // metadata time comes around.
1940 let mut v = TransItemVisitor{ ccx: ccx };
1941 visit::walk_item(&mut v, item, ());
1943 _ => {/* fall through */ }
1947 // Translate a module. Doing this amounts to translating the items in the
1948 // module; there ends up being no artifact (aside from linkage names) of
1949 // separate modules in the compiled program. That's because modules exist
1950 // only as a convenience for humans working with the code, to organize names
1951 // and control visibility.
1952 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1953 let _icx = push_ctxt("trans_mod");
1954 for item in m.items.iter() {
1955 trans_item(ccx, &**item);
1959 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
1961 ccx.item_symbols.borrow_mut().insert(node_id, sym);
1963 if !ccx.reachable.contains(&node_id) {
1964 llvm::SetLinkage(llfn, llvm::InternalLinkage);
1967 // The stack exhaustion lang item shouldn't have a split stack because
1968 // otherwise it would continue to be exhausted (bad), and both it and the
1969 // eh_personality functions need to be externally linkable.
1970 let def = ast_util::local_def(node_id);
1971 if ccx.tcx.lang_items.stack_exhausted() == Some(def) {
1972 unset_split_stack(llfn);
1973 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
1975 if ccx.tcx.lang_items.eh_personality() == Some(def) {
1976 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
1980 if is_entry_fn(ccx.sess(), node_id) {
1981 create_entry_wrapper(ccx, sp, llfn);
1985 fn register_fn(ccx: &CrateContext,
1988 node_id: ast::NodeId,
1991 match ty::get(node_type).sty {
1992 ty::ty_bare_fn(ref f) => {
1993 assert!(f.abi == Rust || f.abi == RustCall);
1995 _ => fail!("expected bare rust fn")
1998 let llfn = decl_rust_fn(ccx, node_type, sym.as_slice());
1999 finish_register_fn(ccx, sp, sym, node_id, llfn);
2003 pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t)
2004 -> Vec<(uint, u64)> {
2005 use middle::ty::{BrAnon, ReLateBound};
2007 let (fn_sig, abi, has_env) = match ty::get(fn_ty).sty {
2008 ty::ty_closure(ref f) => (f.sig.clone(), f.abi, true),
2009 ty::ty_bare_fn(ref f) => (f.sig.clone(), f.abi, false),
2010 ty::ty_unboxed_closure(closure_did) => {
2011 let unboxed_closure_types = ccx.tcx
2012 .unboxed_closure_types
2014 let function_type = unboxed_closure_types.get(&closure_did);
2015 (function_type.sig.clone(), RustCall, true)
2017 _ => fail!("expected closure or function.")
2020 // These have an odd calling convention, so we skip them for now.
2022 // FIXME(pcwalton): We don't have to skip them; just untuple the result.
2023 if abi == RustCall {
2027 // Since index 0 is the return value of the llvm func, we start
2028 // at either 1 or 2 depending on whether there's an env slot or not
2029 let mut first_arg_offset = if has_env { 2 } else { 1 };
2030 let mut attrs = Vec::new();
2031 let ret_ty = fn_sig.output;
2033 // A function pointer is called without the declaration
2034 // available, so we have to apply any attributes with ABI
2035 // implications directly to the call instruction. Right now,
2036 // the only attribute we need to worry about is `sret`.
2037 if type_of::return_uses_outptr(ccx, ret_ty) {
2038 attrs.push((1, llvm::StructRetAttribute as u64));
2040 // The outptr can be noalias and nocapture because it's entirely
2041 // invisible to the program. We can also mark it as nonnull
2042 attrs.push((1, llvm::NoAliasAttribute as u64));
2043 attrs.push((1, llvm::NoCaptureAttribute as u64));
2044 attrs.push((1, llvm::NonNullAttribute as u64));
2046 // Add one more since there's an outptr
2047 first_arg_offset += 1;
2049 // The `noalias` attribute on the return value is useful to a
2050 // function ptr caller.
2051 match ty::get(ret_ty).sty {
2052 // `~` pointer return values never alias because ownership
2054 ty::ty_uniq(it) if match ty::get(it).sty {
2055 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
2058 attrs.push((llvm::ReturnIndex as uint, llvm::NoAliasAttribute as u64));
2063 // We can also mark the return value as `nonnull` in certain cases
2064 match ty::get(ret_ty).sty {
2065 // These are not really pointers but pairs, (pointer, len)
2067 ty::ty_rptr(_, ty::mt { ty: it, .. }) if match ty::get(it).sty {
2068 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
2070 ty::ty_uniq(_) | ty::ty_rptr(_, _) => {
2071 attrs.push((llvm::ReturnIndex as uint, llvm::NonNullAttribute as u64));
2076 match ty::get(ret_ty).sty {
2078 attrs.push((llvm::ReturnIndex as uint, llvm::ZExtAttribute as u64));
2084 for (idx, &t) in fn_sig.inputs.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
2085 match ty::get(t).sty {
2086 // this needs to be first to prevent fat pointers from falling through
2087 _ if !type_is_immediate(ccx, t) => {
2088 // For non-immediate arguments the callee gets its own copy of
2089 // the value on the stack, so there are no aliases. It's also
2090 // program-invisible so can't possibly capture
2091 attrs.push((idx, llvm::NoAliasAttribute as u64));
2092 attrs.push((idx, llvm::NoCaptureAttribute as u64));
2093 attrs.push((idx, llvm::NonNullAttribute as u64));
2096 attrs.push((idx, llvm::ZExtAttribute as u64));
2098 // `~` pointer parameters never alias because ownership is transferred
2100 attrs.push((idx, llvm::NoAliasAttribute as u64));
2101 attrs.push((idx, llvm::NonNullAttribute as u64));
2103 // `&mut` pointer parameters never alias other parameters, or mutable global data
2104 ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable => {
2105 attrs.push((idx, llvm::NoAliasAttribute as u64));
2106 attrs.push((idx, llvm::NonNullAttribute as u64));
2108 ReLateBound(_, BrAnon(_)) => {
2109 attrs.push((idx, llvm::NoCaptureAttribute as u64));
2114 // When a reference in an argument has no named lifetime, it's impossible for that
2115 // reference to escape this function (returned or stored beyond the call by a closure).
2116 ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
2117 attrs.push((idx, llvm::NoCaptureAttribute as u64));
2118 attrs.push((idx, llvm::NonNullAttribute as u64));
2120 // & pointer parameters are never null
2121 ty::ty_rptr(_, _) => {
2122 attrs.push((idx, llvm::NonNullAttribute as u64));
2131 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2132 pub fn register_fn_llvmty(ccx: &CrateContext,
2135 node_id: ast::NodeId,
2137 llfty: Type) -> ValueRef {
2138 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2140 let llfn = decl_fn(ccx, sym.as_slice(), cc, llfty, ty::mk_nil());
2141 finish_register_fn(ccx, sp, sym, node_id, llfn);
2145 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2146 match *sess.entry_fn.borrow() {
2147 Some((entry_id, _)) => node_id == entry_id,
2152 // Create a _rust_main(args: ~[str]) function which will be called from the
2153 // runtime rust_start function
2154 pub fn create_entry_wrapper(ccx: &CrateContext,
2156 main_llfn: ValueRef) {
2157 let et = ccx.sess().entry_type.get().unwrap();
2159 config::EntryMain => {
2160 create_entry_fn(ccx, main_llfn, true);
2162 config::EntryStart => create_entry_fn(ccx, main_llfn, false),
2163 config::EntryNone => {} // Do nothing.
2166 fn create_entry_fn(ccx: &CrateContext,
2167 rust_main: ValueRef,
2168 use_start_lang_item: bool) {
2169 let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
2172 let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil());
2173 let llbb = "top".with_c_str(|buf| {
2175 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2178 let bld = ccx.builder.b;
2180 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2182 let (start_fn, args) = if use_start_lang_item {
2183 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2185 Err(s) => { ccx.sess().fatal(s.as_slice()); }
2187 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2188 get_item_val(ccx, start_def_id.node)
2190 let start_fn_type = csearch::get_type(ccx.tcx(),
2192 trans_external_path(ccx, start_def_id, start_fn_type)
2196 let opaque_rust_main = "rust_main".with_c_str(|buf| {
2197 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
2208 debug!("using user-defined start fn");
2210 get_param(llfn, 0 as c_uint),
2211 get_param(llfn, 1 as c_uint)
2217 let result = llvm::LLVMBuildCall(bld,
2220 args.len() as c_uint,
2223 llvm::LLVMBuildRet(bld, result);
2228 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
2229 ty: ty::t, attrs: &[ast::Attribute]) -> String {
2230 match attr::first_attr_value_str_by_name(attrs, "export_name") {
2231 // Use provided name
2232 Some(name) => name.get().to_string(),
2234 _ => ccx.tcx.map.with_path(id, |mut path| {
2235 if attr::contains_name(attrs, "no_mangle") {
2237 path.last().unwrap().to_string()
2239 match weak_lang_items::link_name(attrs) {
2240 Some(name) => name.get().to_string(),
2242 // Usual name mangling
2243 mangle_exported_name(ccx, path, ty, id)
2251 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2252 debug!("get_item_val(id=`{:?}`)", id);
2254 match ccx.item_vals.borrow().find_copy(&id) {
2255 Some(v) => return v,
2259 let mut foreign = false;
2260 let item = ccx.tcx.map.get(id);
2261 let val = match item {
2262 ast_map::NodeItem(i) => {
2263 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2264 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
2266 let v = match i.node {
2267 ast::ItemStatic(_, mutbl, ref expr) => {
2268 // If this static came from an external crate, then
2269 // we need to get the symbol from csearch instead of
2270 // using the current crate's name/version
2271 // information in the hash of the symbol
2272 debug!("making {}", sym);
2273 let (sym, is_local) = {
2274 match ccx.external_srcs.borrow().find(&i.id) {
2276 debug!("but found in other crate...");
2277 (csearch::get_symbol(&ccx.sess().cstore,
2284 // We need the translated value here, because for enums the
2285 // LLVM type is not fully determined by the Rust type.
2286 let (v, inlineable) = consts::const_expr(ccx, &**expr, is_local);
2287 ccx.const_values.borrow_mut().insert(id, v);
2288 let mut inlineable = inlineable;
2291 let llty = llvm::LLVMTypeOf(v);
2292 let g = sym.as_slice().with_c_str(|buf| {
2293 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2296 if !ccx.reachable.contains(&id) {
2297 llvm::SetLinkage(g, llvm::InternalLinkage);
2300 // Apply the `unnamed_addr` attribute if
2302 if !ast_util::static_has_significant_address(
2304 i.attrs.as_slice()) {
2305 llvm::SetUnnamedAddr(g, true);
2307 // This is a curious case where we must make
2308 // all of these statics inlineable. If a
2309 // global is not tagged as `#[inline(never)]`,
2310 // then LLVM won't coalesce globals unless they
2311 // have an internal linkage type. This means that
2312 // external crates cannot use this global.
2313 // This is a problem for things like inner
2314 // statics in generic functions, because the
2315 // function will be inlined into another
2316 // crate and then attempt to link to the
2317 // static in the original crate, only to
2318 // find that it's not there. On the other
2319 // side of inlining, the crates knows to
2320 // not declare this static as
2321 // available_externally (because it isn't)
2325 if attr::contains_name(i.attrs.as_slice(),
2327 llvm::set_thread_local(g, true);
2331 debug!("{} not inlined", sym);
2332 ccx.non_inlineable_statics.borrow_mut()
2336 ccx.item_symbols.borrow_mut().insert(i.id, sym);
2341 ast::ItemFn(_, _, abi, _, _) => {
2342 let llfn = if abi == Rust {
2343 register_fn(ccx, i.span, sym, i.id, ty)
2345 foreign::register_rust_fn_with_foreign_abi(ccx,
2350 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2354 _ => fail!("get_item_val: weird result in table")
2357 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
2359 Some(sect) => unsafe {
2360 sect.get().with_c_str(|buf| {
2361 llvm::LLVMSetSection(v, buf);
2370 ast_map::NodeTraitMethod(trait_method) => {
2371 debug!("get_item_val(): processing a NodeTraitMethod");
2372 match *trait_method {
2373 ast::Required(_) => {
2374 ccx.sess().bug("unexpected variant: required trait method in \
2377 ast::Provided(m) => {
2378 register_method(ccx, id, &*m)
2383 ast_map::NodeMethod(m) => {
2384 register_method(ccx, id, &*m)
2387 ast_map::NodeForeignItem(ni) => {
2391 ast::ForeignItemFn(..) => {
2392 let abi = ccx.tcx.map.get_foreign_abi(id);
2393 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2394 let name = foreign::link_name(&*ni);
2395 foreign::register_foreign_item_fn(ccx, abi, ty,
2396 name.get().as_slice(),
2399 ast::ForeignItemStatic(..) => {
2400 foreign::register_static(ccx, &*ni)
2405 ast_map::NodeVariant(ref v) => {
2407 let args = match v.node.kind {
2408 ast::TupleVariantKind(ref args) => args,
2409 ast::StructVariantKind(_) => {
2410 fail!("struct variant kind unexpected in get_item_val")
2413 assert!(args.len() != 0u);
2414 let ty = ty::node_id_to_type(ccx.tcx(), id);
2415 let parent = ccx.tcx.map.get_parent(id);
2416 let enm = ccx.tcx.map.expect_item(parent);
2417 let sym = exported_name(ccx,
2420 enm.attrs.as_slice());
2422 llfn = match enm.node {
2423 ast::ItemEnum(_, _) => {
2424 register_fn(ccx, (*v).span, sym, id, ty)
2426 _ => fail!("NodeVariant, shouldn't happen")
2428 set_inline_hint(llfn);
2432 ast_map::NodeStructCtor(struct_def) => {
2433 // Only register the constructor if this is a tuple-like struct.
2434 let ctor_id = match struct_def.ctor_id {
2436 ccx.sess().bug("attempt to register a constructor of \
2437 a non-tuple-like struct")
2439 Some(ctor_id) => ctor_id,
2441 let parent = ccx.tcx.map.get_parent(id);
2442 let struct_item = ccx.tcx.map.expect_item(parent);
2443 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2444 let sym = exported_name(ccx,
2449 let llfn = register_fn(ccx, struct_item.span,
2451 set_inline_hint(llfn);
2456 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2457 variant).as_slice())
2461 // foreign items (extern fns and extern statics) don't have internal
2462 // linkage b/c that doesn't quite make sense. Otherwise items can
2463 // have internal linkage if they're not reachable.
2464 if !foreign && !ccx.reachable.contains(&id) {
2465 llvm::SetLinkage(val, llvm::InternalLinkage);
2468 ccx.item_vals.borrow_mut().insert(id, val);
2472 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2473 m: &ast::Method) -> ValueRef {
2474 let mty = ty::node_id_to_type(ccx.tcx(), id);
2476 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2478 let llfn = register_fn(ccx, m.span, sym, id, mty);
2479 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2483 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2485 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2489 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2490 -> encoder::EncodeParams<'r> {
2491 encoder::EncodeParams {
2492 diag: cx.sess().diagnostic(),
2494 reexports2: &cx.exp_map2,
2495 item_symbols: &cx.item_symbols,
2496 non_inlineable_statics: &cx.non_inlineable_statics,
2497 link_meta: &cx.link_meta,
2498 cstore: &cx.sess().cstore,
2499 encode_inlined_item: ie,
2500 reachable: &cx.reachable,
2504 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2507 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2508 *ty != config::CrateTypeExecutable
2514 let encode_inlined_item: encoder::EncodeInlinedItem =
2515 |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
2517 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2518 let metadata = encoder::encode_metadata(encode_parms, krate);
2519 let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2520 .append(match flate::deflate_bytes(metadata.as_slice()) {
2521 Some(compressed) => compressed,
2523 cx.sess().fatal("failed to compress metadata")
2526 let llmeta = C_bytes(cx, compressed.as_slice());
2527 let llconst = C_struct(cx, [llmeta], false);
2528 let name = format!("rust_metadata_{}_{}",
2529 cx.link_meta.crate_name,
2530 cx.link_meta.crate_hash);
2531 let llglobal = name.with_c_str(|buf| {
2533 llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2537 llvm::LLVMSetInitializer(llglobal, llconst);
2538 let name = loader::meta_section_name(cx.sess().targ_cfg.os);
2539 name.unwrap_or("rust_metadata").with_c_str(|buf| {
2540 llvm::LLVMSetSection(llglobal, buf)
2546 pub fn trans_crate(krate: ast::Crate,
2547 analysis: CrateAnalysis) -> (ty::ctxt, CrateTranslation) {
2548 let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, name, .. } = analysis;
2550 // Before we touch LLVM, make sure that multithreading is enabled.
2552 use std::sync::{Once, ONCE_INIT};
2553 static mut INIT: Once = ONCE_INIT;
2554 static mut POISONED: bool = false;
2556 if llvm::LLVMStartMultithreaded() != 1 {
2557 // use an extra bool to make sure that all future usage of LLVM
2558 // cannot proceed despite the Once not running more than once.
2564 tcx.sess.bug("couldn't enable multi-threaded LLVM");
2568 let link_meta = link::build_link_meta(&tcx.sess, &krate, name);
2570 // Append ".rs" to crate name as LLVM module identifier.
2572 // LLVM code generator emits a ".file filename" directive
2573 // for ELF backends. Value of the "filename" is set as the
2574 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2575 // crashes if the module identifier is same as other symbols
2576 // such as a function name in the module.
2577 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2578 let mut llmod_id = link_meta.crate_name.clone();
2579 llmod_id.push_str(".rs");
2581 let ccx = CrateContext::new(llmod_id.as_slice(), tcx, exp_map2,
2582 Sha256::new(), link_meta, reachable);
2584 // First, verify intrinsics.
2585 intrinsic::check_intrinsics(&ccx);
2587 // Next, translate the module.
2589 let _icx = push_ctxt("text");
2590 trans_mod(&ccx, &krate.module);
2593 glue::emit_tydescs(&ccx);
2594 if ccx.sess().opts.debuginfo != NoDebugInfo {
2595 debuginfo::finalize(&ccx);
2598 // Translate the metadata.
2599 let metadata = write_metadata(&ccx, &krate);
2600 if ccx.sess().trans_stats() {
2601 println!("--- trans stats ---");
2602 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2603 println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2604 println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2605 println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2607 println!("n_fns: {}", ccx.stats.n_fns.get());
2608 println!("n_monos: {}", ccx.stats.n_monos.get());
2609 println!("n_inlines: {}", ccx.stats.n_inlines.get());
2610 println!("n_closures: {}", ccx.stats.n_closures.get());
2611 println!("fn stats:");
2612 ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2613 insns_b.cmp(&insns_a)
2615 for tuple in ccx.stats.fn_stats.borrow().iter() {
2617 (ref name, ms, insns) => {
2618 println!("{} insns, {} ms, {}", insns, ms, *name);
2623 if ccx.sess().count_llvm_insns() {
2624 for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2625 println!("{:7u} {}", *v, *k);
2629 let llcx = ccx.llcx;
2630 let link_meta = ccx.link_meta.clone();
2631 let llmod = ccx.llmod;
2633 let mut reachable: Vec<String> = ccx.reachable.iter().filter_map(|id| {
2634 ccx.item_symbols.borrow().find(id).map(|s| s.to_string())
2637 // For the purposes of LTO, we add to the reachable set all of the upstream
2638 // reachable extern fns. These functions are all part of the public ABI of
2639 // the final product, so LTO needs to preserve them.
2640 ccx.sess().cstore.iter_crate_data(|cnum, _| {
2641 let syms = csearch::get_reachable_extern_fns(&ccx.sess().cstore, cnum);
2642 reachable.extend(syms.move_iter().map(|did| {
2643 csearch::get_symbol(&ccx.sess().cstore, did)
2647 // Make sure that some other crucial symbols are not eliminated from the
2648 // module. This includes the main function, the crate map (used for debug
2649 // log settings and I/O), and finally the curious rust_stack_exhausted
2650 // symbol. This symbol is required for use by the libmorestack library that
2651 // we link in, so we must ensure that this symbol is not internalized (if
2652 // defined in the crate).
2653 reachable.push("main".to_string());
2654 reachable.push("rust_stack_exhausted".to_string());
2656 // referenced from .eh_frame section on some platforms
2657 reachable.push("rust_eh_personality".to_string());
2658 // referenced from rt/rust_try.ll
2659 reachable.push("rust_eh_personality_catch".to_string());
2661 let metadata_module = ccx.metadata_llmod;
2662 let formats = ccx.tcx.dependency_formats.borrow().clone();
2663 let no_builtins = attr::contains_name(krate.attrs.as_slice(), "no_builtins");
2665 (ccx.tcx, CrateTranslation {
2669 metadata_module: metadata_module,
2671 reachable: reachable,
2672 crate_formats: formats,
2673 no_builtins: no_builtins,