1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // trans.rs: Translate the completed AST to the LLVM IR.
13 // Some functions here, such as trans_block and trans_expr, return a value --
14 // the result of the translation to LLVM -- while others, such as trans_fn,
15 // trans_impl, and trans_item, are called only for the side effect of adding a
16 // particular definition to the LLVM IR output we're producing.
18 // Hopefully useful general knowledge about trans:
20 // * There's no way to find out the ty::t type of a ValueRef. Doing so
21 // would be "trying to get the eggs out of an omelette" (credit:
22 // pcwalton). You can, instead, find out its TypeRef by calling val_ty,
23 // but one TypeRef corresponds to many `ty::t`s; for instance, tup(int, int,
24 // int) and rec(x=int, y=int, z=int) will have the same TypeRef.
26 #![allow(non_camel_case_types)]
28 use back::link::{mangle_exported_name};
29 use back::{link, abi};
31 use driver::config::{NoDebugInfo, FullDebugInfo};
32 use driver::session::Session;
33 use driver::driver::OutputFilenames;
34 use driver::driver::{CrateAnalysis, CrateTranslation};
35 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
36 use lib::llvm::{llvm, Vector};
38 use metadata::{csearch, encoder};
39 use middle::astencode;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::trans::_match;
42 use middle::trans::adt;
43 use middle::trans::build::*;
44 use middle::trans::builder::{Builder, noname};
45 use middle::trans::callee;
46 use middle::trans::cleanup;
47 use middle::trans::cleanup::CleanupMethods;
48 use middle::trans::common::*;
49 use middle::trans::consts;
50 use middle::trans::controlflow;
51 use middle::trans::datum;
52 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
53 use middle::trans::debuginfo;
54 use middle::trans::expr;
55 use middle::trans::foreign;
56 use middle::trans::glue;
57 use middle::trans::inline;
58 use middle::trans::machine;
59 use middle::trans::machine::{llalign_of_min, llsize_of};
60 use middle::trans::meth;
61 use middle::trans::monomorphize;
62 use middle::trans::tvec;
63 use middle::trans::type_::Type;
64 use middle::trans::type_of;
65 use middle::trans::type_of::*;
66 use middle::trans::value::Value;
69 use util::common::indenter;
70 use util::ppaux::{Repr, ty_to_str};
71 use util::sha2::Sha256;
72 use util::nodemap::NodeMap;
74 use arena::TypedArena;
76 use std::c_str::ToCStr;
77 use std::cell::{Cell, RefCell};
79 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic};
80 use syntax::ast_util::{local_def, is_local};
81 use syntax::attr::AttrMetaMethods;
83 use syntax::codemap::Span;
84 use syntax::parse::token::InternedString;
85 use syntax::visit::Visitor;
87 use syntax::{ast, ast_util, ast_map};
91 local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)
93 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
94 match task_local_insn_key.get() {
95 Some(ctx) => blk(ctx.borrow().as_slice()),
100 pub fn init_insn_ctxt() {
101 task_local_insn_key.replace(Some(RefCell::new(Vec::new())));
104 pub struct _InsnCtxt { _x: () }
107 impl Drop for _InsnCtxt {
109 match task_local_insn_key.get() {
110 Some(ctx) => { ctx.borrow_mut().pop(); }
116 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
117 debug!("new InsnCtxt: {}", s);
118 match task_local_insn_key.get() {
119 Some(ctx) => ctx.borrow_mut().push(s),
125 pub struct StatRecorder<'a> {
126 ccx: &'a CrateContext,
127 name: Option<StrBuf>,
132 impl<'a> StatRecorder<'a> {
133 pub fn new(ccx: &'a CrateContext, name: StrBuf) -> StatRecorder<'a> {
134 let start = if ccx.sess().trans_stats() {
135 time::precise_time_ns()
139 let istart = ccx.stats.n_llvm_insns.get();
150 impl<'a> Drop for StatRecorder<'a> {
152 if self.ccx.sess().trans_stats() {
153 let end = time::precise_time_ns();
154 let elapsed = ((end - self.start) / 1_000_000) as uint;
155 let iend = self.ccx.stats.n_llvm_insns.get();
156 self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
158 iend - self.istart));
159 self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
160 // Reset LLVM insn count to avoid compound costs.
161 self.ccx.stats.n_llvm_insns.set(self.istart);
166 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
167 fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv,
168 ty: Type, output: ty::t) -> ValueRef {
169 let llfn: ValueRef = name.with_c_str(|buf| {
171 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
175 match ty::get(output).sty {
176 // functions returning bottom may unwind, but can never return normally
179 llvm::LLVMAddFunctionAttr(llfn, lib::llvm::NoReturnAttribute as c_uint)
182 // `~` pointer return values never alias because ownership is transferred
183 ty::ty_uniq(..) // | ty::ty_trait(_, _, ty::UniqTraitStore, _, _)
186 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
192 lib::llvm::SetFunctionCallConv(llfn, cc);
193 // Function addresses in Rust are never significant, allowing functions to be merged.
194 lib::llvm::SetUnnamedAddr(llfn, true);
195 set_split_stack(llfn);
200 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
201 pub fn decl_cdecl_fn(llmod: ModuleRef,
204 output: ty::t) -> ValueRef {
205 decl_fn(llmod, name, lib::llvm::CCallConv, ty, output)
208 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
209 pub fn get_extern_fn(externs: &mut ExternMap,
212 cc: lib::llvm::CallConv,
216 match externs.find_equiv(&name) {
217 Some(n) => return *n,
220 let f = decl_fn(llmod, name, cc, ty, output);
221 externs.insert(name.to_strbuf(), f);
225 fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
226 name: &str, did: ast::DefId) -> ValueRef {
227 match ccx.externs.borrow().find_equiv(&name) {
228 Some(n) => return *n,
232 let f = decl_rust_fn(ccx, false, inputs, output, name);
233 csearch::get_item_attrs(&ccx.sess().cstore, did, |meta_items| {
234 set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x))
235 .collect::<Vec<_>>().as_slice(), f)
238 ccx.externs.borrow_mut().insert(name.to_strbuf(), f);
242 pub fn decl_rust_fn(ccx: &CrateContext, has_env: bool,
243 inputs: &[ty::t], output: ty::t,
244 name: &str) -> ValueRef {
245 use middle::ty::{BrAnon, ReLateBound};
247 let llfty = type_of_rust_fn(ccx, has_env, inputs, output);
248 let llfn = decl_cdecl_fn(ccx.llmod, name, llfty, output);
250 let uses_outptr = type_of::return_uses_outptr(ccx, output);
251 let offset = if uses_outptr { 1 } else { 0 };
252 let offset = if has_env { offset + 1 } else { offset };
254 for (i, &arg_ty) in inputs.iter().enumerate() {
255 let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
256 match ty::get(arg_ty).sty {
257 // `~` pointer parameters never alias because ownership is transferred
260 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
263 // `&mut` pointer parameters never alias other parameters, or mutable global data
264 ty::ty_rptr(_, mt) if mt.mutbl == ast::MutMutable => {
266 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
269 // When a reference in an argument has no named lifetime, it's impossible for that
270 // reference to escape this function (returned or stored beyond the call by a closure).
271 ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
272 debug!("marking argument of {} as nocapture because of anonymous lifetime", name);
274 llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
278 // For non-immediate arguments the callee gets its own copy of
279 // the value on the stack, so there are no aliases
280 if !type_is_immediate(ccx, arg_ty) {
282 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
283 llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
290 // The out pointer will never alias with any other pointers, as the object only exists at a
291 // language level after the call. It can also be tagged with SRet to indicate that it is
292 // guaranteed to point to a usable block of memory for the type.
295 let outptr = llvm::LLVMGetParam(llfn, 0);
296 llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
297 llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
304 pub fn decl_internal_rust_fn(ccx: &CrateContext, has_env: bool,
305 inputs: &[ty::t], output: ty::t,
306 name: &str) -> ValueRef {
307 let llfn = decl_rust_fn(ccx, has_env, inputs, output, name);
308 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
312 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
313 name: &str, ty: Type) -> ValueRef {
314 match externs.find_equiv(&name) {
315 Some(n) => return *n,
319 let c = name.with_c_str(|buf| {
320 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
322 externs.insert(name.to_strbuf(), c);
327 // Returns a pointer to the body for the box. The box may be an opaque
328 // box. The result will be casted to the type of body_t, if it is statically
330 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
331 let _icx = push_ctxt("at_box_body");
333 let ty = Type::at_box(ccx, type_of(ccx, body_t));
334 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
335 GEPi(bcx, boxptr, [0u, abi::box_field_body])
338 fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
339 match bcx.tcx().lang_items.require(it) {
342 bcx.sess().fatal(format!("allocation of `{}` {}",
343 bcx.ty_to_str(info_ty), s));
348 // The following malloc_raw_dyn* functions allocate a box to contain
349 // a given type, but with a potentially dynamic size.
351 pub fn malloc_raw_dyn<'a>(bcx: &'a Block<'a>,
356 let _icx = push_ctxt("malloc_raw_exchange");
360 let r = callee::trans_lang_call(bcx,
361 require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
365 let llty_ptr = type_of::type_of(ccx, ptr_ty);
366 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
369 pub fn malloc_raw_dyn_managed<'a>(
375 let _icx = push_ctxt("malloc_raw_managed");
378 let langcall = require_alloc_fn(bcx, t, alloc_fn);
380 // Grab the TypeRef type of box_ptr_ty.
381 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
382 let llty = type_of(ccx, box_ptr_ty);
383 let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
386 let drop_glue = glue::get_drop_glue(ccx, t);
387 let r = callee::trans_lang_call(
391 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
396 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
399 // Type descriptor and type glue stuff
401 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
402 match ccx.tydescs.borrow().find(&t) {
403 Some(inf) => return inf.clone(),
407 ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
408 let inf = Rc::new(glue::declare_tydesc(ccx, t));
410 ccx.tydescs.borrow_mut().insert(t, inf.clone());
414 #[allow(dead_code)] // useful
415 pub fn set_optimize_for_size(f: ValueRef) {
416 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
419 pub fn set_no_inline(f: ValueRef) {
420 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
423 #[allow(dead_code)] // useful
424 pub fn set_no_unwind(f: ValueRef) {
425 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
428 // Tell LLVM to emit the information necessary to unwind the stack for the
430 pub fn set_uwtable(f: ValueRef) {
431 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
434 pub fn set_inline_hint(f: ValueRef) {
435 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
438 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
440 // Set the inline hint if there is one
441 match find_inline_attr(attrs) {
442 InlineHint => set_inline_hint(llfn),
443 InlineAlways => set_always_inline(llfn),
444 InlineNever => set_no_inline(llfn),
445 InlineNone => { /* fallthrough */ }
448 // Add the no-split-stack attribute if requested
449 if contains_name(attrs, "no_split_stack") {
450 unset_split_stack(llfn);
453 if contains_name(attrs, "cold") {
454 unsafe { llvm::LLVMAddColdAttribute(llfn) }
458 pub fn set_always_inline(f: ValueRef) {
459 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
462 pub fn set_split_stack(f: ValueRef) {
463 "split-stack".with_c_str(|buf| {
464 unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
468 pub fn unset_split_stack(f: ValueRef) {
469 "split-stack".with_c_str(|buf| {
470 unsafe { llvm::LLVMRemoveFunctionAttrString(f, buf); }
474 // Double-check that we never ask LLVM to declare the same symbol twice. It
475 // silently mangles such symbols, breaking our linkage model.
476 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: StrBuf) {
477 if ccx.all_llvm_symbols.borrow().contains(&sym) {
478 ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym));
480 ccx.all_llvm_symbols.borrow_mut().insert(sym);
484 pub fn get_res_dtor(ccx: &CrateContext,
486 parent_id: ast::DefId,
489 let _icx = push_ctxt("trans_res_dtor");
490 let did = if did.krate != ast::LOCAL_CRATE {
491 inline::maybe_instantiate_inline(ccx, did)
496 if !substs.tps.is_empty() || !substs.self_ty.is_none() {
497 assert_eq!(did.krate, ast::LOCAL_CRATE);
499 let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, substs);
500 let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, vtables, None, None);
503 } else if did.krate == ast::LOCAL_CRATE {
504 get_item_val(ccx, did.node)
507 let name = csearch::get_symbol(&ccx.sess().cstore, did);
508 let class_ty = ty::subst(tcx, substs,
509 ty::lookup_item_type(tcx, parent_id).ty);
510 let llty = type_of_dtor(ccx, class_ty);
512 get_extern_fn(&mut *ccx.externs.borrow_mut(),
515 lib::llvm::CCallConv,
521 // Structural comparison: a rather involved form of glue.
522 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
523 if cx.sess().opts.cg.save_temps {
526 llvm::LLVMSetValueName(v, buf)
533 // Used only for creating scalar comparison glue.
534 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
536 // NB: This produces an i1, not a Rust bool (i8).
537 pub fn compare_scalar_types<'a>(
544 let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
546 match ty::get(t).sty {
547 ty::ty_nil => f(nil_type),
548 ty::ty_bool | ty::ty_ptr(_) |
549 ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
550 ty::ty_int(_) => f(signed_int),
551 ty::ty_float(_) => f(floating_point),
552 // Should never get here, because t is scalar.
553 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
558 // A helper function to do the actual comparison of scalar values.
559 pub fn compare_scalar_values<'a>(
566 let _icx = push_ctxt("compare_scalar_values");
567 fn die(cx: &Block) -> ! {
568 cx.sess().bug("compare_scalar_values: must be a comparison operator");
572 // We don't need to do actual comparisons for nil.
573 // () == () holds but () < () does not.
575 ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(cx.ccx(), true),
576 ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(cx.ccx(), false),
577 // refinements would be nice
583 ast::BiEq => lib::llvm::RealOEQ,
584 ast::BiNe => lib::llvm::RealUNE,
585 ast::BiLt => lib::llvm::RealOLT,
586 ast::BiLe => lib::llvm::RealOLE,
587 ast::BiGt => lib::llvm::RealOGT,
588 ast::BiGe => lib::llvm::RealOGE,
591 return FCmp(cx, cmp, lhs, rhs);
595 ast::BiEq => lib::llvm::IntEQ,
596 ast::BiNe => lib::llvm::IntNE,
597 ast::BiLt => lib::llvm::IntSLT,
598 ast::BiLe => lib::llvm::IntSLE,
599 ast::BiGt => lib::llvm::IntSGT,
600 ast::BiGe => lib::llvm::IntSGE,
603 return ICmp(cx, cmp, lhs, rhs);
607 ast::BiEq => lib::llvm::IntEQ,
608 ast::BiNe => lib::llvm::IntNE,
609 ast::BiLt => lib::llvm::IntULT,
610 ast::BiLe => lib::llvm::IntULE,
611 ast::BiGt => lib::llvm::IntUGT,
612 ast::BiGe => lib::llvm::IntUGE,
615 return ICmp(cx, cmp, lhs, rhs);
620 pub fn compare_simd_types(
628 match ty::get(t).sty {
630 // The comparison operators for floating point vectors are challenging.
631 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
632 // then bitcast to a floating point vector, the result will be `-NaN`
633 // for each truth value. Because of this they are unsupported.
634 cx.sess().bug("compare_simd_types: comparison operators \
635 not supported for floating point SIMD types")
637 ty::ty_uint(_) | ty::ty_int(_) => {
639 ast::BiEq => lib::llvm::IntEQ,
640 ast::BiNe => lib::llvm::IntNE,
641 ast::BiLt => lib::llvm::IntSLT,
642 ast::BiLe => lib::llvm::IntSLE,
643 ast::BiGt => lib::llvm::IntSGT,
644 ast::BiGe => lib::llvm::IntSGE,
645 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
647 let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
648 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
649 // to get the correctly sized type. This will compile to a single instruction
650 // once the IR is converted to assembly if the SIMD instruction is supported
651 // by the target architecture.
652 SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
654 _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
658 pub type val_and_ty_fn<'r,'b> =
659 |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
661 // Iterates through the elements of a structural type.
662 pub fn iter_structural_ty<'r,
667 f: val_and_ty_fn<'r,'b>)
669 let _icx = push_ctxt("iter_structural_ty");
676 variant: &ty::VariantInfo,
678 f: val_and_ty_fn<'r,'b>)
680 let _icx = push_ctxt("iter_variant");
684 for (i, &arg) in variant.args.iter().enumerate() {
686 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
687 ty::subst(tcx, substs, arg));
693 match ty::get(t).sty {
694 ty::ty_struct(..) => {
695 let repr = adt::represent_type(cx.ccx(), t);
696 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
697 for (i, field_ty) in field_tys.iter().enumerate() {
698 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, discr, i);
699 cx = f(cx, llfld_a, field_ty.mt.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() {
741 fcx.new_temp_block("enum-iter-variant-".to_owned() +
742 variant.disr_val.to_str());
743 match adt::trans_case(cx, &*repr, variant.disr_val) {
744 _match::single_result(r) => {
745 AddCase(llswitch, r.val, variant_cx.llbb)
747 _ => ccx.sess().unimpl("value from adt::trans_case \
748 in iter_structural_ty")
751 iter_variant(variant_cx,
757 Br(variant_cx, next_cx.llbb);
761 _ => ccx.sess().unimpl("value from adt::trans_switch \
762 in iter_structural_ty")
765 _ => cx.sess().unimpl("type in iter_structural_ty")
770 pub fn cast_shift_expr_rhs<'a>(
776 cast_shift_rhs(op, lhs, rhs,
777 |a,b| Trunc(cx, a, b),
778 |a,b| ZExt(cx, a, b))
781 pub fn cast_shift_const_rhs(op: ast::BinOp,
782 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
783 cast_shift_rhs(op, lhs, rhs,
784 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
785 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
788 pub fn cast_shift_rhs(op: ast::BinOp,
791 trunc: |ValueRef, Type| -> ValueRef,
792 zext: |ValueRef, Type| -> ValueRef)
794 // Shifts may have any size int on the rhs
796 if ast_util::is_shift_binop(op) {
797 let mut rhs_llty = val_ty(rhs);
798 let mut lhs_llty = val_ty(lhs);
799 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
800 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
801 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
802 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
805 } else if lhs_sz > rhs_sz {
806 // FIXME (#1877: If shifting by negative
807 // values becomes not undefined then this is wrong.
818 pub fn fail_if_zero<'a>(
825 let text = if divrem == ast::BiDiv {
826 "attempted to divide by zero"
828 "attempted remainder with a divisor of zero"
830 let is_zero = match ty::get(rhs_t).sty {
832 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
833 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
836 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
837 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
840 cx.sess().bug(format!("fail-if-zero on unexpected type: {}",
841 ty_to_str(cx.tcx(), rhs_t)));
844 with_cond(cx, is_zero, |bcx| {
845 controlflow::trans_fail(bcx, span, InternedString::new(text))
849 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
850 let name = csearch::get_symbol(&ccx.sess().cstore, did);
851 match ty::get(t).sty {
852 ty::ty_bare_fn(ref fn_ty) => {
853 match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
854 ccx.sess().targ_cfg.arch) {
855 Some(Rust) | Some(RustIntrinsic) => {
856 get_extern_rust_fn(ccx,
857 fn_ty.sig.inputs.as_slice(),
863 foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
864 name.as_slice(), None)
868 ty::ty_closure(ref f) => {
869 get_extern_rust_fn(ccx,
870 f.sig.inputs.as_slice(),
876 let llty = type_of(ccx, t);
877 get_extern_const(&mut *ccx.externs.borrow_mut(),
888 llargs: Vec<ValueRef> ,
889 attributes: &[(uint, lib::llvm::Attribute)],
890 call_info: Option<NodeInfo>)
891 -> (ValueRef, &'a Block<'a>) {
892 let _icx = push_ctxt("invoke_");
893 if bcx.unreachable.get() {
894 return (C_null(Type::i8(bcx.ccx())), bcx);
897 match bcx.opt_node_id {
899 debug!("invoke at ???");
902 debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
906 if need_invoke(bcx) {
907 debug!("invoking {} at {}", llfn, bcx.llbb);
908 for &llarg in llargs.iter() {
909 debug!("arg: {}", llarg);
911 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
912 let landing_pad = bcx.fcx.get_landing_pad();
915 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
916 None => debuginfo::clear_source_location(bcx.fcx)
919 let llresult = Invoke(bcx,
925 return (llresult, normal_bcx);
927 debug!("calling {} at {}", llfn, bcx.llbb);
928 for &llarg in llargs.iter() {
929 debug!("arg: {}", llarg);
933 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
934 None => debuginfo::clear_source_location(bcx.fcx)
937 let llresult = Call(bcx, llfn, llargs.as_slice(), attributes);
938 return (llresult, bcx);
942 pub fn need_invoke(bcx: &Block) -> bool {
943 if bcx.sess().no_landing_pads() {
947 // Avoid using invoke if we are already inside a landing pad.
952 bcx.fcx.needs_invoke()
955 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
956 let _icx = push_ctxt("load_if_immediate");
957 if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
961 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
962 match local.pat.node {
963 ast::PatWild => true, _ => false
967 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
970 debug!("init_local(bcx={}, local.id={:?})",
971 bcx.to_str(), local.id);
972 let _indenter = indenter();
974 let _icx = push_ctxt("init_local");
976 if ignore_lhs(bcx, local) {
977 // Handle let _ = e; just like e;
980 return controlflow::trans_stmt_semi(bcx, init)
982 None => { return bcx; }
986 _match::store_local(bcx, local)
989 pub fn raw_block<'a>(
990 fcx: &'a FunctionContext<'a>,
994 Block::new(llbb, is_lpad, None, fcx)
997 pub fn with_cond<'a>(
1000 f: |&'a Block<'a>| -> &'a Block<'a>)
1002 let _icx = push_ctxt("with_cond");
1004 let next_cx = fcx.new_temp_block("next");
1005 let cond_cx = fcx.new_temp_block("cond");
1006 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1007 let after_cx = f(cond_cx);
1008 if !after_cx.terminated.get() {
1009 Br(after_cx, next_cx.llbb);
1014 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1015 let _icx = push_ctxt("call_memcpy");
1017 let key = match ccx.sess().targ_cfg.arch {
1018 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1019 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1021 let memcpy = ccx.get_intrinsic(&key);
1022 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1023 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1024 let size = IntCast(cx, n_bytes, ccx.int_type);
1025 let align = C_i32(ccx, align as i32);
1026 let volatile = C_i1(ccx, false);
1027 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1030 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1031 let _icx = push_ctxt("memcpy_ty");
1032 let ccx = bcx.ccx();
1033 if ty::type_is_structural(t) {
1034 let llty = type_of::type_of(ccx, t);
1035 let llsz = llsize_of(ccx, llty);
1036 let llalign = llalign_of_min(ccx, llty);
1037 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1039 Store(bcx, Load(bcx, src), dst);
1043 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1044 if cx.unreachable.get() { return; }
1045 let _icx = push_ctxt("zero_mem");
1048 let llty = type_of::type_of(ccx, t);
1049 memzero(&B(bcx), llptr, llty);
1052 // Always use this function instead of storing a zero constant to the memory
1053 // in question. If you store a zero constant, LLVM will drown in vreg
1054 // allocation for large data structures, and the generated code will be
1055 // awful. (A telltale sign of this is large quantities of
1056 // `mov [byte ptr foo],0` in the generated code.)
1057 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1058 let _icx = push_ctxt("memzero");
1061 let intrinsic_key = match ccx.sess().targ_cfg.arch {
1062 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1063 X86_64 => "llvm.memset.p0i8.i64"
1066 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1067 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1068 let llzeroval = C_u8(ccx, 0);
1069 let size = machine::llsize_of(ccx, ty);
1070 let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1071 let volatile = C_i1(ccx, false);
1072 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1075 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1076 let _icx = push_ctxt("alloc_ty");
1077 let ccx = bcx.ccx();
1078 let ty = type_of::type_of(ccx, t);
1079 assert!(!ty::type_has_params(t));
1080 let val = alloca(bcx, ty, name);
1084 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1085 alloca_maybe_zeroed(cx, ty, name, false)
1088 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1089 let _icx = push_ctxt("alloca");
1090 if cx.unreachable.get() {
1092 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1095 debuginfo::clear_source_location(cx.fcx);
1096 let p = Alloca(cx, ty, name);
1098 let b = cx.fcx.ccx.builder();
1099 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1105 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1106 let _icx = push_ctxt("arrayalloca");
1107 if cx.unreachable.get() {
1109 return llvm::LLVMGetUndef(ty.to_ref());
1112 debuginfo::clear_source_location(cx.fcx);
1113 return ArrayAlloca(cx, ty, v);
1116 // Creates and returns space for, or returns the argument representing, the
1117 // slot where the return value of the function must go.
1118 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1121 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1122 llvm::LLVMGetParam(fcx.llfn, 0)
1124 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1125 let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1126 Alloca(bcx, lloutputtype, "__make_return_pointer")
1131 // NB: must keep 4 fns in sync:
1134 // - create_datums_for_fn_args.
1138 // Be warned! You must call `init_function` before doing anything with the
1139 // returned function context.
1140 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1145 param_substs: Option<&'a param_substs>,
1147 block_arena: &'a TypedArena<Block<'a>>)
1148 -> FunctionContext<'a> {
1149 for p in param_substs.iter() { p.validate(); }
1151 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1155 ccx.tcx.map.path_to_str(id).to_owned()
1157 id, param_substs.map(|s| s.repr(ccx.tcx())));
1159 let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1160 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1161 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1163 let mut fcx = FunctionContext {
1166 llretptr: Cell::new(None),
1167 entry_bcx: RefCell::new(None),
1168 alloca_insert_pt: Cell::new(None),
1169 llreturn: Cell::new(None),
1170 personality: Cell::new(None),
1171 caller_expects_out_pointer: uses_outptr,
1172 llargs: RefCell::new(NodeMap::new()),
1173 lllocals: RefCell::new(NodeMap::new()),
1174 llupvars: RefCell::new(NodeMap::new()),
1176 param_substs: param_substs,
1178 block_arena: block_arena,
1180 debug_context: debug_context,
1181 scopes: RefCell::new(Vec::new())
1185 fcx.llenv = Some(unsafe {
1186 llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1193 /// Performs setup on a newly created function, creating the entry scope block
1194 /// and allocating space for the return pointer.
1195 pub fn init_function<'a>(fcx: &'a FunctionContext<'a>,
1197 output_type: ty::t) {
1198 let entry_bcx = fcx.new_temp_block("entry-block");
1200 *fcx.entry_bcx.borrow_mut() = Some(entry_bcx);
1202 // Use a dummy instruction as the insertion point for all allocas.
1203 // This is later removed in FunctionContext::cleanup.
1204 fcx.alloca_insert_pt.set(Some(unsafe {
1205 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1206 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1209 // This shouldn't need to recompute the return type,
1210 // as new_fn_ctxt did it already.
1211 let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1213 if !return_type_is_void(fcx.ccx, substd_output_type) {
1214 // If the function returns nil/bot, there is no real return
1215 // value, so do not set `llretptr`.
1216 if !skip_retptr || fcx.caller_expects_out_pointer {
1217 // Otherwise, we normally allocate the llretptr, unless we
1218 // have been instructed to skip it for immediate return
1220 fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1225 // NB: must keep 4 fns in sync:
1228 // - create_datums_for_fn_args.
1232 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1233 use middle::trans::datum::{ByRef, ByValue};
1236 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1240 // work around bizarre resolve errors
1241 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1242 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1244 // create_datums_for_fn_args: creates rvalue datums for each of the
1245 // incoming function arguments. These will later be stored into
1246 // appropriate lvalue datums.
1247 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1249 -> Vec<RvalueDatum> {
1250 let _icx = push_ctxt("create_datums_for_fn_args");
1252 // Return an array wrapping the ValueRefs that we get from
1253 // llvm::LLVMGetParam for each argument into datums.
1254 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1255 let llarg = unsafe {
1256 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1258 datum::Datum(llarg, arg_ty, arg_kind(fcx, arg_ty))
1262 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1263 arg_scope: cleanup::CustomScopeIndex,
1266 arg_datums: Vec<RvalueDatum> )
1268 debug!("copy_args_to_allocas");
1270 let _icx = push_ctxt("copy_args_to_allocas");
1273 let arg_scope_id = cleanup::CustomScope(arg_scope);
1275 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1276 // For certain mode/type combinations, the raw llarg values are passed
1277 // by value. However, within the fn body itself, we want to always
1278 // have all locals and arguments be by-ref so that we can cancel the
1279 // cleanup and for better interaction with LLVM's debug info. So, if
1280 // the argument would be passed by value, we store it into an alloca.
1281 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1282 // the event it's not truly needed.
1284 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1286 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1287 debuginfo::create_argument_metadata(bcx, &args[i]);
1294 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1295 // and builds the return block.
1296 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1297 last_bcx: &'a Block<'a>) {
1298 let _icx = push_ctxt("finish_fn");
1300 let ret_cx = match fcx.llreturn.get() {
1302 if !last_bcx.terminated.get() {
1303 Br(last_bcx, llreturn);
1305 raw_block(fcx, false, llreturn)
1309 build_return_block(fcx, ret_cx);
1310 debuginfo::clear_source_location(fcx);
1314 // Builds the return block for a function.
1315 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1316 // Return the value if this function immediate; otherwise, return void.
1317 if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1318 return RetVoid(ret_cx);
1321 let retptr = Value(fcx.llretptr.get().unwrap());
1322 let retval = match retptr.get_dominating_store(ret_cx) {
1323 // If there's only a single store to the ret slot, we can directly return
1324 // the value that was stored and omit the store and the alloca
1326 let retval = s.get_operand(0).unwrap().get();
1327 s.erase_from_parent();
1329 if retptr.has_no_uses() {
1330 retptr.erase_from_parent();
1335 // Otherwise, load the return value from the ret slot
1336 None => Load(ret_cx, fcx.llretptr.get().unwrap())
1340 Ret(ret_cx, retval);
1343 // trans_closure: Builds an LLVM function out of a source function.
1344 // If the function closes over its environment a closure will be
1346 pub fn trans_closure(ccx: &CrateContext,
1350 param_substs: Option<¶m_substs>,
1352 _attributes: &[ast::Attribute],
1354 maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1355 ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1357 let _icx = push_ctxt("trans_closure");
1358 set_uwtable(llfndecl);
1360 debug!("trans_closure(..., param_substs={})",
1361 param_substs.map(|s| s.repr(ccx.tcx())));
1363 let has_env = match ty::get(ty::node_id_to_type(ccx.tcx(), id)).sty {
1364 ty::ty_closure(_) => true,
1368 let arena = TypedArena::new();
1369 let fcx = new_fn_ctxt(ccx,
1374 param_substs.map(|s| &*s),
1377 init_function(&fcx, false, output_type);
1379 // cleanup scope for the incoming arguments
1380 let arg_scope = fcx.push_custom_cleanup_scope();
1382 // Create the first basic block in the function and keep a handle on it to
1383 // pass to finish_fn later.
1384 let bcx_top = fcx.entry_bcx.borrow().clone().unwrap();
1385 let mut bcx = bcx_top;
1386 let block_ty = node_id_type(bcx, body.id);
1388 // Set up arguments to the function.
1389 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1390 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1392 bcx = copy_args_to_allocas(&fcx,
1395 decl.inputs.as_slice(),
1398 bcx = maybe_load_env(bcx);
1400 // Up until here, IR instructions for this function have explicitly not been annotated with
1401 // source code location, so we don't step into call setup code. From here on, source location
1402 // emitting should be enabled.
1403 debuginfo::start_emitting_source_locations(&fcx);
1405 let dest = match fcx.llretptr.get() {
1406 Some(e) => {expr::SaveIn(e)}
1408 assert!(type_is_zero_size(bcx.ccx(), block_ty))
1413 // This call to trans_block is the place where we bridge between
1414 // translation calls that don't have a return value (trans_crate,
1415 // trans_mod, trans_item, et cetera) and those that do
1416 // (trans_block, trans_expr, et cetera).
1417 bcx = controlflow::trans_block(bcx, body, dest);
1419 match fcx.llreturn.get() {
1421 Br(bcx, fcx.return_exit_block());
1422 fcx.pop_custom_cleanup_scope(arg_scope);
1425 // Microoptimization writ large: avoid creating a separate
1426 // llreturn basic block
1427 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1431 // Put return block after all other blocks.
1432 // This somewhat improves single-stepping experience in debugger.
1434 let llreturn = fcx.llreturn.get();
1435 for &llreturn in llreturn.iter() {
1436 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1440 // Insert the mandatory first few basic blocks before lltop.
1441 finish_fn(&fcx, bcx);
1444 // trans_fn: creates an LLVM function corresponding to a source language
1446 pub fn trans_fn(ccx: &CrateContext,
1450 param_substs: Option<¶m_substs>,
1452 attrs: &[ast::Attribute]) {
1453 let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id).to_strbuf());
1454 debug!("trans_fn(param_substs={})", param_substs.map(|s| s.repr(ccx.tcx())));
1455 let _icx = push_ctxt("trans_fn");
1456 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
1457 trans_closure(ccx, decl, body, llfndecl,
1458 param_substs, id, attrs, output_type, |bcx| bcx);
1461 pub fn trans_enum_variant(ccx: &CrateContext,
1462 _enum_id: ast::NodeId,
1463 variant: &ast::Variant,
1464 _args: &[ast::VariantArg],
1466 param_substs: Option<¶m_substs>,
1467 llfndecl: ValueRef) {
1468 let _icx = push_ctxt("trans_enum_variant");
1470 trans_enum_variant_or_tuple_like_struct(
1478 pub fn trans_tuple_struct(ccx: &CrateContext,
1479 _fields: &[ast::StructField],
1480 ctor_id: ast::NodeId,
1481 param_substs: Option<¶m_substs>,
1482 llfndecl: ValueRef) {
1483 let _icx = push_ctxt("trans_tuple_struct");
1485 trans_enum_variant_or_tuple_like_struct(
1493 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1494 ctor_id: ast::NodeId,
1496 param_substs: Option<¶m_substs>,
1497 llfndecl: ValueRef) {
1498 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1499 let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
1501 let result_ty = match ty::get(ctor_ty).sty {
1502 ty::ty_bare_fn(ref bft) => bft.sig.output,
1503 _ => ccx.sess().bug(
1504 format!("trans_enum_variant_or_tuple_like_struct: \
1505 unexpected ctor return type {}",
1506 ty_to_str(ccx.tcx(), ctor_ty)))
1509 let arena = TypedArena::new();
1510 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1511 param_substs.map(|s| &*s), None, &arena);
1512 init_function(&fcx, false, result_ty);
1514 let arg_tys = ty::ty_fn_args(ctor_ty);
1516 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1518 let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1520 if !type_is_zero_size(fcx.ccx, result_ty) {
1521 let repr = adt::represent_type(ccx, result_ty);
1522 adt::trans_start_init(bcx, &*repr, fcx.llretptr.get().unwrap(), disr);
1523 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1524 let lldestptr = adt::trans_field_ptr(bcx,
1526 fcx.llretptr.get().unwrap(),
1529 arg_datum.store_to(bcx, lldestptr);
1533 finish_fn(&fcx, bcx);
1536 fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1537 id: ast::NodeId, vi: &[Rc<ty::VariantInfo>],
1539 for &variant in enum_definition.variants.iter() {
1540 let disr_val = vi[*i].disr_val;
1543 match variant.node.kind {
1544 ast::TupleVariantKind(ref args) if args.len() > 0 => {
1545 let llfn = get_item_val(ccx, variant.node.id);
1546 trans_enum_variant(ccx, id, variant, args.as_slice(),
1547 disr_val, None, llfn);
1549 ast::TupleVariantKind(_) => {
1552 ast::StructVariantKind(struct_def) => {
1553 trans_struct_def(ccx, struct_def);
1559 pub struct TransItemVisitor<'a> {
1560 pub ccx: &'a CrateContext,
1563 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1564 fn visit_item(&mut self, i: &ast::Item, _:()) {
1565 trans_item(self.ccx, i);
1569 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1570 let _icx = push_ctxt("trans_item");
1572 ast::ItemFn(decl, _fn_style, abi, ref generics, body) => {
1574 let llfndecl = get_item_val(ccx, item.id);
1575 foreign::trans_rust_fn_with_foreign_abi(
1576 ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
1577 } else if !generics.is_type_parameterized() {
1578 let llfn = get_item_val(ccx, item.id);
1585 item.attrs.as_slice());
1587 // Be sure to travel more than just one layer deep to catch nested
1588 // items in blocks and such.
1589 let mut v = TransItemVisitor{ ccx: ccx };
1590 v.visit_block(body, ());
1593 ast::ItemImpl(ref generics, _, _, ref ms) => {
1594 meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1596 ast::ItemMod(ref m) => {
1599 ast::ItemEnum(ref enum_definition, ref generics) => {
1600 if !generics.is_type_parameterized() {
1601 let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1603 trans_enum_def(ccx, enum_definition, item.id, vi.as_slice(), &mut i);
1606 ast::ItemStatic(_, m, expr) => {
1607 // Recurse on the expression to catch items in blocks
1608 let mut v = TransItemVisitor{ ccx: ccx };
1609 v.visit_expr(expr, ());
1610 consts::trans_const(ccx, m, item.id);
1611 // Do static_assert checking. It can't really be done much earlier
1612 // because we need to get the value of the bool out of LLVM
1613 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1614 if m == ast::MutMutable {
1615 ccx.sess().span_fatal(expr.span,
1616 "cannot have static_assert on a mutable \
1620 let v = ccx.const_values.borrow().get_copy(&item.id);
1622 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1623 ccx.sess().span_fatal(expr.span, "static assertion failed");
1628 ast::ItemForeignMod(ref foreign_mod) => {
1629 foreign::trans_foreign_mod(ccx, foreign_mod);
1631 ast::ItemStruct(struct_def, ref generics) => {
1632 if !generics.is_type_parameterized() {
1633 trans_struct_def(ccx, struct_def);
1636 ast::ItemTrait(..) => {
1637 // Inside of this trait definition, we won't be actually translating any
1638 // functions, but the trait still needs to be walked. Otherwise default
1639 // methods with items will not get translated and will cause ICE's when
1640 // metadata time comes around.
1641 let mut v = TransItemVisitor{ ccx: ccx };
1642 visit::walk_item(&mut v, item, ());
1644 _ => {/* fall through */ }
1648 pub fn trans_struct_def(ccx: &CrateContext, struct_def: @ast::StructDef) {
1649 // If this is a tuple-like struct, translate the constructor.
1650 match struct_def.ctor_id {
1651 // We only need to translate a constructor if there are fields;
1652 // otherwise this is a unit-like struct.
1653 Some(ctor_id) if struct_def.fields.len() > 0 => {
1654 let llfndecl = get_item_val(ccx, ctor_id);
1655 trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1656 ctor_id, None, llfndecl);
1658 Some(_) | None => {}
1662 // Translate a module. Doing this amounts to translating the items in the
1663 // module; there ends up being no artifact (aside from linkage names) of
1664 // separate modules in the compiled program. That's because modules exist
1665 // only as a convenience for humans working with the code, to organize names
1666 // and control visibility.
1667 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1668 let _icx = push_ctxt("trans_mod");
1669 for item in m.items.iter() {
1670 trans_item(ccx, *item);
1674 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: StrBuf, node_id: ast::NodeId,
1676 ccx.item_symbols.borrow_mut().insert(node_id, sym);
1678 if !ccx.reachable.contains(&node_id) {
1679 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1682 if is_entry_fn(ccx.sess(), node_id) {
1683 create_entry_wrapper(ccx, sp, llfn);
1687 fn register_fn(ccx: &CrateContext,
1690 node_id: ast::NodeId,
1693 let f = match ty::get(node_type).sty {
1694 ty::ty_bare_fn(ref f) => {
1695 assert!(f.abi == Rust || f.abi == RustIntrinsic);
1698 _ => fail!("expected bare rust fn or an intrinsic")
1701 let llfn = decl_rust_fn(ccx,
1703 f.sig.inputs.as_slice(),
1706 finish_register_fn(ccx, sp, sym, node_id, llfn);
1710 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1711 pub fn register_fn_llvmty(ccx: &CrateContext,
1714 node_id: ast::NodeId,
1715 cc: lib::llvm::CallConv,
1717 output: ty::t) -> ValueRef {
1718 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1720 let llfn = decl_fn(ccx.llmod, sym.as_slice(), cc, fn_ty, output);
1721 finish_register_fn(ccx, sp, sym, node_id, llfn);
1725 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1726 match *sess.entry_fn.borrow() {
1727 Some((entry_id, _)) => node_id == entry_id,
1732 // Create a _rust_main(args: ~[str]) function which will be called from the
1733 // runtime rust_start function
1734 pub fn create_entry_wrapper(ccx: &CrateContext,
1736 main_llfn: ValueRef) {
1737 let et = ccx.sess().entry_type.get().unwrap();
1739 config::EntryMain => {
1740 create_entry_fn(ccx, main_llfn, true);
1742 config::EntryStart => create_entry_fn(ccx, main_llfn, false),
1743 config::EntryNone => {} // Do nothing.
1746 fn create_entry_fn(ccx: &CrateContext,
1747 rust_main: ValueRef,
1748 use_start_lang_item: bool) {
1749 let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
1752 let llfn = decl_cdecl_fn(ccx.llmod, "main", llfty, ty::mk_nil());
1753 let llbb = "top".with_c_str(|buf| {
1755 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1758 let bld = ccx.builder.b;
1760 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1762 let (start_fn, args) = if use_start_lang_item {
1763 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1765 Err(s) => { ccx.sess().fatal(s.as_slice()); }
1767 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1768 get_item_val(ccx, start_def_id.node)
1770 let start_fn_type = csearch::get_type(ccx.tcx(),
1772 trans_external_path(ccx, start_def_id, start_fn_type)
1776 let opaque_rust_main = "rust_main".with_c_str(|buf| {
1777 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
1782 llvm::LLVMGetParam(llfn, 0),
1783 llvm::LLVMGetParam(llfn, 1)
1788 debug!("using user-defined start fn");
1790 llvm::LLVMGetParam(llfn, 0 as c_uint),
1791 llvm::LLVMGetParam(llfn, 1 as c_uint)
1797 let result = llvm::LLVMBuildCall(bld,
1800 args.len() as c_uint,
1803 llvm::LLVMBuildRet(bld, result);
1808 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1809 ty: ty::t, attrs: &[ast::Attribute]) -> StrBuf {
1810 match attr::first_attr_value_str_by_name(attrs, "export_name") {
1811 // Use provided name
1812 Some(name) => name.get().to_strbuf(),
1814 _ => ccx.tcx.map.with_path(id, |mut path| {
1815 if attr::contains_name(attrs, "no_mangle") {
1817 path.last().unwrap().to_str().to_strbuf()
1819 // Usual name mangling
1820 mangle_exported_name(ccx, path, ty, id)
1826 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
1827 debug!("get_item_val(id=`{:?}`)", id);
1829 match ccx.item_vals.borrow().find_copy(&id) {
1830 Some(v) => return v,
1834 let mut foreign = false;
1835 let item = ccx.tcx.map.get(id);
1836 let val = match item {
1837 ast_map::NodeItem(i) => {
1838 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
1839 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1841 let v = match i.node {
1842 ast::ItemStatic(_, _, expr) => {
1843 // If this static came from an external crate, then
1844 // we need to get the symbol from csearch instead of
1845 // using the current crate's name/version
1846 // information in the hash of the symbol
1847 debug!("making {}", sym);
1848 let (sym, is_local) = {
1849 match ccx.external_srcs.borrow().find(&i.id) {
1851 debug!("but found in other crate...");
1852 (csearch::get_symbol(&ccx.sess().cstore,
1859 // We need the translated value here, because for enums the
1860 // LLVM type is not fully determined by the Rust type.
1861 let (v, inlineable) = consts::const_expr(ccx, expr, is_local);
1862 ccx.const_values.borrow_mut().insert(id, v);
1863 let mut inlineable = inlineable;
1866 let llty = llvm::LLVMTypeOf(v);
1867 let g = sym.as_slice().with_c_str(|buf| {
1868 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
1871 if !ccx.reachable.contains(&id) {
1872 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
1875 // Apply the `unnamed_addr` attribute if
1877 if attr::contains_name(i.attrs.as_slice(),
1878 "address_insignificant") {
1879 if ccx.reachable.contains(&id) {
1880 ccx.sess().span_bug(i.span,
1881 "insignificant static is reachable");
1883 lib::llvm::SetUnnamedAddr(g, true);
1885 // This is a curious case where we must make
1886 // all of these statics inlineable. If a
1887 // global is tagged as
1888 // address_insignificant, then LLVM won't
1889 // coalesce globals unless they have an
1890 // internal linkage type. This means that
1891 // external crates cannot use this global.
1892 // This is a problem for things like inner
1893 // statics in generic functions, because the
1894 // function will be inlined into another
1895 // crate and then attempt to link to the
1896 // static in the original crate, only to
1897 // find that it's not there. On the other
1898 // side of inlininig, the crates knows to
1899 // not declare this static as
1900 // available_externally (because it isn't)
1904 if attr::contains_name(i.attrs.as_slice(),
1906 lib::llvm::set_thread_local(g, true);
1910 debug!("{} not inlined", sym);
1911 ccx.non_inlineable_statics.borrow_mut()
1915 ccx.item_symbols.borrow_mut().insert(i.id, sym);
1920 ast::ItemFn(_, _, abi, _, _) => {
1921 let llfn = if abi == Rust {
1922 register_fn(ccx, i.span, sym, i.id, ty)
1924 foreign::register_rust_fn_with_foreign_abi(ccx,
1929 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
1933 _ => fail!("get_item_val: weird result in table")
1936 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
1938 Some(sect) => unsafe {
1939 sect.get().with_c_str(|buf| {
1940 llvm::LLVMSetSection(v, buf);
1949 ast_map::NodeTraitMethod(trait_method) => {
1950 debug!("get_item_val(): processing a NodeTraitMethod");
1951 match *trait_method {
1952 ast::Required(_) => {
1953 ccx.sess().bug("unexpected variant: required trait method in \
1956 ast::Provided(m) => {
1957 register_method(ccx, id, m)
1962 ast_map::NodeMethod(m) => {
1963 register_method(ccx, id, m)
1966 ast_map::NodeForeignItem(ni) => {
1970 ast::ForeignItemFn(..) => {
1971 let abi = ccx.tcx.map.get_foreign_abi(id);
1972 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
1973 let name = foreign::link_name(ni);
1974 foreign::register_foreign_item_fn(ccx, abi, ty,
1975 name.get().as_slice(),
1978 ast::ForeignItemStatic(..) => {
1979 foreign::register_static(ccx, ni)
1984 ast_map::NodeVariant(ref v) => {
1986 let args = match v.node.kind {
1987 ast::TupleVariantKind(ref args) => args,
1988 ast::StructVariantKind(_) => {
1989 fail!("struct variant kind unexpected in get_item_val")
1992 assert!(args.len() != 0u);
1993 let ty = ty::node_id_to_type(ccx.tcx(), id);
1994 let parent = ccx.tcx.map.get_parent(id);
1995 let enm = ccx.tcx.map.expect_item(parent);
1996 let sym = exported_name(ccx,
1999 enm.attrs.as_slice());
2001 llfn = match enm.node {
2002 ast::ItemEnum(_, _) => {
2003 register_fn(ccx, (*v).span, sym, id, ty)
2005 _ => fail!("NodeVariant, shouldn't happen")
2007 set_inline_hint(llfn);
2011 ast_map::NodeStructCtor(struct_def) => {
2012 // Only register the constructor if this is a tuple-like struct.
2013 let ctor_id = match struct_def.ctor_id {
2015 ccx.sess().bug("attempt to register a constructor of \
2016 a non-tuple-like struct")
2018 Some(ctor_id) => ctor_id,
2020 let parent = ccx.tcx.map.get_parent(id);
2021 let struct_item = ccx.tcx.map.expect_item(parent);
2022 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2023 let sym = exported_name(ccx,
2028 let llfn = register_fn(ccx, struct_item.span,
2030 set_inline_hint(llfn);
2035 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2040 // foreign items (extern fns and extern statics) don't have internal
2041 // linkage b/c that doesn't quite make sense. Otherwise items can
2042 // have internal linkage if they're not reachable.
2043 if !foreign && !ccx.reachable.contains(&id) {
2044 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2047 ccx.item_vals.borrow_mut().insert(id, val);
2051 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2052 m: &ast::Method) -> ValueRef {
2053 let mty = ty::node_id_to_type(ccx.tcx(), id);
2055 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2057 let llfn = register_fn(ccx, m.span, sym, id, mty);
2058 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2062 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2064 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2068 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2069 -> encoder::EncodeParams<'r> {
2070 encoder::EncodeParams {
2071 diag: cx.sess().diagnostic(),
2073 reexports2: &cx.exp_map2,
2074 item_symbols: &cx.item_symbols,
2075 non_inlineable_statics: &cx.non_inlineable_statics,
2076 link_meta: &cx.link_meta,
2077 cstore: &cx.sess().cstore,
2078 encode_inlined_item: ie,
2082 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2085 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2086 *ty != config::CrateTypeExecutable
2092 let encode_inlined_item: encoder::EncodeInlinedItem =
2093 |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
2095 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2096 let metadata = encoder::encode_metadata(encode_parms, krate);
2097 let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2098 .append(match flate::deflate_bytes(metadata.as_slice()) {
2099 Some(compressed) => compressed,
2100 None => cx.sess().fatal(format!("failed to compress metadata"))
2102 let llmeta = C_bytes(cx, compressed.as_slice());
2103 let llconst = C_struct(cx, [llmeta], false);
2104 let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2105 cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2106 let llglobal = name.with_c_str(|buf| {
2108 llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2112 llvm::LLVMSetInitializer(llglobal, llconst);
2119 llvm::LLVMSetSection(llglobal, buf)
2125 pub fn trans_crate(krate: ast::Crate,
2126 analysis: CrateAnalysis,
2127 output: &OutputFilenames) -> (ty::ctxt, CrateTranslation) {
2128 let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, .. } = analysis;
2130 // Before we touch LLVM, make sure that multithreading is enabled.
2132 use sync::one::{Once, ONCE_INIT};
2133 static mut INIT: Once = ONCE_INIT;
2134 static mut POISONED: bool = false;
2136 if llvm::LLVMStartMultithreaded() != 1 {
2137 // use an extra bool to make sure that all future usage of LLVM
2138 // cannot proceed despite the Once not running more than once.
2144 tcx.sess.bug("couldn't enable multi-threaded LLVM");
2148 let link_meta = link::build_link_meta(&krate,
2149 output.out_filestem.as_slice());
2151 // Append ".rs" to crate name as LLVM module identifier.
2153 // LLVM code generator emits a ".file filename" directive
2154 // for ELF backends. Value of the "filename" is set as the
2155 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2156 // crashes if the module identifer is same as other symbols
2157 // such as a function name in the module.
2158 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2159 let mut llmod_id = link_meta.crateid.name.clone();
2160 llmod_id.push_str(".rs");
2162 let ccx = CrateContext::new(llmod_id.as_slice(), tcx, exp_map2,
2163 Sha256::new(), link_meta, reachable);
2165 let _icx = push_ctxt("text");
2166 trans_mod(&ccx, &krate.module);
2169 glue::emit_tydescs(&ccx);
2170 if ccx.sess().opts.debuginfo != NoDebugInfo {
2171 debuginfo::finalize(&ccx);
2174 // Translate the metadata.
2175 let metadata = write_metadata(&ccx, &krate);
2176 if ccx.sess().trans_stats() {
2177 println!("--- trans stats ---");
2178 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2179 println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2180 println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2181 println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2183 println!("n_fns: {}", ccx.stats.n_fns.get());
2184 println!("n_monos: {}", ccx.stats.n_monos.get());
2185 println!("n_inlines: {}", ccx.stats.n_inlines.get());
2186 println!("n_closures: {}", ccx.stats.n_closures.get());
2187 println!("fn stats:");
2188 ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2189 insns_b.cmp(&insns_a)
2191 for tuple in ccx.stats.fn_stats.borrow().iter() {
2193 (ref name, ms, insns) => {
2194 println!("{} insns, {} ms, {}", insns, ms, *name);
2199 if ccx.sess().count_llvm_insns() {
2200 for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2201 println!("{:7u} {}", *v, *k);
2205 let llcx = ccx.llcx;
2206 let link_meta = ccx.link_meta.clone();
2207 let llmod = ccx.llmod;
2209 let mut reachable: Vec<StrBuf> = ccx.reachable.iter().filter_map(|id| {
2210 ccx.item_symbols.borrow().find(id).map(|s| s.to_strbuf())
2213 // Make sure that some other crucial symbols are not eliminated from the
2214 // module. This includes the main function, the crate map (used for debug
2215 // log settings and I/O), and finally the curious rust_stack_exhausted
2216 // symbol. This symbol is required for use by the libmorestack library that
2217 // we link in, so we must ensure that this symbol is not internalized (if
2218 // defined in the crate).
2219 reachable.push("main".to_strbuf());
2220 reachable.push("rust_stack_exhausted".to_strbuf());
2222 // referenced from .eh_frame section on some platforms
2223 reachable.push("rust_eh_personality".to_strbuf());
2224 // referenced from rt/rust_try.ll
2225 reachable.push("rust_eh_personality_catch".to_strbuf());
2227 let metadata_module = ccx.metadata_llmod;
2228 let formats = ccx.tcx.dependency_formats.borrow().clone();
2230 (ccx.tcx, CrateTranslation {
2234 metadata_module: metadata_module,
2236 reachable: reachable,
2237 crate_formats: formats,