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::weak_lang_items;
42 use middle::trans::_match;
43 use middle::trans::adt;
44 use middle::trans::build::*;
45 use middle::trans::builder::{Builder, noname};
46 use middle::trans::callee;
47 use middle::trans::cleanup;
48 use middle::trans::cleanup::CleanupMethods;
49 use middle::trans::common::*;
50 use middle::trans::consts;
51 use middle::trans::controlflow;
52 use middle::trans::datum;
53 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
54 use middle::trans::debuginfo;
55 use middle::trans::expr;
56 use middle::trans::foreign;
57 use middle::trans::glue;
58 use middle::trans::inline;
59 use middle::trans::machine;
60 use middle::trans::machine::{llalign_of_min, llsize_of};
61 use middle::trans::meth;
62 use middle::trans::monomorphize;
63 use middle::trans::tvec;
64 use middle::trans::type_::Type;
65 use middle::trans::type_of;
66 use middle::trans::type_of::*;
67 use middle::trans::value::Value;
70 use util::common::indenter;
71 use util::ppaux::{Repr, ty_to_str};
72 use util::sha2::Sha256;
73 use util::nodemap::NodeMap;
75 use arena::TypedArena;
77 use std::c_str::ToCStr;
78 use std::cell::{Cell, RefCell};
80 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic};
81 use syntax::ast_util::{local_def, is_local};
82 use syntax::attr::AttrMetaMethods;
84 use syntax::codemap::Span;
85 use syntax::parse::token::InternedString;
86 use syntax::visit::Visitor;
88 use syntax::{ast, ast_util, ast_map};
92 local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)
94 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
95 match task_local_insn_key.get() {
96 Some(ctx) => blk(ctx.borrow().as_slice()),
101 pub fn init_insn_ctxt() {
102 task_local_insn_key.replace(Some(RefCell::new(Vec::new())));
105 pub struct _InsnCtxt { _x: () }
108 impl Drop for _InsnCtxt {
110 match task_local_insn_key.get() {
111 Some(ctx) => { ctx.borrow_mut().pop(); }
117 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
118 debug!("new InsnCtxt: {}", s);
119 match task_local_insn_key.get() {
120 Some(ctx) => ctx.borrow_mut().push(s),
126 pub struct StatRecorder<'a> {
127 ccx: &'a CrateContext,
128 name: Option<StrBuf>,
133 impl<'a> StatRecorder<'a> {
134 pub fn new(ccx: &'a CrateContext, name: StrBuf) -> StatRecorder<'a> {
135 let start = if ccx.sess().trans_stats() {
136 time::precise_time_ns()
140 let istart = ccx.stats.n_llvm_insns.get();
151 impl<'a> Drop for StatRecorder<'a> {
153 if self.ccx.sess().trans_stats() {
154 let end = time::precise_time_ns();
155 let elapsed = ((end - self.start) / 1_000_000) as uint;
156 let iend = self.ccx.stats.n_llvm_insns.get();
157 self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
159 iend - self.istart));
160 self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
161 // Reset LLVM insn count to avoid compound costs.
162 self.ccx.stats.n_llvm_insns.set(self.istart);
167 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
168 fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv,
169 ty: Type, output: ty::t) -> ValueRef {
170 let llfn: ValueRef = name.with_c_str(|buf| {
172 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
176 match ty::get(output).sty {
177 // functions returning bottom may unwind, but can never return normally
180 llvm::LLVMAddFunctionAttr(llfn, lib::llvm::NoReturnAttribute as c_uint)
183 // `~` pointer return values never alias because ownership is transferred
184 ty::ty_uniq(..) // | ty::ty_trait(_, _, ty::UniqTraitStore, _, _)
187 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
193 lib::llvm::SetFunctionCallConv(llfn, cc);
194 // Function addresses in Rust are never significant, allowing functions to be merged.
195 lib::llvm::SetUnnamedAddr(llfn, true);
196 set_split_stack(llfn);
201 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
202 pub fn decl_cdecl_fn(llmod: ModuleRef,
205 output: ty::t) -> ValueRef {
206 decl_fn(llmod, name, lib::llvm::CCallConv, ty, output)
209 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
210 pub fn get_extern_fn(externs: &mut ExternMap,
213 cc: lib::llvm::CallConv,
217 match externs.find_equiv(&name) {
218 Some(n) => return *n,
221 let f = decl_fn(llmod, name, cc, ty, output);
222 externs.insert(name.to_strbuf(), f);
226 fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
227 name: &str, did: ast::DefId) -> ValueRef {
228 match ccx.externs.borrow().find_equiv(&name) {
229 Some(n) => return *n,
233 let f = decl_rust_fn(ccx, false, inputs, output, name);
234 csearch::get_item_attrs(&ccx.sess().cstore, did, |meta_items| {
235 set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr_outer(x))
236 .collect::<Vec<_>>().as_slice(), f)
239 ccx.externs.borrow_mut().insert(name.to_strbuf(), 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
261 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
264 // `&mut` pointer parameters never alias other parameters, or mutable global data
265 ty::ty_rptr(_, mt) if mt.mutbl == ast::MutMutable => {
267 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
270 // When a reference in an argument has no named lifetime, it's impossible for that
271 // reference to escape this function (returned or stored beyond the call by a closure).
272 ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
273 debug!("marking argument of {} as nocapture because of anonymous lifetime", name);
275 llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
279 // For non-immediate arguments the callee gets its own copy of
280 // the value on the stack, so there are no aliases
281 if !type_is_immediate(ccx, arg_ty) {
283 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
284 llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
291 // The out pointer will never alias with any other pointers, as the object only exists at a
292 // language level after the call. It can also be tagged with SRet to indicate that it is
293 // guaranteed to point to a usable block of memory for the type.
296 let outptr = llvm::LLVMGetParam(llfn, 0);
297 llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
298 llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
305 pub fn decl_internal_rust_fn(ccx: &CrateContext, has_env: bool,
306 inputs: &[ty::t], output: ty::t,
307 name: &str) -> ValueRef {
308 let llfn = decl_rust_fn(ccx, has_env, inputs, output, name);
309 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
313 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
314 name: &str, ty: Type) -> ValueRef {
315 match externs.find_equiv(&name) {
316 Some(n) => return *n,
320 let c = name.with_c_str(|buf| {
321 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
323 externs.insert(name.to_strbuf(), c);
328 // Returns a pointer to the body for the box. The box may be an opaque
329 // box. The result will be casted to the type of body_t, if it is statically
331 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
332 let _icx = push_ctxt("at_box_body");
334 let ty = Type::at_box(ccx, type_of(ccx, body_t));
335 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
336 GEPi(bcx, boxptr, [0u, abi::box_field_body])
339 fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
340 match bcx.tcx().lang_items.require(it) {
343 bcx.sess().fatal(format!("allocation of `{}` {}",
344 bcx.ty_to_str(info_ty),
350 // The following malloc_raw_dyn* functions allocate a box to contain
351 // a given type, but with a potentially dynamic size.
353 pub fn malloc_raw_dyn<'a>(bcx: &'a Block<'a>,
358 let _icx = push_ctxt("malloc_raw_exchange");
362 let r = callee::trans_lang_call(bcx,
363 require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
367 let llty_ptr = type_of::type_of(ccx, ptr_ty);
368 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
371 pub fn malloc_raw_dyn_managed<'a>(
377 let _icx = push_ctxt("malloc_raw_managed");
380 let langcall = require_alloc_fn(bcx, t, alloc_fn);
382 // Grab the TypeRef type of box_ptr_ty.
383 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
384 let llty = type_of(ccx, box_ptr_ty);
385 let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
388 let drop_glue = glue::get_drop_glue(ccx, t);
389 let r = callee::trans_lang_call(
393 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
398 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
401 // Type descriptor and type glue stuff
403 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
404 match ccx.tydescs.borrow().find(&t) {
405 Some(inf) => return inf.clone(),
409 ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
410 let inf = Rc::new(glue::declare_tydesc(ccx, t));
412 ccx.tydescs.borrow_mut().insert(t, inf.clone());
416 #[allow(dead_code)] // useful
417 pub fn set_optimize_for_size(f: ValueRef) {
418 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
421 pub fn set_no_inline(f: ValueRef) {
422 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
425 #[allow(dead_code)] // useful
426 pub fn set_no_unwind(f: ValueRef) {
427 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
430 // Tell LLVM to emit the information necessary to unwind the stack for the
432 pub fn set_uwtable(f: ValueRef) {
433 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
436 pub fn set_inline_hint(f: ValueRef) {
437 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
440 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
442 // Set the inline hint if there is one
443 match find_inline_attr(attrs) {
444 InlineHint => set_inline_hint(llfn),
445 InlineAlways => set_always_inline(llfn),
446 InlineNever => set_no_inline(llfn),
447 InlineNone => { /* fallthrough */ }
450 // Add the no-split-stack attribute if requested
451 if contains_name(attrs, "no_split_stack") {
452 unset_split_stack(llfn);
455 if contains_name(attrs, "cold") {
456 unsafe { llvm::LLVMAddColdAttribute(llfn) }
460 pub fn set_always_inline(f: ValueRef) {
461 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
464 pub fn set_split_stack(f: ValueRef) {
465 "split-stack".with_c_str(|buf| {
466 unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
470 pub fn unset_split_stack(f: ValueRef) {
471 "split-stack".with_c_str(|buf| {
472 unsafe { llvm::LLVMRemoveFunctionAttrString(f, buf); }
476 // Double-check that we never ask LLVM to declare the same symbol twice. It
477 // silently mangles such symbols, breaking our linkage model.
478 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: StrBuf) {
479 if ccx.all_llvm_symbols.borrow().contains(&sym) {
480 ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).as_slice());
482 ccx.all_llvm_symbols.borrow_mut().insert(sym);
486 pub fn get_res_dtor(ccx: &CrateContext,
488 parent_id: ast::DefId,
491 let _icx = push_ctxt("trans_res_dtor");
492 let did = if did.krate != ast::LOCAL_CRATE {
493 inline::maybe_instantiate_inline(ccx, did)
498 if !substs.tps.is_empty() || !substs.self_ty.is_none() {
499 assert_eq!(did.krate, ast::LOCAL_CRATE);
501 let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, substs);
502 let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, vtables, None, None);
505 } else if did.krate == ast::LOCAL_CRATE {
506 get_item_val(ccx, did.node)
509 let name = csearch::get_symbol(&ccx.sess().cstore, did);
510 let class_ty = ty::subst(tcx, substs,
511 ty::lookup_item_type(tcx, parent_id).ty);
512 let llty = type_of_dtor(ccx, class_ty);
514 get_extern_fn(&mut *ccx.externs.borrow_mut(),
517 lib::llvm::CCallConv,
523 // Structural comparison: a rather involved form of glue.
524 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
525 if cx.sess().opts.cg.save_temps {
528 llvm::LLVMSetValueName(v, buf)
535 // Used only for creating scalar comparison glue.
536 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
538 // NB: This produces an i1, not a Rust bool (i8).
539 pub fn compare_scalar_types<'a>(
546 let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
548 match ty::get(t).sty {
549 ty::ty_nil => f(nil_type),
550 ty::ty_bool | ty::ty_ptr(_) |
551 ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
552 ty::ty_int(_) => f(signed_int),
553 ty::ty_float(_) => f(floating_point),
554 // Should never get here, because t is scalar.
555 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
560 // A helper function to do the actual comparison of scalar values.
561 pub fn compare_scalar_values<'a>(
568 let _icx = push_ctxt("compare_scalar_values");
569 fn die(cx: &Block) -> ! {
570 cx.sess().bug("compare_scalar_values: must be a comparison operator");
574 // We don't need to do actual comparisons for nil.
575 // () == () holds but () < () does not.
577 ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(cx.ccx(), true),
578 ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(cx.ccx(), false),
579 // refinements would be nice
585 ast::BiEq => lib::llvm::RealOEQ,
586 ast::BiNe => lib::llvm::RealUNE,
587 ast::BiLt => lib::llvm::RealOLT,
588 ast::BiLe => lib::llvm::RealOLE,
589 ast::BiGt => lib::llvm::RealOGT,
590 ast::BiGe => lib::llvm::RealOGE,
593 return FCmp(cx, cmp, lhs, rhs);
597 ast::BiEq => lib::llvm::IntEQ,
598 ast::BiNe => lib::llvm::IntNE,
599 ast::BiLt => lib::llvm::IntSLT,
600 ast::BiLe => lib::llvm::IntSLE,
601 ast::BiGt => lib::llvm::IntSGT,
602 ast::BiGe => lib::llvm::IntSGE,
605 return ICmp(cx, cmp, lhs, rhs);
609 ast::BiEq => lib::llvm::IntEQ,
610 ast::BiNe => lib::llvm::IntNE,
611 ast::BiLt => lib::llvm::IntULT,
612 ast::BiLe => lib::llvm::IntULE,
613 ast::BiGt => lib::llvm::IntUGT,
614 ast::BiGe => lib::llvm::IntUGE,
617 return ICmp(cx, cmp, lhs, rhs);
622 pub fn compare_simd_types(
630 match ty::get(t).sty {
632 // The comparison operators for floating point vectors are challenging.
633 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
634 // then bitcast to a floating point vector, the result will be `-NaN`
635 // for each truth value. Because of this they are unsupported.
636 cx.sess().bug("compare_simd_types: comparison operators \
637 not supported for floating point SIMD types")
639 ty::ty_uint(_) | ty::ty_int(_) => {
641 ast::BiEq => lib::llvm::IntEQ,
642 ast::BiNe => lib::llvm::IntNE,
643 ast::BiLt => lib::llvm::IntSLT,
644 ast::BiLe => lib::llvm::IntSLE,
645 ast::BiGt => lib::llvm::IntSGT,
646 ast::BiGe => lib::llvm::IntSGE,
647 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
649 let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
650 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
651 // to get the correctly sized type. This will compile to a single instruction
652 // once the IR is converted to assembly if the SIMD instruction is supported
653 // by the target architecture.
654 SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
656 _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
660 pub type val_and_ty_fn<'r,'b> =
661 |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
663 // Iterates through the elements of a structural type.
664 pub fn iter_structural_ty<'r,
669 f: val_and_ty_fn<'r,'b>)
671 let _icx = push_ctxt("iter_structural_ty");
678 variant: &ty::VariantInfo,
680 f: val_and_ty_fn<'r,'b>)
682 let _icx = push_ctxt("iter_variant");
686 for (i, &arg) in variant.args.iter().enumerate() {
688 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
689 ty::subst(tcx, substs, arg));
695 match ty::get(t).sty {
696 ty::ty_struct(..) => {
697 let repr = adt::represent_type(cx.ccx(), t);
698 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
699 for (i, field_ty) in field_tys.iter().enumerate() {
700 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, discr, i);
701 cx = f(cx, llfld_a, field_ty.mt.ty);
705 ty::ty_vec(_, Some(n)) => {
706 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
707 let (base, len) = tvec::get_fixed_base_and_byte_len(cx, av, unit_ty, n);
708 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
710 ty::ty_tup(ref args) => {
711 let repr = adt::represent_type(cx.ccx(), t);
712 for (i, arg) in args.iter().enumerate() {
713 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, 0, i);
714 cx = f(cx, llfld_a, *arg);
717 ty::ty_enum(tid, ref substs) => {
721 let repr = adt::represent_type(ccx, t);
722 let variants = ty::enum_variants(ccx.tcx(), tid);
723 let n_variants = (*variants).len();
725 // NB: we must hit the discriminant first so that structural
726 // comparison know not to proceed when the discriminants differ.
728 match adt::trans_switch(cx, &*repr, av) {
729 (_match::single, None) => {
730 cx = iter_variant(cx, &*repr, av, &**variants.get(0),
733 (_match::switch, Some(lldiscrim_a)) => {
734 cx = f(cx, lldiscrim_a, ty::mk_int());
735 let unr_cx = fcx.new_temp_block("enum-iter-unr");
737 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
739 let next_cx = fcx.new_temp_block("enum-iter-next");
741 for variant in (*variants).iter() {
744 format_strbuf!("enum-iter-variant-{}",
747 .as_slice()).as_slice());
748 match adt::trans_case(cx, &*repr, variant.disr_val) {
749 _match::single_result(r) => {
750 AddCase(llswitch, r.val, variant_cx.llbb)
752 _ => ccx.sess().unimpl("value from adt::trans_case \
753 in iter_structural_ty")
756 iter_variant(variant_cx,
762 Br(variant_cx, next_cx.llbb);
766 _ => ccx.sess().unimpl("value from adt::trans_switch \
767 in iter_structural_ty")
770 _ => cx.sess().unimpl("type in iter_structural_ty")
775 pub fn cast_shift_expr_rhs<'a>(
781 cast_shift_rhs(op, lhs, rhs,
782 |a,b| Trunc(cx, a, b),
783 |a,b| ZExt(cx, a, b))
786 pub fn cast_shift_const_rhs(op: ast::BinOp,
787 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
788 cast_shift_rhs(op, lhs, rhs,
789 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
790 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
793 pub fn cast_shift_rhs(op: ast::BinOp,
796 trunc: |ValueRef, Type| -> ValueRef,
797 zext: |ValueRef, Type| -> ValueRef)
799 // Shifts may have any size int on the rhs
801 if ast_util::is_shift_binop(op) {
802 let mut rhs_llty = val_ty(rhs);
803 let mut lhs_llty = val_ty(lhs);
804 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
805 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
806 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
807 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
810 } else if lhs_sz > rhs_sz {
811 // FIXME (#1877: If shifting by negative
812 // values becomes not undefined then this is wrong.
823 pub fn fail_if_zero<'a>(
830 let text = if divrem == ast::BiDiv {
831 "attempted to divide by zero"
833 "attempted remainder with a divisor of zero"
835 let is_zero = match ty::get(rhs_t).sty {
837 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
838 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
841 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
842 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
845 cx.sess().bug(format!("fail-if-zero on unexpected type: {}",
846 ty_to_str(cx.tcx(), rhs_t)).as_slice());
849 with_cond(cx, is_zero, |bcx| {
850 controlflow::trans_fail(bcx, span, InternedString::new(text))
854 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
855 let name = csearch::get_symbol(&ccx.sess().cstore, did);
856 match ty::get(t).sty {
857 ty::ty_bare_fn(ref fn_ty) => {
858 match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
859 ccx.sess().targ_cfg.arch) {
860 Some(Rust) | Some(RustIntrinsic) => {
861 get_extern_rust_fn(ccx,
862 fn_ty.sig.inputs.as_slice(),
868 foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
869 name.as_slice(), None)
873 ty::ty_closure(ref f) => {
874 get_extern_rust_fn(ccx,
875 f.sig.inputs.as_slice(),
881 let llty = type_of(ccx, t);
882 get_extern_const(&mut *ccx.externs.borrow_mut(),
893 llargs: Vec<ValueRef> ,
894 attributes: &[(uint, lib::llvm::Attribute)],
895 call_info: Option<NodeInfo>)
896 -> (ValueRef, &'a Block<'a>) {
897 let _icx = push_ctxt("invoke_");
898 if bcx.unreachable.get() {
899 return (C_null(Type::i8(bcx.ccx())), bcx);
902 match bcx.opt_node_id {
904 debug!("invoke at ???");
907 debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
911 if need_invoke(bcx) {
912 debug!("invoking {} at {}", llfn, bcx.llbb);
913 for &llarg in llargs.iter() {
914 debug!("arg: {}", llarg);
916 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
917 let landing_pad = bcx.fcx.get_landing_pad();
920 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
921 None => debuginfo::clear_source_location(bcx.fcx)
924 let llresult = Invoke(bcx,
930 return (llresult, normal_bcx);
932 debug!("calling {} at {}", llfn, bcx.llbb);
933 for &llarg in llargs.iter() {
934 debug!("arg: {}", llarg);
938 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
939 None => debuginfo::clear_source_location(bcx.fcx)
942 let llresult = Call(bcx, llfn, llargs.as_slice(), attributes);
943 return (llresult, bcx);
947 pub fn need_invoke(bcx: &Block) -> bool {
948 if bcx.sess().no_landing_pads() {
952 // Avoid using invoke if we are already inside a landing pad.
957 bcx.fcx.needs_invoke()
960 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
961 let _icx = push_ctxt("load_if_immediate");
962 if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
966 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
967 match local.pat.node {
968 ast::PatWild => true, _ => false
972 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
975 debug!("init_local(bcx={}, local.id={:?})",
976 bcx.to_str(), local.id);
977 let _indenter = indenter();
979 let _icx = push_ctxt("init_local");
981 if ignore_lhs(bcx, local) {
982 // Handle let _ = e; just like e;
985 return controlflow::trans_stmt_semi(bcx, init)
987 None => { return bcx; }
991 _match::store_local(bcx, local)
994 pub fn raw_block<'a>(
995 fcx: &'a FunctionContext<'a>,
999 Block::new(llbb, is_lpad, None, fcx)
1002 pub fn with_cond<'a>(
1005 f: |&'a Block<'a>| -> &'a Block<'a>)
1007 let _icx = push_ctxt("with_cond");
1009 let next_cx = fcx.new_temp_block("next");
1010 let cond_cx = fcx.new_temp_block("cond");
1011 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1012 let after_cx = f(cond_cx);
1013 if !after_cx.terminated.get() {
1014 Br(after_cx, next_cx.llbb);
1019 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1020 let _icx = push_ctxt("call_memcpy");
1022 let key = match ccx.sess().targ_cfg.arch {
1023 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1024 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1026 let memcpy = ccx.get_intrinsic(&key);
1027 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1028 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1029 let size = IntCast(cx, n_bytes, ccx.int_type);
1030 let align = C_i32(ccx, align as i32);
1031 let volatile = C_i1(ccx, false);
1032 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1035 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1036 let _icx = push_ctxt("memcpy_ty");
1037 let ccx = bcx.ccx();
1038 if ty::type_is_structural(t) {
1039 let llty = type_of::type_of(ccx, t);
1040 let llsz = llsize_of(ccx, llty);
1041 let llalign = llalign_of_min(ccx, llty);
1042 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1044 Store(bcx, Load(bcx, src), dst);
1048 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1049 if cx.unreachable.get() { return; }
1050 let _icx = push_ctxt("zero_mem");
1053 let llty = type_of::type_of(ccx, t);
1054 memzero(&B(bcx), llptr, llty);
1057 // Always use this function instead of storing a zero constant to the memory
1058 // in question. If you store a zero constant, LLVM will drown in vreg
1059 // allocation for large data structures, and the generated code will be
1060 // awful. (A telltale sign of this is large quantities of
1061 // `mov [byte ptr foo],0` in the generated code.)
1062 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1063 let _icx = push_ctxt("memzero");
1066 let intrinsic_key = match ccx.sess().targ_cfg.arch {
1067 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1068 X86_64 => "llvm.memset.p0i8.i64"
1071 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1072 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1073 let llzeroval = C_u8(ccx, 0);
1074 let size = machine::llsize_of(ccx, ty);
1075 let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1076 let volatile = C_i1(ccx, false);
1077 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1080 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1081 let _icx = push_ctxt("alloc_ty");
1082 let ccx = bcx.ccx();
1083 let ty = type_of::type_of(ccx, t);
1084 assert!(!ty::type_has_params(t));
1085 let val = alloca(bcx, ty, name);
1089 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1090 alloca_maybe_zeroed(cx, ty, name, false)
1093 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1094 let _icx = push_ctxt("alloca");
1095 if cx.unreachable.get() {
1097 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1100 debuginfo::clear_source_location(cx.fcx);
1101 let p = Alloca(cx, ty, name);
1103 let b = cx.fcx.ccx.builder();
1104 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1110 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1111 let _icx = push_ctxt("arrayalloca");
1112 if cx.unreachable.get() {
1114 return llvm::LLVMGetUndef(ty.to_ref());
1117 debuginfo::clear_source_location(cx.fcx);
1118 return ArrayAlloca(cx, ty, v);
1121 // Creates and returns space for, or returns the argument representing, the
1122 // slot where the return value of the function must go.
1123 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1126 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1127 llvm::LLVMGetParam(fcx.llfn, 0)
1129 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1130 let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1131 Alloca(bcx, lloutputtype, "__make_return_pointer")
1136 // NB: must keep 4 fns in sync:
1139 // - create_datums_for_fn_args.
1143 // Be warned! You must call `init_function` before doing anything with the
1144 // returned function context.
1145 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1150 param_substs: Option<&'a param_substs>,
1152 block_arena: &'a TypedArena<Block<'a>>)
1153 -> FunctionContext<'a> {
1154 for p in param_substs.iter() { p.validate(); }
1156 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1160 ccx.tcx.map.path_to_str(id).to_owned()
1162 id, param_substs.map(|s| s.repr(ccx.tcx())));
1164 let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1165 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1166 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1168 let mut fcx = FunctionContext {
1171 llretptr: Cell::new(None),
1172 entry_bcx: RefCell::new(None),
1173 alloca_insert_pt: Cell::new(None),
1174 llreturn: Cell::new(None),
1175 personality: Cell::new(None),
1176 caller_expects_out_pointer: uses_outptr,
1177 llargs: RefCell::new(NodeMap::new()),
1178 lllocals: RefCell::new(NodeMap::new()),
1179 llupvars: RefCell::new(NodeMap::new()),
1181 param_substs: param_substs,
1183 block_arena: block_arena,
1185 debug_context: debug_context,
1186 scopes: RefCell::new(Vec::new())
1190 fcx.llenv = Some(unsafe {
1191 llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1198 /// Performs setup on a newly created function, creating the entry scope block
1199 /// and allocating space for the return pointer.
1200 pub fn init_function<'a>(fcx: &'a FunctionContext<'a>,
1202 output_type: ty::t) {
1203 let entry_bcx = fcx.new_temp_block("entry-block");
1205 *fcx.entry_bcx.borrow_mut() = Some(entry_bcx);
1207 // Use a dummy instruction as the insertion point for all allocas.
1208 // This is later removed in FunctionContext::cleanup.
1209 fcx.alloca_insert_pt.set(Some(unsafe {
1210 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1211 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1214 // This shouldn't need to recompute the return type,
1215 // as new_fn_ctxt did it already.
1216 let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1218 if !return_type_is_void(fcx.ccx, substd_output_type) {
1219 // If the function returns nil/bot, there is no real return
1220 // value, so do not set `llretptr`.
1221 if !skip_retptr || fcx.caller_expects_out_pointer {
1222 // Otherwise, we normally allocate the llretptr, unless we
1223 // have been instructed to skip it for immediate return
1225 fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1230 // NB: must keep 4 fns in sync:
1233 // - create_datums_for_fn_args.
1237 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1238 use middle::trans::datum::{ByRef, ByValue};
1241 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1245 // work around bizarre resolve errors
1246 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1247 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1249 // create_datums_for_fn_args: creates rvalue datums for each of the
1250 // incoming function arguments. These will later be stored into
1251 // appropriate lvalue datums.
1252 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1254 -> Vec<RvalueDatum> {
1255 let _icx = push_ctxt("create_datums_for_fn_args");
1257 // Return an array wrapping the ValueRefs that we get from
1258 // llvm::LLVMGetParam for each argument into datums.
1259 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1260 let llarg = unsafe {
1261 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1263 datum::Datum(llarg, arg_ty, arg_kind(fcx, arg_ty))
1267 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1268 arg_scope: cleanup::CustomScopeIndex,
1271 arg_datums: Vec<RvalueDatum> )
1273 debug!("copy_args_to_allocas");
1275 let _icx = push_ctxt("copy_args_to_allocas");
1278 let arg_scope_id = cleanup::CustomScope(arg_scope);
1280 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1281 // For certain mode/type combinations, the raw llarg values are passed
1282 // by value. However, within the fn body itself, we want to always
1283 // have all locals and arguments be by-ref so that we can cancel the
1284 // cleanup and for better interaction with LLVM's debug info. So, if
1285 // the argument would be passed by value, we store it into an alloca.
1286 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1287 // the event it's not truly needed.
1289 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1291 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1292 debuginfo::create_argument_metadata(bcx, &args[i]);
1299 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1300 // and builds the return block.
1301 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1302 last_bcx: &'a Block<'a>) {
1303 let _icx = push_ctxt("finish_fn");
1305 let ret_cx = match fcx.llreturn.get() {
1307 if !last_bcx.terminated.get() {
1308 Br(last_bcx, llreturn);
1310 raw_block(fcx, false, llreturn)
1314 build_return_block(fcx, ret_cx);
1315 debuginfo::clear_source_location(fcx);
1319 // Builds the return block for a function.
1320 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1321 // Return the value if this function immediate; otherwise, return void.
1322 if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1323 return RetVoid(ret_cx);
1326 let retptr = Value(fcx.llretptr.get().unwrap());
1327 let retval = match retptr.get_dominating_store(ret_cx) {
1328 // If there's only a single store to the ret slot, we can directly return
1329 // the value that was stored and omit the store and the alloca
1331 let retval = s.get_operand(0).unwrap().get();
1332 s.erase_from_parent();
1334 if retptr.has_no_uses() {
1335 retptr.erase_from_parent();
1340 // Otherwise, load the return value from the ret slot
1341 None => Load(ret_cx, fcx.llretptr.get().unwrap())
1345 Ret(ret_cx, retval);
1348 // trans_closure: Builds an LLVM function out of a source function.
1349 // If the function closes over its environment a closure will be
1351 pub fn trans_closure(ccx: &CrateContext,
1355 param_substs: Option<¶m_substs>,
1357 _attributes: &[ast::Attribute],
1359 maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1360 ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1362 let _icx = push_ctxt("trans_closure");
1363 set_uwtable(llfndecl);
1365 debug!("trans_closure(..., param_substs={})",
1366 param_substs.map(|s| s.repr(ccx.tcx())));
1368 let has_env = match ty::get(ty::node_id_to_type(ccx.tcx(), id)).sty {
1369 ty::ty_closure(_) => true,
1373 let arena = TypedArena::new();
1374 let fcx = new_fn_ctxt(ccx,
1379 param_substs.map(|s| &*s),
1382 init_function(&fcx, false, output_type);
1384 // cleanup scope for the incoming arguments
1385 let arg_scope = fcx.push_custom_cleanup_scope();
1387 // Create the first basic block in the function and keep a handle on it to
1388 // pass to finish_fn later.
1389 let bcx_top = fcx.entry_bcx.borrow().clone().unwrap();
1390 let mut bcx = bcx_top;
1391 let block_ty = node_id_type(bcx, body.id);
1393 // Set up arguments to the function.
1394 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1395 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1397 bcx = copy_args_to_allocas(&fcx,
1400 decl.inputs.as_slice(),
1403 bcx = maybe_load_env(bcx);
1405 // Up until here, IR instructions for this function have explicitly not been annotated with
1406 // source code location, so we don't step into call setup code. From here on, source location
1407 // emitting should be enabled.
1408 debuginfo::start_emitting_source_locations(&fcx);
1410 let dest = match fcx.llretptr.get() {
1411 Some(e) => {expr::SaveIn(e)}
1413 assert!(type_is_zero_size(bcx.ccx(), block_ty))
1418 // This call to trans_block is the place where we bridge between
1419 // translation calls that don't have a return value (trans_crate,
1420 // trans_mod, trans_item, et cetera) and those that do
1421 // (trans_block, trans_expr, et cetera).
1422 bcx = controlflow::trans_block(bcx, body, dest);
1424 match fcx.llreturn.get() {
1426 Br(bcx, fcx.return_exit_block());
1427 fcx.pop_custom_cleanup_scope(arg_scope);
1430 // Microoptimization writ large: avoid creating a separate
1431 // llreturn basic block
1432 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1436 // Put return block after all other blocks.
1437 // This somewhat improves single-stepping experience in debugger.
1439 let llreturn = fcx.llreturn.get();
1440 for &llreturn in llreturn.iter() {
1441 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1445 // Insert the mandatory first few basic blocks before lltop.
1446 finish_fn(&fcx, bcx);
1449 // trans_fn: creates an LLVM function corresponding to a source language
1451 pub fn trans_fn(ccx: &CrateContext,
1455 param_substs: Option<¶m_substs>,
1457 attrs: &[ast::Attribute]) {
1458 let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id).to_strbuf());
1459 debug!("trans_fn(param_substs={})", param_substs.map(|s| s.repr(ccx.tcx())));
1460 let _icx = push_ctxt("trans_fn");
1461 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
1462 trans_closure(ccx, decl, body, llfndecl,
1463 param_substs, id, attrs, output_type, |bcx| bcx);
1466 pub fn trans_enum_variant(ccx: &CrateContext,
1467 _enum_id: ast::NodeId,
1468 variant: &ast::Variant,
1469 _args: &[ast::VariantArg],
1471 param_substs: Option<¶m_substs>,
1472 llfndecl: ValueRef) {
1473 let _icx = push_ctxt("trans_enum_variant");
1475 trans_enum_variant_or_tuple_like_struct(
1483 pub fn trans_tuple_struct(ccx: &CrateContext,
1484 _fields: &[ast::StructField],
1485 ctor_id: ast::NodeId,
1486 param_substs: Option<¶m_substs>,
1487 llfndecl: ValueRef) {
1488 let _icx = push_ctxt("trans_tuple_struct");
1490 trans_enum_variant_or_tuple_like_struct(
1498 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1499 ctor_id: ast::NodeId,
1501 param_substs: Option<¶m_substs>,
1502 llfndecl: ValueRef) {
1503 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1504 let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
1506 let result_ty = match ty::get(ctor_ty).sty {
1507 ty::ty_bare_fn(ref bft) => bft.sig.output,
1508 _ => ccx.sess().bug(
1509 format!("trans_enum_variant_or_tuple_like_struct: \
1510 unexpected ctor return type {}",
1511 ty_to_str(ccx.tcx(), ctor_ty)).as_slice())
1514 let arena = TypedArena::new();
1515 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1516 param_substs.map(|s| &*s), None, &arena);
1517 init_function(&fcx, false, result_ty);
1519 let arg_tys = ty::ty_fn_args(ctor_ty);
1521 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1523 let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1525 if !type_is_zero_size(fcx.ccx, result_ty) {
1526 let repr = adt::represent_type(ccx, result_ty);
1527 adt::trans_start_init(bcx, &*repr, fcx.llretptr.get().unwrap(), disr);
1528 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1529 let lldestptr = adt::trans_field_ptr(bcx,
1531 fcx.llretptr.get().unwrap(),
1534 arg_datum.store_to(bcx, lldestptr);
1538 finish_fn(&fcx, bcx);
1541 fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1542 id: ast::NodeId, vi: &[Rc<ty::VariantInfo>],
1544 for &variant in enum_definition.variants.iter() {
1545 let disr_val = vi[*i].disr_val;
1548 match variant.node.kind {
1549 ast::TupleVariantKind(ref args) if args.len() > 0 => {
1550 let llfn = get_item_val(ccx, variant.node.id);
1551 trans_enum_variant(ccx, id, variant, args.as_slice(),
1552 disr_val, None, llfn);
1554 ast::TupleVariantKind(_) => {
1557 ast::StructVariantKind(struct_def) => {
1558 trans_struct_def(ccx, struct_def);
1564 pub struct TransItemVisitor<'a> {
1565 pub ccx: &'a CrateContext,
1568 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1569 fn visit_item(&mut self, i: &ast::Item, _:()) {
1570 trans_item(self.ccx, i);
1574 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1575 let _icx = push_ctxt("trans_item");
1577 ast::ItemFn(decl, _fn_style, abi, ref generics, body) => {
1579 let llfndecl = get_item_val(ccx, item.id);
1580 foreign::trans_rust_fn_with_foreign_abi(
1581 ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
1582 } else if !generics.is_type_parameterized() {
1583 let llfn = get_item_val(ccx, item.id);
1590 item.attrs.as_slice());
1592 // Be sure to travel more than just one layer deep to catch nested
1593 // items in blocks and such.
1594 let mut v = TransItemVisitor{ ccx: ccx };
1595 v.visit_block(body, ());
1598 ast::ItemImpl(ref generics, _, _, ref ms) => {
1599 meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1601 ast::ItemMod(ref m) => {
1604 ast::ItemEnum(ref enum_definition, ref generics) => {
1605 if !generics.is_type_parameterized() {
1606 let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1608 trans_enum_def(ccx, enum_definition, item.id, vi.as_slice(), &mut i);
1611 ast::ItemStatic(_, m, expr) => {
1612 // Recurse on the expression to catch items in blocks
1613 let mut v = TransItemVisitor{ ccx: ccx };
1614 v.visit_expr(expr, ());
1615 consts::trans_const(ccx, m, item.id);
1616 // Do static_assert checking. It can't really be done much earlier
1617 // because we need to get the value of the bool out of LLVM
1618 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1619 if m == ast::MutMutable {
1620 ccx.sess().span_fatal(expr.span,
1621 "cannot have static_assert on a mutable \
1625 let v = ccx.const_values.borrow().get_copy(&item.id);
1627 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1628 ccx.sess().span_fatal(expr.span, "static assertion failed");
1633 ast::ItemForeignMod(ref foreign_mod) => {
1634 foreign::trans_foreign_mod(ccx, foreign_mod);
1636 ast::ItemStruct(struct_def, ref generics) => {
1637 if !generics.is_type_parameterized() {
1638 trans_struct_def(ccx, struct_def);
1641 ast::ItemTrait(..) => {
1642 // Inside of this trait definition, we won't be actually translating any
1643 // functions, but the trait still needs to be walked. Otherwise default
1644 // methods with items will not get translated and will cause ICE's when
1645 // metadata time comes around.
1646 let mut v = TransItemVisitor{ ccx: ccx };
1647 visit::walk_item(&mut v, item, ());
1649 _ => {/* fall through */ }
1653 pub fn trans_struct_def(ccx: &CrateContext, struct_def: @ast::StructDef) {
1654 // If this is a tuple-like struct, translate the constructor.
1655 match struct_def.ctor_id {
1656 // We only need to translate a constructor if there are fields;
1657 // otherwise this is a unit-like struct.
1658 Some(ctor_id) if struct_def.fields.len() > 0 => {
1659 let llfndecl = get_item_val(ccx, ctor_id);
1660 trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1661 ctor_id, None, llfndecl);
1663 Some(_) | None => {}
1667 // Translate a module. Doing this amounts to translating the items in the
1668 // module; there ends up being no artifact (aside from linkage names) of
1669 // separate modules in the compiled program. That's because modules exist
1670 // only as a convenience for humans working with the code, to organize names
1671 // and control visibility.
1672 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1673 let _icx = push_ctxt("trans_mod");
1674 for item in m.items.iter() {
1675 trans_item(ccx, *item);
1679 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: StrBuf, node_id: ast::NodeId,
1681 ccx.item_symbols.borrow_mut().insert(node_id, sym);
1683 if !ccx.reachable.contains(&node_id) {
1684 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1687 // The stack exhaustion lang item shouldn't have a split stack because
1688 // otherwise it would continue to be exhausted (bad), and both it and the
1689 // eh_personality functions need to be externally linkable.
1690 let def = ast_util::local_def(node_id);
1691 if ccx.tcx.lang_items.stack_exhausted() == Some(def) {
1692 unset_split_stack(llfn);
1693 lib::llvm::SetLinkage(llfn, lib::llvm::ExternalLinkage);
1695 if ccx.tcx.lang_items.eh_personality() == Some(def) {
1696 lib::llvm::SetLinkage(llfn, lib::llvm::ExternalLinkage);
1700 if is_entry_fn(ccx.sess(), node_id) {
1701 create_entry_wrapper(ccx, sp, llfn);
1705 fn register_fn(ccx: &CrateContext,
1708 node_id: ast::NodeId,
1711 let f = match ty::get(node_type).sty {
1712 ty::ty_bare_fn(ref f) => {
1713 assert!(f.abi == Rust || f.abi == RustIntrinsic);
1716 _ => fail!("expected bare rust fn or an intrinsic")
1719 let llfn = decl_rust_fn(ccx,
1721 f.sig.inputs.as_slice(),
1724 finish_register_fn(ccx, sp, sym, node_id, llfn);
1728 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1729 pub fn register_fn_llvmty(ccx: &CrateContext,
1732 node_id: ast::NodeId,
1733 cc: lib::llvm::CallConv,
1735 output: ty::t) -> ValueRef {
1736 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1738 let llfn = decl_fn(ccx.llmod, sym.as_slice(), cc, fn_ty, output);
1739 finish_register_fn(ccx, sp, sym, node_id, llfn);
1743 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1744 match *sess.entry_fn.borrow() {
1745 Some((entry_id, _)) => node_id == entry_id,
1750 // Create a _rust_main(args: ~[str]) function which will be called from the
1751 // runtime rust_start function
1752 pub fn create_entry_wrapper(ccx: &CrateContext,
1754 main_llfn: ValueRef) {
1755 let et = ccx.sess().entry_type.get().unwrap();
1757 config::EntryMain => {
1758 create_entry_fn(ccx, main_llfn, true);
1760 config::EntryStart => create_entry_fn(ccx, main_llfn, false),
1761 config::EntryNone => {} // Do nothing.
1764 fn create_entry_fn(ccx: &CrateContext,
1765 rust_main: ValueRef,
1766 use_start_lang_item: bool) {
1767 let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
1770 let llfn = decl_cdecl_fn(ccx.llmod, "main", llfty, ty::mk_nil());
1771 let llbb = "top".with_c_str(|buf| {
1773 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1776 let bld = ccx.builder.b;
1778 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1780 let (start_fn, args) = if use_start_lang_item {
1781 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1783 Err(s) => { ccx.sess().fatal(s.as_slice()); }
1785 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1786 get_item_val(ccx, start_def_id.node)
1788 let start_fn_type = csearch::get_type(ccx.tcx(),
1790 trans_external_path(ccx, start_def_id, start_fn_type)
1794 let opaque_rust_main = "rust_main".with_c_str(|buf| {
1795 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
1800 llvm::LLVMGetParam(llfn, 0),
1801 llvm::LLVMGetParam(llfn, 1)
1806 debug!("using user-defined start fn");
1808 llvm::LLVMGetParam(llfn, 0 as c_uint),
1809 llvm::LLVMGetParam(llfn, 1 as c_uint)
1815 let result = llvm::LLVMBuildCall(bld,
1818 args.len() as c_uint,
1821 llvm::LLVMBuildRet(bld, result);
1826 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1827 ty: ty::t, attrs: &[ast::Attribute]) -> StrBuf {
1828 match attr::first_attr_value_str_by_name(attrs, "export_name") {
1829 // Use provided name
1830 Some(name) => name.get().to_strbuf(),
1832 _ => ccx.tcx.map.with_path(id, |mut path| {
1833 if attr::contains_name(attrs, "no_mangle") {
1835 path.last().unwrap().to_str().to_strbuf()
1837 match weak_lang_items::link_name(attrs) {
1838 Some(name) => name.get().to_strbuf(),
1840 // Usual name mangling
1841 mangle_exported_name(ccx, path, ty, id)
1849 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
1850 debug!("get_item_val(id=`{:?}`)", id);
1852 match ccx.item_vals.borrow().find_copy(&id) {
1853 Some(v) => return v,
1857 let mut foreign = false;
1858 let item = ccx.tcx.map.get(id);
1859 let val = match item {
1860 ast_map::NodeItem(i) => {
1861 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
1862 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1864 let v = match i.node {
1865 ast::ItemStatic(_, _, expr) => {
1866 // If this static came from an external crate, then
1867 // we need to get the symbol from csearch instead of
1868 // using the current crate's name/version
1869 // information in the hash of the symbol
1870 debug!("making {}", sym);
1871 let (sym, is_local) = {
1872 match ccx.external_srcs.borrow().find(&i.id) {
1874 debug!("but found in other crate...");
1875 (csearch::get_symbol(&ccx.sess().cstore,
1882 // We need the translated value here, because for enums the
1883 // LLVM type is not fully determined by the Rust type.
1884 let (v, inlineable) = consts::const_expr(ccx, expr, is_local);
1885 ccx.const_values.borrow_mut().insert(id, v);
1886 let mut inlineable = inlineable;
1889 let llty = llvm::LLVMTypeOf(v);
1890 let g = sym.as_slice().with_c_str(|buf| {
1891 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
1894 if !ccx.reachable.contains(&id) {
1895 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
1898 // Apply the `unnamed_addr` attribute if
1900 if attr::contains_name(i.attrs.as_slice(),
1901 "address_insignificant") {
1902 if ccx.reachable.contains(&id) {
1903 ccx.sess().span_bug(i.span,
1904 "insignificant static is reachable");
1906 lib::llvm::SetUnnamedAddr(g, true);
1908 // This is a curious case where we must make
1909 // all of these statics inlineable. If a
1910 // global is tagged as
1911 // address_insignificant, then LLVM won't
1912 // coalesce globals unless they have an
1913 // internal linkage type. This means that
1914 // external crates cannot use this global.
1915 // This is a problem for things like inner
1916 // statics in generic functions, because the
1917 // function will be inlined into another
1918 // crate and then attempt to link to the
1919 // static in the original crate, only to
1920 // find that it's not there. On the other
1921 // side of inlininig, the crates knows to
1922 // not declare this static as
1923 // available_externally (because it isn't)
1927 if attr::contains_name(i.attrs.as_slice(),
1929 lib::llvm::set_thread_local(g, true);
1933 debug!("{} not inlined", sym);
1934 ccx.non_inlineable_statics.borrow_mut()
1938 ccx.item_symbols.borrow_mut().insert(i.id, sym);
1943 ast::ItemFn(_, _, abi, _, _) => {
1944 let llfn = if abi == Rust {
1945 register_fn(ccx, i.span, sym, i.id, ty)
1947 foreign::register_rust_fn_with_foreign_abi(ccx,
1952 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
1956 _ => fail!("get_item_val: weird result in table")
1959 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
1961 Some(sect) => unsafe {
1962 sect.get().with_c_str(|buf| {
1963 llvm::LLVMSetSection(v, buf);
1972 ast_map::NodeTraitMethod(trait_method) => {
1973 debug!("get_item_val(): processing a NodeTraitMethod");
1974 match *trait_method {
1975 ast::Required(_) => {
1976 ccx.sess().bug("unexpected variant: required trait method in \
1979 ast::Provided(m) => {
1980 register_method(ccx, id, m)
1985 ast_map::NodeMethod(m) => {
1986 register_method(ccx, id, m)
1989 ast_map::NodeForeignItem(ni) => {
1993 ast::ForeignItemFn(..) => {
1994 let abi = ccx.tcx.map.get_foreign_abi(id);
1995 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
1996 let name = foreign::link_name(ni);
1997 foreign::register_foreign_item_fn(ccx, abi, ty,
1998 name.get().as_slice(),
2001 ast::ForeignItemStatic(..) => {
2002 foreign::register_static(ccx, ni)
2007 ast_map::NodeVariant(ref v) => {
2009 let args = match v.node.kind {
2010 ast::TupleVariantKind(ref args) => args,
2011 ast::StructVariantKind(_) => {
2012 fail!("struct variant kind unexpected in get_item_val")
2015 assert!(args.len() != 0u);
2016 let ty = ty::node_id_to_type(ccx.tcx(), id);
2017 let parent = ccx.tcx.map.get_parent(id);
2018 let enm = ccx.tcx.map.expect_item(parent);
2019 let sym = exported_name(ccx,
2022 enm.attrs.as_slice());
2024 llfn = match enm.node {
2025 ast::ItemEnum(_, _) => {
2026 register_fn(ccx, (*v).span, sym, id, ty)
2028 _ => fail!("NodeVariant, shouldn't happen")
2030 set_inline_hint(llfn);
2034 ast_map::NodeStructCtor(struct_def) => {
2035 // Only register the constructor if this is a tuple-like struct.
2036 let ctor_id = match struct_def.ctor_id {
2038 ccx.sess().bug("attempt to register a constructor of \
2039 a non-tuple-like struct")
2041 Some(ctor_id) => ctor_id,
2043 let parent = ccx.tcx.map.get_parent(id);
2044 let struct_item = ccx.tcx.map.expect_item(parent);
2045 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2046 let sym = exported_name(ccx,
2051 let llfn = register_fn(ccx, struct_item.span,
2053 set_inline_hint(llfn);
2058 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2059 variant).as_slice())
2063 // foreign items (extern fns and extern statics) don't have internal
2064 // linkage b/c that doesn't quite make sense. Otherwise items can
2065 // have internal linkage if they're not reachable.
2066 if !foreign && !ccx.reachable.contains(&id) {
2067 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2070 ccx.item_vals.borrow_mut().insert(id, val);
2074 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2075 m: &ast::Method) -> ValueRef {
2076 let mty = ty::node_id_to_type(ccx.tcx(), id);
2078 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2080 let llfn = register_fn(ccx, m.span, sym, id, mty);
2081 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2085 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2087 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2091 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2092 -> encoder::EncodeParams<'r> {
2093 encoder::EncodeParams {
2094 diag: cx.sess().diagnostic(),
2096 reexports2: &cx.exp_map2,
2097 item_symbols: &cx.item_symbols,
2098 non_inlineable_statics: &cx.non_inlineable_statics,
2099 link_meta: &cx.link_meta,
2100 cstore: &cx.sess().cstore,
2101 encode_inlined_item: ie,
2105 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2108 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2109 *ty != config::CrateTypeExecutable
2115 let encode_inlined_item: encoder::EncodeInlinedItem =
2116 |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
2118 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2119 let metadata = encoder::encode_metadata(encode_parms, krate);
2120 let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2121 .append(match flate::deflate_bytes(metadata.as_slice()) {
2122 Some(compressed) => compressed,
2124 cx.sess().fatal("failed to compress metadata")
2127 let llmeta = C_bytes(cx, compressed.as_slice());
2128 let llconst = C_struct(cx, [llmeta], false);
2129 let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2130 cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2131 let llglobal = name.with_c_str(|buf| {
2133 llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2137 llvm::LLVMSetInitializer(llglobal, llconst);
2144 llvm::LLVMSetSection(llglobal, buf)
2150 pub fn trans_crate(krate: ast::Crate,
2151 analysis: CrateAnalysis,
2152 output: &OutputFilenames) -> (ty::ctxt, CrateTranslation) {
2153 let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, .. } = analysis;
2155 // Before we touch LLVM, make sure that multithreading is enabled.
2157 use sync::one::{Once, ONCE_INIT};
2158 static mut INIT: Once = ONCE_INIT;
2159 static mut POISONED: bool = false;
2161 if llvm::LLVMStartMultithreaded() != 1 {
2162 // use an extra bool to make sure that all future usage of LLVM
2163 // cannot proceed despite the Once not running more than once.
2169 tcx.sess.bug("couldn't enable multi-threaded LLVM");
2173 let link_meta = link::build_link_meta(&krate,
2174 output.out_filestem.as_slice());
2176 // Append ".rs" to crate name as LLVM module identifier.
2178 // LLVM code generator emits a ".file filename" directive
2179 // for ELF backends. Value of the "filename" is set as the
2180 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2181 // crashes if the module identifer is same as other symbols
2182 // such as a function name in the module.
2183 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2184 let mut llmod_id = link_meta.crateid.name.clone();
2185 llmod_id.push_str(".rs");
2187 let ccx = CrateContext::new(llmod_id.as_slice(), tcx, exp_map2,
2188 Sha256::new(), link_meta, reachable);
2190 let _icx = push_ctxt("text");
2191 trans_mod(&ccx, &krate.module);
2194 glue::emit_tydescs(&ccx);
2195 if ccx.sess().opts.debuginfo != NoDebugInfo {
2196 debuginfo::finalize(&ccx);
2199 // Translate the metadata.
2200 let metadata = write_metadata(&ccx, &krate);
2201 if ccx.sess().trans_stats() {
2202 println!("--- trans stats ---");
2203 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2204 println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2205 println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2206 println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2208 println!("n_fns: {}", ccx.stats.n_fns.get());
2209 println!("n_monos: {}", ccx.stats.n_monos.get());
2210 println!("n_inlines: {}", ccx.stats.n_inlines.get());
2211 println!("n_closures: {}", ccx.stats.n_closures.get());
2212 println!("fn stats:");
2213 ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2214 insns_b.cmp(&insns_a)
2216 for tuple in ccx.stats.fn_stats.borrow().iter() {
2218 (ref name, ms, insns) => {
2219 println!("{} insns, {} ms, {}", insns, ms, *name);
2224 if ccx.sess().count_llvm_insns() {
2225 for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2226 println!("{:7u} {}", *v, *k);
2230 let llcx = ccx.llcx;
2231 let link_meta = ccx.link_meta.clone();
2232 let llmod = ccx.llmod;
2234 let mut reachable: Vec<StrBuf> = ccx.reachable.iter().filter_map(|id| {
2235 ccx.item_symbols.borrow().find(id).map(|s| s.to_strbuf())
2238 // Make sure that some other crucial symbols are not eliminated from the
2239 // module. This includes the main function, the crate map (used for debug
2240 // log settings and I/O), and finally the curious rust_stack_exhausted
2241 // symbol. This symbol is required for use by the libmorestack library that
2242 // we link in, so we must ensure that this symbol is not internalized (if
2243 // defined in the crate).
2244 reachable.push("main".to_strbuf());
2245 reachable.push("rust_stack_exhausted".to_strbuf());
2247 // referenced from .eh_frame section on some platforms
2248 reachable.push("rust_eh_personality".to_strbuf());
2249 // referenced from rt/rust_try.ll
2250 reachable.push("rust_eh_personality_catch".to_strbuf());
2252 let metadata_module = ccx.metadata_llmod;
2253 let formats = ccx.tcx.dependency_formats.borrow().clone();
2254 let no_builtins = attr::contains_name(krate.attrs.as_slice(), "no_builtins");
2256 (ccx.tcx, CrateTranslation {
2260 metadata_module: metadata_module,
2262 reachable: reachable,
2263 crate_formats: formats,
2264 no_builtins: no_builtins,