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::session::{Session, NoDebugInfo, FullDebugInfo};
32 use driver::driver::OutputFilenames;
33 use driver::driver::{CrateAnalysis, CrateTranslation};
34 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
35 use lib::llvm::{llvm, Vector};
37 use metadata::{csearch, encoder};
38 use middle::astencode;
39 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
40 use middle::trans::_match;
41 use middle::trans::adt;
42 use middle::trans::build::*;
43 use middle::trans::builder::{Builder, noname};
44 use middle::trans::callee;
45 use middle::trans::cleanup;
46 use middle::trans::cleanup::CleanupMethods;
47 use middle::trans::common::*;
48 use middle::trans::consts;
49 use middle::trans::controlflow;
50 use middle::trans::datum;
51 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
52 use middle::trans::debuginfo;
53 use middle::trans::expr;
54 use middle::trans::foreign;
55 use middle::trans::glue;
56 use middle::trans::inline;
57 use middle::trans::machine;
58 use middle::trans::machine::{llalign_of_min, llsize_of};
59 use middle::trans::meth;
60 use middle::trans::monomorphize;
61 use middle::trans::tvec;
62 use middle::trans::type_::Type;
63 use middle::trans::type_of;
64 use middle::trans::type_of::*;
65 use middle::trans::value::Value;
68 use util::common::indenter;
69 use util::ppaux::{Repr, ty_to_str};
70 use util::sha2::Sha256;
71 use util::nodemap::NodeMap;
73 use arena::TypedArena;
75 use std::c_str::ToCStr;
76 use std::cell::{Cell, RefCell};
78 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic};
79 use syntax::ast_util::{local_def, is_local};
80 use syntax::attr::AttrMetaMethods;
82 use syntax::codemap::Span;
83 use syntax::parse::token::InternedString;
84 use syntax::visit::Visitor;
86 use syntax::{ast, ast_util, ast_map};
90 local_data_key!(task_local_insn_key: Vec<&'static str> )
92 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
93 local_data::get(task_local_insn_key, |c| {
95 Some(ctx) => blk(ctx.as_slice()),
101 pub fn init_insn_ctxt() {
102 local_data::set(task_local_insn_key, Vec::new());
105 pub struct _InsnCtxt { _x: () }
108 impl Drop for _InsnCtxt {
110 local_data::modify(task_local_insn_key, |c| {
119 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
120 debug!("new InsnCtxt: {}", s);
121 local_data::modify(task_local_insn_key, |c| {
130 pub struct StatRecorder<'a> {
131 ccx: &'a CrateContext,
137 impl<'a> StatRecorder<'a> {
138 pub fn new(ccx: &'a CrateContext, name: ~str) -> StatRecorder<'a> {
139 let start = if ccx.sess().trans_stats() {
140 time::precise_time_ns()
144 let istart = ccx.stats.n_llvm_insns.get();
155 impl<'a> Drop for StatRecorder<'a> {
157 if self.ccx.sess().trans_stats() {
158 let end = time::precise_time_ns();
159 let elapsed = ((end - self.start) / 1_000_000) as uint;
160 let iend = self.ccx.stats.n_llvm_insns.get();
161 self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
163 iend - self.istart));
164 self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
165 // Reset LLVM insn count to avoid compound costs.
166 self.ccx.stats.n_llvm_insns.set(self.istart);
171 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
172 fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv,
173 ty: Type, output: ty::t) -> ValueRef {
174 let llfn: ValueRef = name.with_c_str(|buf| {
176 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
180 match ty::get(output).sty {
181 // functions returning bottom may unwind, but can never return normally
184 llvm::LLVMAddFunctionAttr(llfn, lib::llvm::NoReturnAttribute as c_uint)
187 // `~` pointer return values never alias because ownership is transferred
188 // FIXME #6750 ~Trait cannot be directly marked as
189 // noalias because the actual object pointer is nested.
190 ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
191 ty::ty_vec(_, ty::VstoreUniq) | ty::ty_str(ty::VstoreUniq) => {
193 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
199 lib::llvm::SetFunctionCallConv(llfn, cc);
200 // Function addresses in Rust are never significant, allowing functions to be merged.
201 lib::llvm::SetUnnamedAddr(llfn, true);
206 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
207 pub fn decl_cdecl_fn(llmod: ModuleRef,
210 output: ty::t) -> ValueRef {
211 decl_fn(llmod, name, lib::llvm::CCallConv, ty, output)
214 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
215 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef,
216 name: &str, cc: lib::llvm::CallConv,
217 ty: Type, output: ty::t) -> ValueRef {
218 match externs.find_equiv(&name) {
219 Some(n) => return *n,
222 let f = decl_fn(llmod, name, cc, ty, output);
223 externs.insert(name.to_owned(), f);
227 fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
228 name: &str, did: ast::DefId) -> ValueRef {
229 match ccx.externs.borrow().find_equiv(&name) {
230 Some(n) => return *n,
234 let f = decl_rust_fn(ccx, false, inputs, output, name);
235 csearch::get_item_attrs(&ccx.sess().cstore, did, |meta_items| {
236 set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).collect::<~[_]>(), f)
239 ccx.externs.borrow_mut().insert(name.to_owned(), f);
243 pub fn decl_rust_fn(ccx: &CrateContext, has_env: bool,
244 inputs: &[ty::t], output: ty::t,
245 name: &str) -> ValueRef {
246 use middle::ty::{BrAnon, ReLateBound};
248 let llfty = type_of_rust_fn(ccx, has_env, inputs, output);
249 let llfn = decl_cdecl_fn(ccx.llmod, name, llfty, output);
251 let uses_outptr = type_of::return_uses_outptr(ccx, output);
252 let offset = if uses_outptr { 1 } else { 0 };
253 let offset = if has_env { offset + 1 } else { offset };
255 for (i, &arg_ty) in inputs.iter().enumerate() {
256 let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
257 match ty::get(arg_ty).sty {
258 // `~` pointer parameters never alias because ownership is transferred
259 // FIXME #6750 ~Trait cannot be directly marked as
260 // noalias because the actual object pointer is nested.
261 ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
262 ty::ty_vec(_, ty::VstoreUniq) | ty::ty_str(ty::VstoreUniq) |
263 ty::ty_closure(~ty::ClosureTy {store: ty::UniqTraitStore, ..}) => {
265 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
268 // When a reference in an argument has no named lifetime, it's
269 // impossible for that reference to escape this function(ie, be
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_owned(), 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>,
355 let _icx = push_ctxt("malloc_raw_exchange");
359 let r = callee::trans_lang_call(bcx,
360 require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
364 let llty_ptr = type_of::type_of(ccx, ptr_ty);
365 rslt(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
368 pub fn malloc_raw_dyn_managed<'a>(
374 let _icx = push_ctxt("malloc_raw_managed");
377 let langcall = require_alloc_fn(bcx, t, alloc_fn);
379 // Grab the TypeRef type of box_ptr_ty.
380 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
381 let llty = type_of(ccx, box_ptr_ty);
382 let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
385 let drop_glue = glue::get_drop_glue(ccx, t);
386 let r = callee::trans_lang_call(
390 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
395 rslt(r.bcx, PointerCast(r.bcx, r.val, llty))
398 // Type descriptor and type glue stuff
400 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> @tydesc_info {
401 match ccx.tydescs.borrow().find(&t) {
402 Some(&inf) => return inf,
406 ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
407 let inf = glue::declare_tydesc(ccx, t);
409 ccx.tydescs.borrow_mut().insert(t, inf);
413 #[allow(dead_code)] // useful
414 pub fn set_optimize_for_size(f: ValueRef) {
415 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
418 pub fn set_no_inline(f: ValueRef) {
419 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
422 #[allow(dead_code)] // useful
423 pub fn set_no_unwind(f: ValueRef) {
424 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
427 // Tell LLVM to emit the information necessary to unwind the stack for the
429 pub fn set_uwtable(f: ValueRef) {
430 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
433 pub fn set_inline_hint(f: ValueRef) {
434 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
437 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
439 // Set the inline hint if there is one
440 match find_inline_attr(attrs) {
441 InlineHint => set_inline_hint(llfn),
442 InlineAlways => set_always_inline(llfn),
443 InlineNever => set_no_inline(llfn),
444 InlineNone => { /* fallthrough */ }
447 // Add the no-split-stack attribute if requested
448 if contains_name(attrs, "no_split_stack") {
449 set_no_split_stack(llfn);
452 if contains_name(attrs, "cold") {
453 unsafe { llvm::LLVMAddColdAttribute(llfn) }
457 pub fn set_always_inline(f: ValueRef) {
458 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
461 pub fn set_no_split_stack(f: ValueRef) {
462 "no-split-stack".with_c_str(|buf| {
463 unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
467 // Double-check that we never ask LLVM to declare the same symbol twice. It
468 // silently mangles such symbols, breaking our linkage model.
469 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) {
470 if ccx.all_llvm_symbols.borrow().contains(&sym) {
471 ccx.sess().bug(~"duplicate LLVM symbol: " + sym);
473 ccx.all_llvm_symbols.borrow_mut().insert(sym);
477 pub fn get_res_dtor(ccx: &CrateContext,
479 parent_id: ast::DefId,
482 let _icx = push_ctxt("trans_res_dtor");
483 let did = if did.krate != ast::LOCAL_CRATE {
484 inline::maybe_instantiate_inline(ccx, did)
488 if !substs.is_empty() {
489 assert_eq!(did.krate, ast::LOCAL_CRATE);
490 let tsubsts = ty::substs {
491 regions: ty::ErasedRegions,
493 tps: Vec::from_slice(substs),
496 let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, &tsubsts);
497 let (val, _) = monomorphize::monomorphic_fn(ccx, did, &tsubsts, vtables, None, None);
500 } else if did.krate == ast::LOCAL_CRATE {
501 get_item_val(ccx, did.node)
504 let name = csearch::get_symbol(&ccx.sess().cstore, did);
505 let class_ty = ty::subst_tps(tcx,
508 ty::lookup_item_type(tcx, parent_id).ty);
509 let llty = type_of_dtor(ccx, class_ty);
511 get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod, name,
512 lib::llvm::CCallConv, llty, ty::mk_nil())
516 // Structural comparison: a rather involved form of glue.
517 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
518 if cx.sess().opts.cg.save_temps {
521 llvm::LLVMSetValueName(v, buf)
528 // Used only for creating scalar comparison glue.
529 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
531 // NB: This produces an i1, not a Rust bool (i8).
532 pub fn compare_scalar_types<'a>(
539 let f = |a| rslt(cx, compare_scalar_values(cx, lhs, rhs, a, op));
541 match ty::get(t).sty {
542 ty::ty_nil => f(nil_type),
543 ty::ty_bool | ty::ty_ptr(_) |
544 ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
545 ty::ty_int(_) => f(signed_int),
546 ty::ty_float(_) => f(floating_point),
547 // Should never get here, because t is scalar.
548 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
553 // A helper function to do the actual comparison of scalar values.
554 pub fn compare_scalar_values<'a>(
561 let _icx = push_ctxt("compare_scalar_values");
562 fn die(cx: &Block) -> ! {
563 cx.sess().bug("compare_scalar_values: must be a comparison operator");
567 // We don't need to do actual comparisons for nil.
568 // () == () holds but () < () does not.
570 ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(cx.ccx(), true),
571 ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(cx.ccx(), false),
572 // refinements would be nice
578 ast::BiEq => lib::llvm::RealOEQ,
579 ast::BiNe => lib::llvm::RealUNE,
580 ast::BiLt => lib::llvm::RealOLT,
581 ast::BiLe => lib::llvm::RealOLE,
582 ast::BiGt => lib::llvm::RealOGT,
583 ast::BiGe => lib::llvm::RealOGE,
586 return FCmp(cx, cmp, lhs, rhs);
590 ast::BiEq => lib::llvm::IntEQ,
591 ast::BiNe => lib::llvm::IntNE,
592 ast::BiLt => lib::llvm::IntSLT,
593 ast::BiLe => lib::llvm::IntSLE,
594 ast::BiGt => lib::llvm::IntSGT,
595 ast::BiGe => lib::llvm::IntSGE,
598 return ICmp(cx, cmp, lhs, rhs);
602 ast::BiEq => lib::llvm::IntEQ,
603 ast::BiNe => lib::llvm::IntNE,
604 ast::BiLt => lib::llvm::IntULT,
605 ast::BiLe => lib::llvm::IntULE,
606 ast::BiGt => lib::llvm::IntUGT,
607 ast::BiGe => lib::llvm::IntUGE,
610 return ICmp(cx, cmp, lhs, rhs);
615 pub type val_and_ty_fn<'r,'b> =
616 |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
618 // Iterates through the elements of a structural type.
619 pub fn iter_structural_ty<'r,
624 f: val_and_ty_fn<'r,'b>)
626 let _icx = push_ctxt("iter_structural_ty");
633 variant: @ty::VariantInfo,
635 f: val_and_ty_fn<'r,'b>)
637 let _icx = push_ctxt("iter_variant");
641 for (i, &arg) in variant.args.iter().enumerate() {
643 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
644 ty::subst_tps(tcx, tps, None, arg));
650 match ty::get(t).sty {
651 ty::ty_struct(..) => {
652 let repr = adt::represent_type(cx.ccx(), t);
653 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
654 for (i, field_ty) in field_tys.iter().enumerate() {
655 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
656 cx = f(cx, llfld_a, field_ty.mt.ty);
660 ty::ty_str(ty::VstoreFixed(n)) |
661 ty::ty_vec(_, ty::VstoreFixed(n)) => {
662 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
663 let (base, len) = tvec::get_fixed_base_and_byte_len(cx, av, unit_ty, n);
664 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
666 ty::ty_tup(ref args) => {
667 let repr = adt::represent_type(cx.ccx(), t);
668 for (i, arg) in args.iter().enumerate() {
669 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
670 cx = f(cx, llfld_a, *arg);
673 ty::ty_enum(tid, ref substs) => {
677 let repr = adt::represent_type(ccx, t);
678 let variants = ty::enum_variants(ccx.tcx(), tid);
679 let n_variants = (*variants).len();
681 // NB: we must hit the discriminant first so that structural
682 // comparison know not to proceed when the discriminants differ.
684 match adt::trans_switch(cx, repr, av) {
685 (_match::single, None) => {
686 cx = iter_variant(cx, repr, av, *variants.get(0),
687 substs.tps.as_slice(), f);
689 (_match::switch, Some(lldiscrim_a)) => {
690 cx = f(cx, lldiscrim_a, ty::mk_int());
691 let unr_cx = fcx.new_temp_block("enum-iter-unr");
693 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
695 let next_cx = fcx.new_temp_block("enum-iter-next");
697 for variant in (*variants).iter() {
699 fcx.new_temp_block(~"enum-iter-variant-" +
700 variant.disr_val.to_str());
701 match adt::trans_case(cx, repr, variant.disr_val) {
702 _match::single_result(r) => {
703 AddCase(llswitch, r.val, variant_cx.llbb)
705 _ => ccx.sess().unimpl("value from adt::trans_case \
706 in iter_structural_ty")
709 iter_variant(variant_cx,
713 substs.tps.as_slice(),
715 Br(variant_cx, next_cx.llbb);
719 _ => ccx.sess().unimpl("value from adt::trans_switch \
720 in iter_structural_ty")
723 _ => cx.sess().unimpl("type in iter_structural_ty")
728 pub fn cast_shift_expr_rhs<'a>(
734 cast_shift_rhs(op, lhs, rhs,
735 |a,b| Trunc(cx, a, b),
736 |a,b| ZExt(cx, a, b))
739 pub fn cast_shift_const_rhs(op: ast::BinOp,
740 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
741 cast_shift_rhs(op, lhs, rhs,
742 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
743 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
746 pub fn cast_shift_rhs(op: ast::BinOp,
749 trunc: |ValueRef, Type| -> ValueRef,
750 zext: |ValueRef, Type| -> ValueRef)
752 // Shifts may have any size int on the rhs
754 if ast_util::is_shift_binop(op) {
755 let mut rhs_llty = val_ty(rhs);
756 let mut lhs_llty = val_ty(lhs);
757 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
758 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
759 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
760 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
763 } else if lhs_sz > rhs_sz {
764 // FIXME (#1877: If shifting by negative
765 // values becomes not undefined then this is wrong.
776 pub fn fail_if_zero<'a>(
783 let text = if divrem == ast::BiDiv {
784 "attempted to divide by zero"
786 "attempted remainder with a divisor of zero"
788 let is_zero = match ty::get(rhs_t).sty {
790 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
791 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
794 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
795 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
798 cx.sess().bug(~"fail-if-zero on unexpected type: " +
799 ty_to_str(cx.tcx(), rhs_t));
802 with_cond(cx, is_zero, |bcx| {
803 controlflow::trans_fail(bcx, span, InternedString::new(text))
807 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
808 let name = csearch::get_symbol(&ccx.sess().cstore, did);
809 match ty::get(t).sty {
810 ty::ty_bare_fn(ref fn_ty) => {
811 match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
812 ccx.sess().targ_cfg.arch) {
813 Some(Rust) | Some(RustIntrinsic) => {
814 get_extern_rust_fn(ccx,
815 fn_ty.sig.inputs.as_slice(),
821 let c = foreign::llvm_calling_convention(ccx, fn_ty.abi);
822 let cconv = c.unwrap_or(lib::llvm::CCallConv);
823 let llty = type_of_fn_from_ty(ccx, t);
824 get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod,
825 name, cconv, llty, fn_ty.sig.output)
829 ty::ty_closure(ref f) => {
830 get_extern_rust_fn(ccx,
831 f.sig.inputs.as_slice(),
837 let llty = type_of(ccx, t);
838 get_extern_const(&mut *ccx.externs.borrow_mut(), ccx.llmod, name,
847 llargs: Vec<ValueRef> ,
848 attributes: &[(uint, lib::llvm::Attribute)],
849 call_info: Option<NodeInfo>)
850 -> (ValueRef, &'a Block<'a>) {
851 let _icx = push_ctxt("invoke_");
852 if bcx.unreachable.get() {
853 return (C_null(Type::i8(bcx.ccx())), bcx);
856 match bcx.opt_node_id {
858 debug!("invoke at ???");
861 debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
865 if need_invoke(bcx) {
866 debug!("invoking {} at {}", llfn, bcx.llbb);
867 for &llarg in llargs.iter() {
868 debug!("arg: {}", llarg);
870 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
871 let landing_pad = bcx.fcx.get_landing_pad();
874 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
875 None => debuginfo::clear_source_location(bcx.fcx)
878 let llresult = Invoke(bcx,
884 return (llresult, normal_bcx);
886 debug!("calling {} at {}", llfn, bcx.llbb);
887 for &llarg in llargs.iter() {
888 debug!("arg: {}", llarg);
892 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
893 None => debuginfo::clear_source_location(bcx.fcx)
896 let llresult = Call(bcx, llfn, llargs.as_slice(), attributes);
897 return (llresult, bcx);
901 pub fn need_invoke(bcx: &Block) -> bool {
902 if bcx.sess().no_landing_pads() {
906 // Avoid using invoke if we are already inside a landing pad.
911 bcx.fcx.needs_invoke()
914 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
915 let _icx = push_ctxt("load_if_immediate");
916 if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
920 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
921 match local.pat.node {
922 ast::PatWild => true, _ => false
926 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
929 debug!("init_local(bcx={}, local.id={:?})",
930 bcx.to_str(), local.id);
931 let _indenter = indenter();
933 let _icx = push_ctxt("init_local");
935 if ignore_lhs(bcx, local) {
936 // Handle let _ = e; just like e;
939 return controlflow::trans_stmt_semi(bcx, init)
941 None => { return bcx; }
945 _match::store_local(bcx, local)
948 pub fn raw_block<'a>(
949 fcx: &'a FunctionContext<'a>,
953 Block::new(llbb, is_lpad, None, fcx)
956 pub fn with_cond<'a>(
959 f: |&'a Block<'a>| -> &'a Block<'a>)
961 let _icx = push_ctxt("with_cond");
963 let next_cx = fcx.new_temp_block("next");
964 let cond_cx = fcx.new_temp_block("cond");
965 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
966 let after_cx = f(cond_cx);
967 if !after_cx.terminated.get() {
968 Br(after_cx, next_cx.llbb);
973 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
974 let _icx = push_ctxt("call_memcpy");
976 let key = match ccx.sess().targ_cfg.arch {
977 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
978 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
980 let memcpy = ccx.get_intrinsic(&key);
981 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
982 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
983 let size = IntCast(cx, n_bytes, ccx.int_type);
984 let align = C_i32(ccx, align as i32);
985 let volatile = C_i1(ccx, false);
986 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
989 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
990 let _icx = push_ctxt("memcpy_ty");
992 if ty::type_is_structural(t) {
993 let llty = type_of::type_of(ccx, t);
994 let llsz = llsize_of(ccx, llty);
995 let llalign = llalign_of_min(ccx, llty);
996 call_memcpy(bcx, dst, src, llsz, llalign as u32);
998 Store(bcx, Load(bcx, src), dst);
1002 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1003 if cx.unreachable.get() { return; }
1004 let _icx = push_ctxt("zero_mem");
1007 let llty = type_of::type_of(ccx, t);
1008 memzero(&B(bcx), llptr, llty);
1011 // Always use this function instead of storing a zero constant to the memory
1012 // in question. If you store a zero constant, LLVM will drown in vreg
1013 // allocation for large data structures, and the generated code will be
1014 // awful. (A telltale sign of this is large quantities of
1015 // `mov [byte ptr foo],0` in the generated code.)
1016 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1017 let _icx = push_ctxt("memzero");
1020 let intrinsic_key = match ccx.sess().targ_cfg.arch {
1021 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1022 X86_64 => "llvm.memset.p0i8.i64"
1025 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1026 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1027 let llzeroval = C_u8(ccx, 0);
1028 let size = machine::llsize_of(ccx, ty);
1029 let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1030 let volatile = C_i1(ccx, false);
1031 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1034 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1035 let _icx = push_ctxt("alloc_ty");
1036 let ccx = bcx.ccx();
1037 let ty = type_of::type_of(ccx, t);
1038 assert!(!ty::type_has_params(t));
1039 let val = alloca(bcx, ty, name);
1043 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1044 alloca_maybe_zeroed(cx, ty, name, false)
1047 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1048 let _icx = push_ctxt("alloca");
1049 if cx.unreachable.get() {
1051 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1054 debuginfo::clear_source_location(cx.fcx);
1055 let p = Alloca(cx, ty, name);
1057 let b = cx.fcx.ccx.builder();
1058 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1064 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1065 let _icx = push_ctxt("arrayalloca");
1066 if cx.unreachable.get() {
1068 return llvm::LLVMGetUndef(ty.to_ref());
1071 debuginfo::clear_source_location(cx.fcx);
1072 return ArrayAlloca(cx, ty, v);
1075 // Creates and returns space for, or returns the argument representing, the
1076 // slot where the return value of the function must go.
1077 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1080 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1081 llvm::LLVMGetParam(fcx.llfn, 0)
1083 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1084 let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1085 Alloca(bcx, lloutputtype, "__make_return_pointer")
1090 // NB: must keep 4 fns in sync:
1093 // - create_datums_for_fn_args.
1097 // Be warned! You must call `init_function` before doing anything with the
1098 // returned function context.
1099 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1104 param_substs: Option<@param_substs>,
1106 block_arena: &'a TypedArena<Block<'a>>)
1107 -> FunctionContext<'a> {
1108 for p in param_substs.iter() { p.validate(); }
1110 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1111 if id == -1 { ~"" } else { ccx.tcx.map.path_to_str(id) },
1112 id, param_substs.repr(ccx.tcx()));
1114 let substd_output_type = match param_substs {
1115 None => output_type,
1117 ty::subst_tps(ccx.tcx(),
1118 substs.tys.as_slice(),
1123 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1124 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1126 let mut fcx = FunctionContext {
1129 llretptr: Cell::new(None),
1130 entry_bcx: RefCell::new(None),
1131 alloca_insert_pt: Cell::new(None),
1132 llreturn: Cell::new(None),
1133 personality: Cell::new(None),
1134 caller_expects_out_pointer: uses_outptr,
1135 llargs: RefCell::new(NodeMap::new()),
1136 lllocals: RefCell::new(NodeMap::new()),
1137 llupvars: RefCell::new(NodeMap::new()),
1139 param_substs: param_substs,
1141 block_arena: block_arena,
1143 debug_context: debug_context,
1144 scopes: RefCell::new(Vec::new())
1148 fcx.llenv = Some(unsafe {
1149 llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1156 /// Performs setup on a newly created function, creating the entry scope block
1157 /// and allocating space for the return pointer.
1158 pub fn init_function<'a>(
1159 fcx: &'a FunctionContext<'a>,
1162 param_substs: Option<@param_substs>) {
1163 let entry_bcx = fcx.new_temp_block("entry-block");
1165 *fcx.entry_bcx.borrow_mut() = Some(entry_bcx);
1167 // Use a dummy instruction as the insertion point for all allocas.
1168 // This is later removed in FunctionContext::cleanup.
1169 fcx.alloca_insert_pt.set(Some(unsafe {
1170 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1171 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1174 let substd_output_type = match param_substs {
1175 None => output_type,
1177 ty::subst_tps(fcx.ccx.tcx(),
1178 substs.tys.as_slice(),
1184 if !return_type_is_void(fcx.ccx, substd_output_type) {
1185 // If the function returns nil/bot, there is no real return
1186 // value, so do not set `llretptr`.
1187 if !skip_retptr || fcx.caller_expects_out_pointer {
1188 // Otherwise, we normally allocate the llretptr, unless we
1189 // have been instructed to skip it for immediate return
1191 fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1196 // NB: must keep 4 fns in sync:
1199 // - create_datums_for_fn_args.
1203 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1204 use middle::trans::datum::{ByRef, ByValue};
1207 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1211 // work around bizarre resolve errors
1212 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1213 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1215 // create_datums_for_fn_args: creates rvalue datums for each of the
1216 // incoming function arguments. These will later be stored into
1217 // appropriate lvalue datums.
1218 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1220 -> Vec<RvalueDatum> {
1221 let _icx = push_ctxt("create_datums_for_fn_args");
1223 // Return an array wrapping the ValueRefs that we get from
1224 // llvm::LLVMGetParam for each argument into datums.
1225 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1226 let llarg = unsafe {
1227 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1229 datum::Datum(llarg, arg_ty, arg_kind(fcx, arg_ty))
1233 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1234 arg_scope: cleanup::CustomScopeIndex,
1237 arg_datums: Vec<RvalueDatum> )
1239 debug!("copy_args_to_allocas");
1241 let _icx = push_ctxt("copy_args_to_allocas");
1244 let arg_scope_id = cleanup::CustomScope(arg_scope);
1246 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1247 // For certain mode/type combinations, the raw llarg values are passed
1248 // by value. However, within the fn body itself, we want to always
1249 // have all locals and arguments be by-ref so that we can cancel the
1250 // cleanup and for better interaction with LLVM's debug info. So, if
1251 // the argument would be passed by value, we store it into an alloca.
1252 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1253 // the event it's not truly needed.
1255 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1257 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1258 debuginfo::create_argument_metadata(bcx, &args[i]);
1265 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1266 // and builds the return block.
1267 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1268 last_bcx: &'a Block<'a>) {
1269 let _icx = push_ctxt("finish_fn");
1271 let ret_cx = match fcx.llreturn.get() {
1273 if !last_bcx.terminated.get() {
1274 Br(last_bcx, llreturn);
1276 raw_block(fcx, false, llreturn)
1280 build_return_block(fcx, ret_cx);
1281 debuginfo::clear_source_location(fcx);
1285 // Builds the return block for a function.
1286 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1287 // Return the value if this function immediate; otherwise, return void.
1288 if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1289 return RetVoid(ret_cx);
1292 let retptr = Value(fcx.llretptr.get().unwrap());
1293 let retval = match retptr.get_dominating_store(ret_cx) {
1294 // If there's only a single store to the ret slot, we can directly return
1295 // the value that was stored and omit the store and the alloca
1297 let retval = s.get_operand(0).unwrap().get();
1298 s.erase_from_parent();
1300 if retptr.has_no_uses() {
1301 retptr.erase_from_parent();
1306 // Otherwise, load the return value from the ret slot
1307 None => Load(ret_cx, fcx.llretptr.get().unwrap())
1311 Ret(ret_cx, retval);
1314 // trans_closure: Builds an LLVM function out of a source function.
1315 // If the function closes over its environment a closure will be
1317 pub fn trans_closure(ccx: &CrateContext,
1321 param_substs: Option<@param_substs>,
1323 _attributes: &[ast::Attribute],
1325 maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1326 ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1328 let _icx = push_ctxt("trans_closure");
1329 set_uwtable(llfndecl);
1331 debug!("trans_closure(..., param_substs={})",
1332 param_substs.repr(ccx.tcx()));
1334 let has_env = match ty::get(ty::node_id_to_type(ccx.tcx(), id)).sty {
1335 ty::ty_closure(_) => true,
1339 let arena = TypedArena::new();
1340 let fcx = new_fn_ctxt(ccx,
1348 init_function(&fcx, false, output_type, param_substs);
1350 // cleanup scope for the incoming arguments
1351 let arg_scope = fcx.push_custom_cleanup_scope();
1353 // Create the first basic block in the function and keep a handle on it to
1354 // pass to finish_fn later.
1355 let bcx_top = fcx.entry_bcx.borrow().clone().unwrap();
1356 let mut bcx = bcx_top;
1357 let block_ty = node_id_type(bcx, body.id);
1359 // Set up arguments to the function.
1360 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1361 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1363 bcx = copy_args_to_allocas(&fcx,
1366 decl.inputs.as_slice(),
1369 bcx = maybe_load_env(bcx);
1371 // Up until here, IR instructions for this function have explicitly not been annotated with
1372 // source code location, so we don't step into call setup code. From here on, source location
1373 // emitting should be enabled.
1374 debuginfo::start_emitting_source_locations(&fcx);
1376 let dest = match fcx.llretptr.get() {
1377 Some(e) => {expr::SaveIn(e)}
1379 assert!(type_is_zero_size(bcx.ccx(), block_ty))
1384 // This call to trans_block is the place where we bridge between
1385 // translation calls that don't have a return value (trans_crate,
1386 // trans_mod, trans_item, et cetera) and those that do
1387 // (trans_block, trans_expr, et cetera).
1388 bcx = controlflow::trans_block(bcx, body, dest);
1390 match fcx.llreturn.get() {
1392 Br(bcx, fcx.return_exit_block());
1393 fcx.pop_custom_cleanup_scope(arg_scope);
1396 // Microoptimization writ large: avoid creating a separate
1397 // llreturn basic block
1398 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1402 // Put return block after all other blocks.
1403 // This somewhat improves single-stepping experience in debugger.
1405 let llreturn = fcx.llreturn.get();
1406 for &llreturn in llreturn.iter() {
1407 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1411 // Insert the mandatory first few basic blocks before lltop.
1412 finish_fn(&fcx, bcx);
1415 // trans_fn: creates an LLVM function corresponding to a source language
1417 pub fn trans_fn(ccx: &CrateContext,
1421 param_substs: Option<@param_substs>,
1423 attrs: &[ast::Attribute]) {
1424 let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id));
1425 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1426 let _icx = push_ctxt("trans_fn");
1427 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
1428 trans_closure(ccx, decl, body, llfndecl,
1429 param_substs, id, attrs, output_type, |bcx| bcx);
1432 pub fn trans_enum_variant(ccx: &CrateContext,
1433 _enum_id: ast::NodeId,
1434 variant: &ast::Variant,
1435 _args: &[ast::VariantArg],
1437 param_substs: Option<@param_substs>,
1438 llfndecl: ValueRef) {
1439 let _icx = push_ctxt("trans_enum_variant");
1441 trans_enum_variant_or_tuple_like_struct(
1449 pub fn trans_tuple_struct(ccx: &CrateContext,
1450 _fields: &[ast::StructField],
1451 ctor_id: ast::NodeId,
1452 param_substs: Option<@param_substs>,
1453 llfndecl: ValueRef) {
1454 let _icx = push_ctxt("trans_tuple_struct");
1456 trans_enum_variant_or_tuple_like_struct(
1464 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1465 ctor_id: ast::NodeId,
1467 param_substs: Option<@param_substs>,
1468 llfndecl: ValueRef) {
1469 let no_substs: &[ty::t] = [];
1470 let ty_param_substs = match param_substs {
1471 Some(ref substs) => {
1472 let v: &[ty::t] = substs.tys.as_slice();
1476 let v: &[ty::t] = no_substs;
1481 let ctor_ty = ty::subst_tps(ccx.tcx(),
1484 ty::node_id_to_type(ccx.tcx(), ctor_id));
1486 let result_ty = match ty::get(ctor_ty).sty {
1487 ty::ty_bare_fn(ref bft) => bft.sig.output,
1488 _ => ccx.sess().bug(
1489 format!("trans_enum_variant_or_tuple_like_struct: \
1490 unexpected ctor return type {}",
1491 ty_to_str(ccx.tcx(), ctor_ty)))
1494 let arena = TypedArena::new();
1495 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1496 param_substs, None, &arena);
1497 init_function(&fcx, false, result_ty, param_substs);
1499 let arg_tys = ty::ty_fn_args(ctor_ty);
1501 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1503 let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1505 if !type_is_zero_size(fcx.ccx, result_ty) {
1506 let repr = adt::represent_type(ccx, result_ty);
1507 adt::trans_start_init(bcx, repr, fcx.llretptr.get().unwrap(), disr);
1508 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1509 let lldestptr = adt::trans_field_ptr(bcx,
1511 fcx.llretptr.get().unwrap(),
1514 arg_datum.store_to(bcx, lldestptr);
1518 finish_fn(&fcx, bcx);
1521 pub fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1522 id: ast::NodeId, vi: @Vec<@ty::VariantInfo>,
1524 for &variant in enum_definition.variants.iter() {
1525 let disr_val = vi.get(*i).disr_val;
1528 match variant.node.kind {
1529 ast::TupleVariantKind(ref args) if args.len() > 0 => {
1530 let llfn = get_item_val(ccx, variant.node.id);
1531 trans_enum_variant(ccx, id, variant, args.as_slice(),
1532 disr_val, None, llfn);
1534 ast::TupleVariantKind(_) => {
1537 ast::StructVariantKind(struct_def) => {
1538 trans_struct_def(ccx, struct_def);
1544 pub struct TransItemVisitor<'a> {
1545 pub ccx: &'a CrateContext,
1548 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1549 fn visit_item(&mut self, i: &ast::Item, _:()) {
1550 trans_item(self.ccx, i);
1554 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1555 let _icx = push_ctxt("trans_item");
1557 ast::ItemFn(decl, fn_style, _abi, ref generics, body) => {
1558 if fn_style == ast::ExternFn {
1559 let llfndecl = get_item_val(ccx, item.id);
1560 foreign::trans_rust_fn_with_foreign_abi(
1561 ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
1562 } else if !generics.is_type_parameterized() {
1563 let llfn = get_item_val(ccx, item.id);
1570 item.attrs.as_slice());
1572 // Be sure to travel more than just one layer deep to catch nested
1573 // items in blocks and such.
1574 let mut v = TransItemVisitor{ ccx: ccx };
1575 v.visit_block(body, ());
1578 ast::ItemImpl(ref generics, _, _, ref ms) => {
1579 meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1581 ast::ItemMod(ref m) => {
1584 ast::ItemEnum(ref enum_definition, ref generics) => {
1585 if !generics.is_type_parameterized() {
1586 let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1588 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
1591 ast::ItemStatic(_, m, expr) => {
1592 consts::trans_const(ccx, m, item.id);
1593 // Do static_assert checking. It can't really be done much earlier
1594 // because we need to get the value of the bool out of LLVM
1595 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1596 if m == ast::MutMutable {
1597 ccx.sess().span_fatal(expr.span,
1598 "cannot have static_assert on a mutable \
1602 let v = ccx.const_values.borrow().get_copy(&item.id);
1604 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1605 ccx.sess().span_fatal(expr.span, "static assertion failed");
1610 ast::ItemForeignMod(ref foreign_mod) => {
1611 foreign::trans_foreign_mod(ccx, foreign_mod);
1613 ast::ItemStruct(struct_def, ref generics) => {
1614 if !generics.is_type_parameterized() {
1615 trans_struct_def(ccx, struct_def);
1618 ast::ItemTrait(..) => {
1619 // Inside of this trait definition, we won't be actually translating any
1620 // functions, but the trait still needs to be walked. Otherwise default
1621 // methods with items will not get translated and will cause ICE's when
1622 // metadata time comes around.
1623 let mut v = TransItemVisitor{ ccx: ccx };
1624 visit::walk_item(&mut v, item, ());
1626 _ => {/* fall through */ }
1630 pub fn trans_struct_def(ccx: &CrateContext, struct_def: @ast::StructDef) {
1631 // If this is a tuple-like struct, translate the constructor.
1632 match struct_def.ctor_id {
1633 // We only need to translate a constructor if there are fields;
1634 // otherwise this is a unit-like struct.
1635 Some(ctor_id) if struct_def.fields.len() > 0 => {
1636 let llfndecl = get_item_val(ccx, ctor_id);
1637 trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1638 ctor_id, None, llfndecl);
1640 Some(_) | None => {}
1644 // Translate a module. Doing this amounts to translating the items in the
1645 // module; there ends up being no artifact (aside from linkage names) of
1646 // separate modules in the compiled program. That's because modules exist
1647 // only as a convenience for humans working with the code, to organize names
1648 // and control visibility.
1649 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1650 let _icx = push_ctxt("trans_mod");
1651 for item in m.items.iter() {
1652 trans_item(ccx, *item);
1656 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: ~str, node_id: ast::NodeId,
1658 ccx.item_symbols.borrow_mut().insert(node_id, sym);
1660 if !ccx.reachable.contains(&node_id) {
1661 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1664 if is_entry_fn(ccx.sess(), node_id) && !ccx.sess().building_library.get() {
1665 create_entry_wrapper(ccx, sp, llfn);
1669 fn register_fn(ccx: &CrateContext,
1672 node_id: ast::NodeId,
1675 let f = match ty::get(node_type).sty {
1676 ty::ty_bare_fn(ref f) => {
1677 assert!(f.abi == Rust || f.abi == RustIntrinsic);
1680 _ => fail!("expected bare rust fn or an intrinsic")
1683 let llfn = decl_rust_fn(ccx,
1685 f.sig.inputs.as_slice(),
1688 finish_register_fn(ccx, sp, sym, node_id, llfn);
1692 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1693 pub fn register_fn_llvmty(ccx: &CrateContext,
1696 node_id: ast::NodeId,
1697 cc: lib::llvm::CallConv,
1699 output: ty::t) -> ValueRef {
1700 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1702 let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty, output);
1703 finish_register_fn(ccx, sp, sym, node_id, llfn);
1707 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1708 match *sess.entry_fn.borrow() {
1709 Some((entry_id, _)) => node_id == entry_id,
1714 // Create a _rust_main(args: ~[str]) function which will be called from the
1715 // runtime rust_start function
1716 pub fn create_entry_wrapper(ccx: &CrateContext,
1718 main_llfn: ValueRef) {
1719 let et = ccx.sess().entry_type.get().unwrap();
1721 session::EntryMain => {
1722 create_entry_fn(ccx, main_llfn, true);
1724 session::EntryStart => create_entry_fn(ccx, main_llfn, false),
1725 session::EntryNone => {} // Do nothing.
1728 fn create_entry_fn(ccx: &CrateContext,
1729 rust_main: ValueRef,
1730 use_start_lang_item: bool) {
1731 let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
1734 let llfn = decl_cdecl_fn(ccx.llmod, "main", llfty, ty::mk_nil());
1735 let llbb = "top".with_c_str(|buf| {
1737 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1740 let bld = ccx.builder.b;
1742 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1744 let (start_fn, args) = if use_start_lang_item {
1745 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1747 Err(s) => { ccx.sess().fatal(s); }
1749 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1750 get_item_val(ccx, start_def_id.node)
1752 let start_fn_type = csearch::get_type(ccx.tcx(),
1754 trans_external_path(ccx, start_def_id, start_fn_type)
1758 let opaque_rust_main = "rust_main".with_c_str(|buf| {
1759 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
1764 llvm::LLVMGetParam(llfn, 0),
1765 llvm::LLVMGetParam(llfn, 1)
1770 debug!("using user-defined start fn");
1772 llvm::LLVMGetParam(llfn, 0 as c_uint),
1773 llvm::LLVMGetParam(llfn, 1 as c_uint)
1779 let result = llvm::LLVMBuildCall(bld,
1782 args.len() as c_uint,
1785 llvm::LLVMBuildRet(bld, result);
1790 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1791 ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
1792 match attr::first_attr_value_str_by_name(attrs, "export_name") {
1793 // Use provided name
1794 Some(name) => name.get().to_owned(),
1796 _ => ccx.tcx.map.with_path(id, |mut path| {
1797 if attr::contains_name(attrs, "no_mangle") {
1799 path.last().unwrap().to_str()
1801 // Usual name mangling
1802 mangle_exported_name(ccx, path, ty, id)
1808 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
1809 debug!("get_item_val(id=`{:?}`)", id);
1811 match ccx.item_vals.borrow().find_copy(&id) {
1812 Some(v) => return v,
1816 let mut foreign = false;
1817 let item = ccx.tcx.map.get(id);
1818 let val = match item {
1819 ast_map::NodeItem(i) => {
1820 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
1821 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1823 let v = match i.node {
1824 ast::ItemStatic(_, _, expr) => {
1825 // If this static came from an external crate, then
1826 // we need to get the symbol from csearch instead of
1827 // using the current crate's name/version
1828 // information in the hash of the symbol
1829 debug!("making {}", sym);
1830 let (sym, is_local) = {
1831 match ccx.external_srcs.borrow().find(&i.id) {
1833 debug!("but found in other crate...");
1834 (csearch::get_symbol(&ccx.sess().cstore,
1841 // We need the translated value here, because for enums the
1842 // LLVM type is not fully determined by the Rust type.
1843 let (v, inlineable) = consts::const_expr(ccx, expr, is_local);
1844 ccx.const_values.borrow_mut().insert(id, v);
1845 let mut inlineable = inlineable;
1848 let llty = llvm::LLVMTypeOf(v);
1849 let g = sym.with_c_str(|buf| {
1850 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
1853 if !ccx.reachable.contains(&id) {
1854 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
1857 // Apply the `unnamed_addr` attribute if
1859 if attr::contains_name(i.attrs.as_slice(),
1860 "address_insignificant") {
1861 if ccx.reachable.contains(&id) {
1862 ccx.sess().span_bug(i.span,
1863 "insignificant static is reachable");
1865 lib::llvm::SetUnnamedAddr(g, true);
1867 // This is a curious case where we must make
1868 // all of these statics inlineable. If a
1869 // global is tagged as
1870 // address_insignificant, then LLVM won't
1871 // coalesce globals unless they have an
1872 // internal linkage type. This means that
1873 // external crates cannot use this global.
1874 // This is a problem for things like inner
1875 // statics in generic functions, because the
1876 // function will be inlined into another
1877 // crate and then attempt to link to the
1878 // static in the original crate, only to
1879 // find that it's not there. On the other
1880 // side of inlininig, the crates knows to
1881 // not declare this static as
1882 // available_externally (because it isn't)
1886 if attr::contains_name(i.attrs.as_slice(),
1888 lib::llvm::set_thread_local(g, true);
1892 debug!("{} not inlined", sym);
1893 ccx.non_inlineable_statics.borrow_mut()
1897 ccx.item_symbols.borrow_mut().insert(i.id, sym);
1902 ast::ItemFn(_, fn_style, _, _, _) => {
1903 let llfn = if fn_style != ast::ExternFn {
1904 register_fn(ccx, i.span, sym, i.id, ty)
1906 foreign::register_rust_fn_with_foreign_abi(ccx,
1911 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
1915 _ => fail!("get_item_val: weird result in table")
1918 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
1920 Some(sect) => unsafe {
1921 sect.get().with_c_str(|buf| {
1922 llvm::LLVMSetSection(v, buf);
1931 ast_map::NodeTraitMethod(trait_method) => {
1932 debug!("get_item_val(): processing a NodeTraitMethod");
1933 match *trait_method {
1934 ast::Required(_) => {
1935 ccx.sess().bug("unexpected variant: required trait method in \
1938 ast::Provided(m) => {
1939 register_method(ccx, id, m)
1944 ast_map::NodeMethod(m) => {
1945 register_method(ccx, id, m)
1948 ast_map::NodeForeignItem(ni) => {
1952 ast::ForeignItemFn(..) => {
1953 let abi = ccx.tcx.map.get_foreign_abi(id);
1954 foreign::register_foreign_item_fn(ccx, abi, ni)
1956 ast::ForeignItemStatic(..) => {
1957 foreign::register_static(ccx, ni)
1962 ast_map::NodeVariant(ref v) => {
1964 let args = match v.node.kind {
1965 ast::TupleVariantKind(ref args) => args,
1966 ast::StructVariantKind(_) => {
1967 fail!("struct variant kind unexpected in get_item_val")
1970 assert!(args.len() != 0u);
1971 let ty = ty::node_id_to_type(ccx.tcx(), id);
1972 let parent = ccx.tcx.map.get_parent(id);
1973 let enm = ccx.tcx.map.expect_item(parent);
1974 let sym = exported_name(ccx,
1977 enm.attrs.as_slice());
1979 llfn = match enm.node {
1980 ast::ItemEnum(_, _) => {
1981 register_fn(ccx, (*v).span, sym, id, ty)
1983 _ => fail!("NodeVariant, shouldn't happen")
1985 set_inline_hint(llfn);
1989 ast_map::NodeStructCtor(struct_def) => {
1990 // Only register the constructor if this is a tuple-like struct.
1991 let ctor_id = match struct_def.ctor_id {
1993 ccx.sess().bug("attempt to register a constructor of \
1994 a non-tuple-like struct")
1996 Some(ctor_id) => ctor_id,
1998 let parent = ccx.tcx.map.get_parent(id);
1999 let struct_item = ccx.tcx.map.expect_item(parent);
2000 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2001 let sym = exported_name(ccx,
2006 let llfn = register_fn(ccx, struct_item.span,
2008 set_inline_hint(llfn);
2013 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2018 // foreign items (extern fns and extern statics) don't have internal
2019 // linkage b/c that doesn't quite make sense. Otherwise items can
2020 // have internal linkage if they're not reachable.
2021 if !foreign && !ccx.reachable.contains(&id) {
2022 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2025 ccx.item_vals.borrow_mut().insert(id, val);
2029 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2030 m: &ast::Method) -> ValueRef {
2031 let mty = ty::node_id_to_type(ccx.tcx(), id);
2033 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2035 let llfn = register_fn(ccx, m.span, sym, id, mty);
2036 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2040 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2042 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2046 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2047 -> encoder::EncodeParams<'r> {
2049 let diag = cx.sess().diagnostic();
2050 let item_symbols = &cx.item_symbols;
2051 let link_meta = &cx.link_meta;
2052 encoder::EncodeParams {
2055 reexports2: cx.exp_map2,
2056 item_symbols: item_symbols,
2057 non_inlineable_statics: &cx.non_inlineable_statics,
2058 link_meta: link_meta,
2059 cstore: &cx.sess().cstore,
2060 encode_inlined_item: ie,
2064 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2067 if !cx.sess().building_library.get() {
2071 let encode_inlined_item: encoder::EncodeInlinedItem =
2072 |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii, &cx.maps);
2074 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2075 let metadata = encoder::encode_metadata(encode_parms, krate);
2076 let compressed = encoder::metadata_encoding_version +
2077 match flate::deflate_bytes(metadata.as_slice()) {
2078 Some(compressed) => compressed,
2079 None => cx.sess().fatal(format!("failed to compress metadata", ))
2081 let llmeta = C_bytes(cx, compressed);
2082 let llconst = C_struct(cx, [llmeta], false);
2083 let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2084 cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2085 let llglobal = name.with_c_str(|buf| {
2087 llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2091 llvm::LLVMSetInitializer(llglobal, llconst);
2092 cx.sess().targ_cfg.target_strs.meta_sect_name.with_c_str(|buf| {
2093 llvm::LLVMSetSection(llglobal, buf)
2099 pub fn trans_crate(krate: ast::Crate,
2100 analysis: CrateAnalysis,
2101 output: &OutputFilenames) -> (ty::ctxt, CrateTranslation) {
2102 let CrateAnalysis { ty_cx: tcx, exp_map2, maps, reachable, .. } = analysis;
2104 // Before we touch LLVM, make sure that multithreading is enabled.
2106 use sync::one::{Once, ONCE_INIT};
2107 static mut INIT: Once = ONCE_INIT;
2108 static mut POISONED: bool = false;
2110 if llvm::LLVMStartMultithreaded() != 1 {
2111 // use an extra bool to make sure that all future usage of LLVM
2112 // cannot proceed despite the Once not running more than once.
2118 tcx.sess.bug("couldn't enable multi-threaded LLVM");
2122 let link_meta = link::build_link_meta(&krate, output.out_filestem);
2124 // Append ".rs" to crate name as LLVM module identifier.
2126 // LLVM code generator emits a ".file filename" directive
2127 // for ELF backends. Value of the "filename" is set as the
2128 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2129 // crashes if the module identifer is same as other symbols
2130 // such as a function name in the module.
2131 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2132 let llmod_id = link_meta.crateid.name + ".rs";
2134 let ccx = CrateContext::new(llmod_id, tcx, exp_map2, maps,
2135 Sha256::new(), link_meta, reachable);
2137 let _icx = push_ctxt("text");
2138 trans_mod(&ccx, &krate.module);
2141 glue::emit_tydescs(&ccx);
2142 if ccx.sess().opts.debuginfo != NoDebugInfo {
2143 debuginfo::finalize(&ccx);
2146 // Translate the metadata.
2147 let metadata = write_metadata(&ccx, &krate);
2148 if ccx.sess().trans_stats() {
2149 println!("--- trans stats ---");
2150 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2151 println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2152 println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2153 println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2155 println!("n_fns: {}", ccx.stats.n_fns.get());
2156 println!("n_monos: {}", ccx.stats.n_monos.get());
2157 println!("n_inlines: {}", ccx.stats.n_inlines.get());
2158 println!("n_closures: {}", ccx.stats.n_closures.get());
2159 println!("fn stats:");
2160 ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2161 insns_b.cmp(&insns_a)
2163 for tuple in ccx.stats.fn_stats.borrow().iter() {
2165 (ref name, ms, insns) => {
2166 println!("{} insns, {} ms, {}", insns, ms, *name);
2171 if ccx.sess().count_llvm_insns() {
2172 for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2173 println!("{:7u} {}", *v, *k);
2177 let llcx = ccx.llcx;
2178 let link_meta = ccx.link_meta.clone();
2179 let llmod = ccx.llmod;
2181 let mut reachable: Vec<~str> = ccx.reachable.iter().filter_map(|id| {
2182 ccx.item_symbols.borrow().find(id).map(|s| s.to_owned())
2185 // Make sure that some other crucial symbols are not eliminated from the
2186 // module. This includes the main function, the crate map (used for debug
2187 // log settings and I/O), and finally the curious rust_stack_exhausted
2188 // symbol. This symbol is required for use by the libmorestack library that
2189 // we link in, so we must ensure that this symbol is not internalized (if
2190 // defined in the crate).
2191 reachable.push(~"main");
2192 reachable.push(~"rust_stack_exhausted");
2193 reachable.push(~"rust_eh_personality"); // referenced from .eh_frame section on some platforms
2194 reachable.push(~"rust_eh_personality_catch"); // referenced from rt/rust_try.ll
2196 let metadata_module = ccx.metadata_llmod;
2198 (ccx.tcx, CrateTranslation {
2202 metadata_module: metadata_module,
2204 reachable: reachable,