1 // Copyright 2012-2013 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 many TypeRefs correspond to one ty::t; for instance, tup(int, int,
24 // int) and rec(x=int, y=int, z=int) will have the same TypeRef.
28 use back::link::{mangle_exported_name};
29 use back::{link, abi};
31 use driver::session::Session;
32 use lib::llvm::{ContextRef, ModuleRef, ValueRef, BasicBlockRef};
33 use lib::llvm::{llvm, True};
35 use metadata::common::LinkMeta;
36 use metadata::{csearch, cstore, encoder};
37 use middle::astencode;
39 use middle::trans::_match;
40 use middle::trans::adt;
41 use middle::trans::base;
42 use middle::trans::build::*;
43 use middle::trans::callee;
44 use middle::trans::common::*;
45 use middle::trans::consts;
46 use middle::trans::controlflow;
47 use middle::trans::datum;
48 use middle::trans::debuginfo;
49 use middle::trans::expr;
50 use middle::trans::foreign;
51 use middle::trans::glue;
52 use middle::trans::inline;
53 use middle::trans::machine;
54 use middle::trans::machine::{llalign_of_min, llsize_of};
55 use middle::trans::meth;
56 use middle::trans::monomorphize;
57 use middle::trans::reachable;
58 use middle::trans::tvec;
59 use middle::trans::type_of;
60 use middle::trans::type_of::*;
62 use util::common::indenter;
63 use util::ppaux::{Repr, ty_to_str};
65 use middle::trans::type_::Type;
68 use core::hashmap::{HashMap};
71 use core::libc::c_uint;
77 use syntax::ast::ident;
78 use syntax::ast_map::{path, path_elt_to_str, path_name};
79 use syntax::ast_util::{local_def, path_to_ident};
81 use syntax::codemap::span;
82 use syntax::parse::token;
83 use syntax::parse::token::{special_idents};
84 use syntax::print::pprust::stmt_to_str;
86 use syntax::{ast, ast_util, codemap, ast_map};
87 use syntax::abi::{X86, X86_64, Arm, Mips};
89 pub use middle::trans::context::task_llcx;
91 fn task_local_insn_key(_v: @~[&'static str]) {}
93 pub fn with_insn_ctxt(blk: &fn(&[&'static str])) {
95 let opt = local_data::local_data_get(task_local_insn_key);
102 pub fn init_insn_ctxt() {
104 local_data::local_data_set(task_local_insn_key, @~[]);
108 pub struct _InsnCtxt { _x: () }
111 impl Drop for _InsnCtxt {
114 do local_data::local_data_modify(task_local_insn_key) |c| {
115 do c.map_consume |@ctx| {
125 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
126 debug!("new InsnCtxt: %s", s);
128 do local_data::local_data_modify(task_local_insn_key) |c| {
129 do c.map_consume |@ctx| {
139 fn fcx_has_nonzero_span(fcx: fn_ctxt) -> bool {
142 Some(span) => *span.lo != 0 || *span.hi != 0
146 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
147 let llfn: ValueRef = do name.as_c_str |buf| {
149 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
153 lib::llvm::SetFunctionCallConv(llfn, cc);
157 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
158 return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
161 // Only use this if you are going to actually define the function. It's
162 // not valid to simply declare a function as internal.
163 pub fn decl_internal_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
164 let llfn = decl_cdecl_fn(llmod, name, ty);
165 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
169 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: @str,
170 cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
171 match externs.find_copy(&name) {
175 let f = decl_fn(llmod, name, cc, ty);
176 externs.insert(name, f);
180 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
181 name: @str, ty: Type) -> ValueRef {
182 match externs.find_copy(&name) {
187 let c = do name.as_c_str |buf| {
188 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
190 externs.insert(name, c);
194 pub fn umax(cx: block, a: ValueRef, b: ValueRef) -> ValueRef {
195 let _icx = push_ctxt("umax");
196 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
197 return Select(cx, cond, b, a);
200 pub fn umin(cx: block, a: ValueRef, b: ValueRef) -> ValueRef {
201 let _icx = push_ctxt("umin");
202 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
203 return Select(cx, cond, a, b);
206 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
207 // The type of the returned pointer is always i8*. If you care about the
208 // return type, use bump_ptr().
209 pub fn ptr_offs(bcx: block, base: ValueRef, sz: ValueRef) -> ValueRef {
210 let _icx = push_ctxt("ptr_offs");
211 let raw = PointerCast(bcx, base, Type::i8p());
212 InBoundsGEP(bcx, raw, [sz])
215 // Increment a pointer by a given amount and then cast it to be a pointer
217 pub fn bump_ptr(bcx: block, t: ty::t, base: ValueRef, sz: ValueRef) ->
219 let _icx = push_ctxt("bump_ptr");
221 let bumped = ptr_offs(bcx, base, sz);
222 let typ = type_of(ccx, t).ptr_to();
223 PointerCast(bcx, bumped, typ)
226 // Returns a pointer to the body for the box. The box may be an opaque
227 // box. The result will be casted to the type of body_t, if it is statically
230 // The runtime equivalent is box_body() in "rust_internal.h".
231 pub fn opaque_box_body(bcx: block,
233 boxptr: ValueRef) -> ValueRef {
234 let _icx = push_ctxt("opaque_box_body");
236 let ty = type_of(ccx, body_t);
237 let ty = Type::box(ccx, &ty);
238 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
239 GEPi(bcx, boxptr, [0u, abi::box_field_body])
242 // malloc_raw_dyn: allocates a box to contain a given type, but with a
243 // potentially dynamic size.
244 pub fn malloc_raw_dyn(bcx: block,
247 size: ValueRef) -> Result {
248 let _icx = push_ctxt("malloc_raw");
251 let (mk_fn, langcall) = match heap {
252 heap_managed | heap_managed_unique => {
253 (ty::mk_imm_box, bcx.tcx().lang_items.malloc_fn())
256 (ty::mk_imm_uniq, bcx.tcx().lang_items.exchange_malloc_fn())
260 // Grab the TypeRef type of box_ptr_ty.
261 let box_ptr_ty = mk_fn(bcx.tcx(), t);
262 let llty = type_of(ccx, box_ptr_ty);
264 // Get the tydesc for the body:
265 let static_ti = get_tydesc(ccx, t);
266 glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
269 let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
270 let rval = alloca(bcx, Type::i8p());
271 let bcx = callee::trans_lang_call(
276 let r = rslt(bcx, PointerCast(bcx, Load(bcx, rval), llty));
277 maybe_set_managed_unique_rc(r.bcx, r.val, heap);
281 // malloc_raw: expects an unboxed type and returns a pointer to
282 // enough space for a box of that type. This includes a rust_opaque_box
284 pub fn malloc_raw(bcx: block, t: ty::t, heap: heap) -> Result {
285 let ty = type_of(bcx.ccx(), t);
286 let size = llsize_of(bcx.ccx(), ty);
287 malloc_raw_dyn(bcx, t, heap, size)
290 pub struct MallocResult {
296 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
297 // and pulls out the body
298 pub fn malloc_general_dyn(bcx: block, t: ty::t, heap: heap, size: ValueRef)
300 let _icx = push_ctxt("malloc_general");
301 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
302 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
304 MallocResult { bcx: bcx, box: llbox, body: body }
307 pub fn malloc_general(bcx: block, t: ty::t, heap: heap)
309 let ty = type_of(bcx.ccx(), t);
310 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
312 pub fn malloc_boxed(bcx: block, t: ty::t)
314 malloc_general(bcx, t, heap_managed)
317 pub fn heap_for_unique(bcx: block, t: ty::t) -> heap {
318 if ty::type_contents(bcx.tcx(), t).contains_managed() {
325 pub fn maybe_set_managed_unique_rc(bcx: block, bx: ValueRef, heap: heap) {
326 if heap == heap_managed_unique {
327 // In cases where we are looking at a unique-typed allocation in the
328 // managed heap (thus have refcount 1 from the managed allocator),
329 // such as a ~(@foo) or such. These need to have their refcount forced
330 // to -2 so the annihilator ignores them.
331 let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
332 let rc_val = C_int(bcx.ccx(), -2);
333 Store(bcx, rc_val, rc);
337 pub fn malloc_unique(bcx: block, t: ty::t)
339 malloc_general(bcx, t, heap_for_unique(bcx, t))
342 // Type descriptor and type glue stuff
344 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
345 get_tydesc(ccx, t).tydesc
348 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
349 match ccx.tydescs.find(&t) {
356 ccx.stats.n_static_tydescs += 1u;
357 let inf = glue::declare_tydesc(ccx, t);
358 ccx.tydescs.insert(t, inf);
362 pub fn set_optimize_for_size(f: ValueRef) {
364 llvm::LLVMAddFunctionAttr(f,
365 lib::llvm::OptimizeForSizeAttribute
371 pub fn set_no_inline(f: ValueRef) {
373 llvm::LLVMAddFunctionAttr(f,
374 lib::llvm::NoInlineAttribute as c_uint,
379 pub fn set_no_unwind(f: ValueRef) {
381 llvm::LLVMAddFunctionAttr(f,
382 lib::llvm::NoUnwindAttribute as c_uint,
387 // Tell LLVM to emit the information necessary to unwind the stack for the
389 pub fn set_uwtable(f: ValueRef) {
391 llvm::LLVMAddFunctionAttr(f,
392 lib::llvm::UWTableAttribute as c_uint,
397 pub fn set_inline_hint(f: ValueRef) {
399 llvm::LLVMAddFunctionAttr(f,
400 lib::llvm::InlineHintAttribute as c_uint,
405 pub fn set_inline_hint_if_appr(attrs: &[ast::attribute],
407 match attr::find_inline_attr(attrs) {
408 attr::ia_hint => set_inline_hint(llfn),
409 attr::ia_always => set_always_inline(llfn),
410 attr::ia_never => set_no_inline(llfn),
411 attr::ia_none => { /* fallthrough */ }
415 pub fn set_always_inline(f: ValueRef) {
417 llvm::LLVMAddFunctionAttr(f,
418 lib::llvm::AlwaysInlineAttribute as c_uint,
423 pub fn set_fixed_stack_segment(f: ValueRef) {
425 llvm::LLVMAddFunctionAttr(f, 0, 1 << (39 - 32));
429 pub fn set_glue_inlining(f: ValueRef, t: ty::t) {
430 if ty::type_is_structural(t) {
431 set_optimize_for_size(f);
432 } else { set_always_inline(f); }
435 // Double-check that we never ask LLVM to declare the same symbol twice. It
436 // silently mangles such symbols, breaking our linkage model.
437 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
438 if ccx.all_llvm_symbols.contains(&sym) {
439 ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
441 ccx.all_llvm_symbols.insert(sym);
445 pub fn get_res_dtor(ccx: @mut CrateContext,
447 parent_id: ast::def_id,
450 let _icx = push_ctxt("trans_res_dtor");
451 if !substs.is_empty() {
452 let did = if did.crate != ast::local_crate {
453 inline::maybe_instantiate_inline(ccx, did, true)
457 assert_eq!(did.crate, ast::local_crate);
458 let tsubsts = ty::substs { self_r: None, self_ty: None,
459 tps: /*bad*/ substs.to_owned() };
460 let (val, _) = monomorphize::monomorphic_fn(ccx,
468 } else if did.crate == ast::local_crate {
469 get_item_val(ccx, did.node)
472 let name = csearch::get_symbol(ccx.sess.cstore, did);
473 let class_ty = ty::subst_tps(tcx,
476 ty::lookup_item_type(tcx, parent_id).ty);
477 let llty = type_of_dtor(ccx, class_ty);
478 let name = name.to_managed(); // :-(
479 get_extern_fn(&mut ccx.externs,
482 lib::llvm::CCallConv,
487 // Structural comparison: a rather involved form of glue.
488 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
489 if cx.sess.opts.save_temps {
490 let _: () = str::as_c_str(s, |buf| {
492 llvm::LLVMSetValueName(v, buf)
499 // Used only for creating scalar comparison glue.
500 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
502 // NB: This produces an i1, not a Rust bool (i8).
503 pub fn compare_scalar_types(cx: block,
509 let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
511 match ty::get(t).sty {
512 ty::ty_nil => rslt(cx, f(nil_type)),
513 ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
514 ty::ty_int(_) => rslt(cx, f(signed_int)),
515 ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
516 ty::ty_float(_) => rslt(cx, f(floating_point)),
519 controlflow::trans_fail(
521 @"attempt to compare values of type type"),
525 // Should never get here, because t is scalar.
526 cx.sess().bug("non-scalar type passed to \
527 compare_scalar_types")
533 // A helper function to do the actual comparison of scalar values.
534 pub fn compare_scalar_values(cx: block,
540 let _icx = push_ctxt("compare_scalar_values");
541 fn die(cx: block) -> ! {
542 cx.tcx().sess.bug("compare_scalar_values: must be a\
543 comparison operator");
547 // We don't need to do actual comparisons for nil.
548 // () == () holds but () < () does not.
550 ast::eq | ast::le | ast::ge => return C_i1(true),
551 ast::ne | ast::lt | ast::gt => return C_i1(false),
552 // refinements would be nice
558 ast::eq => lib::llvm::RealOEQ,
559 ast::ne => lib::llvm::RealUNE,
560 ast::lt => lib::llvm::RealOLT,
561 ast::le => lib::llvm::RealOLE,
562 ast::gt => lib::llvm::RealOGT,
563 ast::ge => lib::llvm::RealOGE,
566 return FCmp(cx, cmp, lhs, rhs);
570 ast::eq => lib::llvm::IntEQ,
571 ast::ne => lib::llvm::IntNE,
572 ast::lt => lib::llvm::IntSLT,
573 ast::le => lib::llvm::IntSLE,
574 ast::gt => lib::llvm::IntSGT,
575 ast::ge => lib::llvm::IntSGE,
578 return ICmp(cx, cmp, lhs, rhs);
582 ast::eq => lib::llvm::IntEQ,
583 ast::ne => lib::llvm::IntNE,
584 ast::lt => lib::llvm::IntULT,
585 ast::le => lib::llvm::IntULE,
586 ast::gt => lib::llvm::IntUGT,
587 ast::ge => lib::llvm::IntUGE,
590 return ICmp(cx, cmp, lhs, rhs);
595 pub type val_and_ty_fn<'self> = &'self fn(block, ValueRef, ty::t) -> block;
597 pub fn load_inbounds(cx: block, p: ValueRef, idxs: &[uint]) -> ValueRef {
598 return Load(cx, GEPi(cx, p, idxs));
601 pub fn store_inbounds(cx: block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
602 Store(cx, v, GEPi(cx, p, idxs));
605 // Iterates through the elements of a structural type.
606 pub fn iter_structural_ty(cx: block, av: ValueRef, t: ty::t,
607 f: val_and_ty_fn) -> block {
608 let _icx = push_ctxt("iter_structural_ty");
610 fn iter_variant(cx: block, repr: &adt::Repr, av: ValueRef,
611 variant: ty::VariantInfo,
612 tps: &[ty::t], f: val_and_ty_fn) -> block {
613 let _icx = push_ctxt("iter_variant");
617 for variant.args.iter().enumerate().advance |(i, &arg)| {
619 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
620 ty::subst_tps(tcx, tps, None, arg));
626 match ty::get(t).sty {
627 ty::ty_struct(*) => {
628 let repr = adt::represent_type(cx.ccx(), t);
629 do expr::with_field_tys(cx.tcx(), t, None) |discr, field_tys| {
630 for field_tys.iter().enumerate().advance |(i, field_ty)| {
631 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
632 cx = f(cx, llfld_a, field_ty.mt.ty);
636 ty::ty_estr(ty::vstore_fixed(_)) |
637 ty::ty_evec(_, ty::vstore_fixed(_)) => {
638 let (base, len) = tvec::get_base_and_len(cx, av, t);
639 cx = tvec::iter_vec_raw(cx, base, t, len, f);
641 ty::ty_tup(ref args) => {
642 let repr = adt::represent_type(cx.ccx(), t);
643 for args.iter().enumerate().advance |(i, arg)| {
644 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
645 cx = f(cx, llfld_a, *arg);
648 ty::ty_enum(tid, ref substs) => {
651 let repr = adt::represent_type(ccx, t);
652 let variants = ty::enum_variants(ccx.tcx, tid);
653 let n_variants = (*variants).len();
655 // NB: we must hit the discriminant first so that structural
656 // comparison know not to proceed when the discriminants differ.
658 match adt::trans_switch(cx, repr, av) {
659 (_match::single, None) => {
660 cx = iter_variant(cx, repr, av, variants[0],
663 (_match::switch, Some(lldiscrim_a)) => {
664 cx = f(cx, lldiscrim_a, ty::mk_int());
665 let unr_cx = sub_block(cx, "enum-iter-unr");
667 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
669 let next_cx = sub_block(cx, "enum-iter-next");
671 for (*variants).iter().advance |variant| {
673 sub_block(cx, ~"enum-iter-variant-" +
674 int::to_str(variant.disr_val));
676 iter_variant(variant_cx, repr, av, *variant,
678 match adt::trans_case(cx, repr, variant.disr_val) {
679 _match::single_result(r) => {
680 AddCase(llswitch, r.val, variant_cx.llbb)
682 _ => ccx.sess.unimpl("value from adt::trans_case \
683 in iter_structural_ty")
685 Br(variant_cx, next_cx.llbb);
689 _ => ccx.sess.unimpl("value from adt::trans_switch \
690 in iter_structural_ty")
693 _ => cx.sess().unimpl("type in iter_structural_ty")
698 pub fn cast_shift_expr_rhs(cx: block, op: ast::binop,
699 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
700 cast_shift_rhs(op, lhs, rhs,
701 |a,b| Trunc(cx, a, b),
702 |a,b| ZExt(cx, a, b))
705 pub fn cast_shift_const_rhs(op: ast::binop,
706 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
707 cast_shift_rhs(op, lhs, rhs,
708 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
709 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
712 pub fn cast_shift_rhs(op: ast::binop,
713 lhs: ValueRef, rhs: ValueRef,
714 trunc: &fn(ValueRef, Type) -> ValueRef,
715 zext: &fn(ValueRef, Type) -> ValueRef)
717 // Shifts may have any size int on the rhs
719 if ast_util::is_shift_binop(op) {
720 let rhs_llty = val_ty(rhs);
721 let lhs_llty = val_ty(lhs);
722 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
723 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
726 } else if lhs_sz > rhs_sz {
727 // FIXME (#1877: If shifting by negative
728 // values becomes not undefined then this is wrong.
739 pub fn fail_if_zero(cx: block, span: span, divrem: ast::binop,
740 rhs: ValueRef, rhs_t: ty::t) -> block {
741 let text = if divrem == ast::div {
742 @"attempted to divide by zero"
744 @"attempted remainder with a divisor of zero"
746 let is_zero = match ty::get(rhs_t).sty {
748 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
749 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
752 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
753 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
756 cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
757 ty_to_str(cx.ccx().tcx, rhs_t));
760 do with_cond(cx, is_zero) |bcx| {
761 controlflow::trans_fail(bcx, Some(span), text)
765 pub fn null_env_ptr(bcx: block) -> ValueRef {
766 C_null(Type::opaque_box(bcx.ccx()).ptr_to())
769 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::def_id, t: ty::t)
771 let name = csearch::get_symbol(ccx.sess.cstore, did).to_managed(); // Sad
772 match ty::get(t).sty {
773 ty::ty_bare_fn(_) | ty::ty_closure(_) => {
774 let llty = type_of_fn_from_ty(ccx, t);
775 return get_extern_fn(&mut ccx.externs, ccx.llmod, name,
776 lib::llvm::CCallConv, llty);
779 let llty = type_of(ccx, t);
780 return get_extern_const(&mut ccx.externs, ccx.llmod, name, llty);
785 pub fn invoke(bcx: block, llfn: ValueRef, llargs: ~[ValueRef])
786 -> (ValueRef, block) {
787 let _icx = push_ctxt("invoke_");
789 return (C_null(Type::i8()), bcx);
792 match bcx.node_info {
793 None => debug!("invoke at ???"),
795 debug!("invoke at %s",
796 bcx.sess().codemap.span_to_str(node_info.span));
800 if need_invoke(bcx) {
802 debug!("invoking %x at %x",
803 ::core::cast::transmute(llfn),
804 ::core::cast::transmute(bcx.llbb));
805 for llargs.iter().advance |&llarg| {
806 debug!("arg: %x", ::core::cast::transmute(llarg));
809 let normal_bcx = sub_block(bcx, "normal return");
810 let llresult = Invoke(bcx,
814 get_landing_pad(bcx));
815 return (llresult, normal_bcx);
818 debug!("calling %x at %x",
819 ::core::cast::transmute(llfn),
820 ::core::cast::transmute(bcx.llbb));
821 for llargs.iter().advance |&llarg| {
822 debug!("arg: %x", ::core::cast::transmute(llarg));
825 let llresult = Call(bcx, llfn, llargs);
826 return (llresult, bcx);
830 pub fn need_invoke(bcx: block) -> bool {
831 if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
835 // Avoid using invoke if we are already inside a landing pad.
840 if have_cached_lpad(bcx) {
844 // Walk the scopes to look for cleanups
848 block_scope(inf) => {
849 let inf = &mut *inf; // FIXME(#5074) workaround old borrowck
850 for inf.cleanups.iter().advance |cleanup| {
852 clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
853 if cleanup_type == normal_exit_and_unwind {
862 cur = match cur.parent {
869 pub fn have_cached_lpad(bcx: block) -> bool {
871 do in_lpad_scope_cx(bcx) |inf| {
872 match inf.landing_pad {
873 Some(_) => res = true,
880 pub fn in_lpad_scope_cx(bcx: block, f: &fn(si: &mut scope_info)) {
885 block_scope(inf) => {
886 let len = { // FIXME(#5074) workaround old borrowck
890 if len > 0u || bcx.parent.is_none() {
898 bcx = block_parent(bcx);
902 pub fn get_landing_pad(bcx: block) -> BasicBlockRef {
903 let _icx = push_ctxt("get_landing_pad");
905 let mut cached = None;
906 let mut pad_bcx = bcx; // Guaranteed to be set below
907 do in_lpad_scope_cx(bcx) |inf| {
908 // If there is a valid landing pad still around, use it
909 match inf.landing_pad {
910 Some(target) => cached = Some(target),
912 pad_bcx = lpad_block(bcx, "unwind");
913 inf.landing_pad = Some(pad_bcx.llbb);
917 // Can't return from block above
918 match cached { Some(b) => return b, None => () }
919 // The landing pad return type (the type being propagated). Not sure what
920 // this represents but it's determined by the personality function and
921 // this is what the EH proposal example uses.
922 let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
923 // The exception handling personality function. This is the C++
924 // personality function __gxx_personality_v0, wrapped in our naming
926 let personality = bcx.ccx().upcalls.rust_personality;
927 // The only landing pad clause will be 'cleanup'
928 let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
929 // The landing pad block is a cleanup
930 SetCleanup(pad_bcx, llretval);
932 // Because we may have unwound across a stack boundary, we must call into
933 // the runtime to figure out which stack segment we are on and place the
934 // stack limit back into the TLS.
935 Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, []);
937 // We store the retval in a function-central alloca, so that calls to
938 // Resume can find it.
939 match bcx.fcx.personality {
940 Some(addr) => Store(pad_bcx, llretval, addr),
942 let addr = alloca(pad_bcx, val_ty(llretval));
943 bcx.fcx.personality = Some(addr);
944 Store(pad_bcx, llretval, addr);
948 // Unwind all parent scopes, and finish with a Resume instr
949 cleanup_and_leave(pad_bcx, None, None);
953 pub fn find_bcx_for_scope(bcx: block, scope_id: ast::node_id) -> block {
954 let mut bcx_sid = bcx;
956 bcx_sid = match bcx_sid.node_info {
957 Some(NodeInfo { id, _ }) if id == scope_id => {
961 // FIXME(#6268, #6248) hacky cleanup for nested method calls
962 Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
967 match bcx_sid.parent {
968 None => bcx.tcx().sess.bug(
969 fmt!("no enclosing scope with id %d", scope_id)),
970 Some(bcx_par) => bcx_par
978 pub fn do_spill(bcx: block, v: ValueRef, t: ty::t) -> ValueRef {
979 if ty::type_is_bot(t) {
980 return C_null(Type::i8p());
982 let llptr = alloc_ty(bcx, t);
983 Store(bcx, v, llptr);
987 // Since this function does *not* root, it is the caller's responsibility to
988 // ensure that the referent is pointed to by a root.
989 pub fn do_spill_noroot(cx: block, v: ValueRef) -> ValueRef {
990 let llptr = alloca(cx, val_ty(v));
995 pub fn spill_if_immediate(cx: block, v: ValueRef, t: ty::t) -> ValueRef {
996 let _icx = push_ctxt("spill_if_immediate");
997 if ty::type_is_immediate(t) { return do_spill(cx, v, t); }
1001 pub fn load_if_immediate(cx: block, v: ValueRef, t: ty::t) -> ValueRef {
1002 let _icx = push_ctxt("load_if_immediate");
1003 if ty::type_is_immediate(t) { return Load(cx, v); }
1007 pub fn trans_trace(bcx: block, sp_opt: Option<span>, trace_str: @str) {
1008 if !bcx.sess().trace() { return; }
1009 let _icx = push_ctxt("trans_trace");
1010 add_comment(bcx, trace_str);
1011 let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1012 let (V_filename, V_line) = match sp_opt {
1014 let sess = bcx.sess();
1015 let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1016 (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1019 (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1022 let ccx = bcx.ccx();
1023 let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1024 let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1025 let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1026 Call(bcx, ccx.upcalls.trace, args);
1029 pub fn build_return(bcx: block) {
1030 let _icx = push_ctxt("build_return");
1031 Br(bcx, bcx.fcx.llreturn);
1034 pub fn ignore_lhs(_bcx: block, local: &ast::local) -> bool {
1035 match local.node.pat.node {
1036 ast::pat_wild => true, _ => false
1040 pub fn init_local(bcx: block, local: &ast::local) -> block {
1042 debug!("init_local(bcx=%s, local.id=%?)",
1043 bcx.to_str(), local.node.id);
1044 let _indenter = indenter();
1046 let _icx = push_ctxt("init_local");
1047 let ty = node_id_type(bcx, local.node.id);
1049 debug!("ty=%s", bcx.ty_to_str(ty));
1051 if ignore_lhs(bcx, local) {
1052 // Handle let _ = e; just like e;
1053 match local.node.init {
1055 return expr::trans_into(bcx, init, expr::Ignore);
1057 None => { return bcx; }
1061 let llptr = match bcx.fcx.lllocals.find_copy(&local.node.id) {
1064 bcx.tcx().sess.span_bug(local.span,
1065 "init_local: Someone forgot to document why it's\
1066 safe to assume local.node.init must be local_mem!");
1071 match local.node.init {
1073 bcx = expr::trans_into(bcx, init, expr::SaveIn(llptr));
1076 zero_mem(bcx, llptr, ty);
1080 // Make a note to drop this slot on the way out.
1081 debug!("adding clean for %?/%s to bcx=%s",
1082 local.node.id, bcx.ty_to_str(ty),
1084 add_clean(bcx, llptr, ty);
1086 return _match::bind_irrefutable_pat(bcx,
1093 pub fn trans_stmt(cx: block, s: &ast::stmt) -> block {
1094 let _icx = push_ctxt("trans_stmt");
1095 debug!("trans_stmt(%s)", stmt_to_str(s, cx.tcx().sess.intr()));
1097 if cx.sess().asm_comments() {
1098 add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1102 debuginfo::update_source_pos(cx, s.span);
1105 ast::stmt_expr(e, _) | ast::stmt_semi(e, _) => {
1106 bcx = expr::trans_into(cx, e, expr::Ignore);
1108 ast::stmt_decl(d, _) => {
1110 ast::decl_local(ref local) => {
1111 bcx = init_local(bcx, *local);
1112 if cx.sess().opts.extra_debuginfo
1113 && fcx_has_nonzero_span(bcx.fcx) {
1114 debuginfo::create_local_var(bcx, *local);
1117 ast::decl_item(i) => trans_item(cx.fcx.ccx, i)
1120 ast::stmt_mac(*) => cx.tcx().sess.bug("unexpanded macro")
1126 // You probably don't want to use this one. See the
1127 // next three functions instead.
1128 pub fn new_block(cx: fn_ctxt, parent: Option<block>, kind: block_kind,
1129 is_lpad: bool, name: &str, opt_node_info: Option<NodeInfo>)
1132 let s = if cx.ccx.sess.opts.save_temps || cx.ccx.sess.opts.debuginfo {
1133 (cx.ccx.names)(name)
1135 special_idents::invalid
1138 let llbb = str::as_c_str(cx.ccx.sess.str_of(s), |buf| {
1139 llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1141 let bcx = mk_block(llbb,
1147 for parent.iter().advance |cx| {
1148 if cx.unreachable { Unreachable(bcx); }
1154 pub fn simple_block_scope() -> block_kind {
1155 block_scope(@mut scope_info {
1164 // Use this when you're at the top block of a function or the like.
1165 pub fn top_scope_block(fcx: fn_ctxt, opt_node_info: Option<NodeInfo>)
1167 return new_block(fcx, None, simple_block_scope(), false,
1168 "function top level", opt_node_info);
1171 pub fn scope_block(bcx: block,
1172 opt_node_info: Option<NodeInfo>,
1174 return new_block(bcx.fcx, Some(bcx), simple_block_scope(), bcx.is_lpad,
1178 pub fn loop_scope_block(bcx: block,
1180 loop_label: Option<ident>,
1182 opt_node_info: Option<NodeInfo>) -> block {
1183 return new_block(bcx.fcx, Some(bcx), block_scope(@mut scope_info {
1184 loop_break: Some(loop_break),
1185 loop_label: loop_label,
1189 }), bcx.is_lpad, n, opt_node_info);
1192 // Use this when creating a block for the inside of a landing pad.
1193 pub fn lpad_block(bcx: block, n: &str) -> block {
1194 new_block(bcx.fcx, Some(bcx), block_non_scope, true, n, None)
1197 // Use this when you're making a general CFG BB within a scope.
1198 pub fn sub_block(bcx: block, n: &str) -> block {
1199 new_block(bcx.fcx, Some(bcx), block_non_scope, bcx.is_lpad, n, None)
1202 pub fn raw_block(fcx: fn_ctxt, is_lpad: bool, llbb: BasicBlockRef) -> block {
1203 mk_block(llbb, None, block_non_scope, is_lpad, None, fcx)
1207 // trans_block_cleanups: Go through all the cleanups attached to this
1208 // block and execute them.
1210 // When translating a block that introduces new variables during its scope, we
1211 // need to make sure those variables go out of scope when the block ends. We
1212 // do that by running a 'cleanup' function for each variable.
1213 // trans_block_cleanups runs all the cleanup functions for the block.
1214 pub fn trans_block_cleanups(bcx: block, cleanups: ~[cleanup]) -> block {
1215 trans_block_cleanups_(bcx, cleanups, false)
1218 pub fn trans_block_cleanups_(bcx: block,
1219 cleanups: &[cleanup],
1220 /* cleanup_cx: block, */
1221 is_lpad: bool) -> block {
1222 let _icx = push_ctxt("trans_block_cleanups");
1223 // NB: Don't short-circuit even if this block is unreachable because
1224 // GC-based cleanup needs to the see that the roots are live.
1226 bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1227 if bcx.unreachable && !no_lpads { return bcx; }
1229 for cleanups.rev_iter().advance |cu| {
1231 clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1232 // Some types don't need to be cleaned up during
1233 // landing pads because they can be freed en mass later
1234 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1243 // In the last argument, Some(block) mean jump to this block, and none means
1244 // this is a landing pad and leaving should be accomplished with a resume
1246 pub fn cleanup_and_leave(bcx: block,
1247 upto: Option<BasicBlockRef>,
1248 leave: Option<BasicBlockRef>) {
1249 let _icx = push_ctxt("cleanup_and_leave");
1252 let is_lpad = leave == None;
1254 debug!("cleanup_and_leave: leaving %s", cur.to_str());
1256 if bcx.sess().trace() {
1259 (fmt!("cleanup_and_leave(%s)", cur.to_str())).to_managed());
1263 block_scope(inf) if !inf.empty_cleanups() => {
1264 let (sub_cx, dest, inf_cleanups) = {
1265 let inf = &mut *inf;
1267 let mut dest = None;
1269 let r = vec::rfind((*inf).cleanup_paths, |cp| cp.target == leave);
1270 for r.iter().advance |cp| {
1271 if cp.size == inf.cleanups.len() {
1277 dest = Some(cp.dest);
1280 let sub_cx = sub_block(bcx, "cleanup");
1281 Br(bcx, sub_cx.llbb);
1282 inf.cleanup_paths.push(cleanup_path {
1284 size: inf.cleanups.len(),
1287 (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1289 bcx = trans_block_cleanups_(sub_cx,
1292 for dest.iter().advance |&dest| {
1301 Some(bb) => { if cur.llbb == bb { break; } }
1304 cur = match cur.parent {
1306 None => { assert!(upto.is_none()); break; }
1310 Some(target) => Br(bcx, target),
1311 None => { Resume(bcx, Load(bcx, bcx.fcx.personality.get())); }
1315 pub fn cleanup_and_Br(bcx: block, upto: block, target: BasicBlockRef) {
1316 let _icx = push_ctxt("cleanup_and_Br");
1317 cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1320 pub fn leave_block(bcx: block, out_of: block) -> block {
1321 let _icx = push_ctxt("leave_block");
1322 let next_cx = sub_block(block_parent(out_of), "next");
1323 if bcx.unreachable { Unreachable(next_cx); }
1324 cleanup_and_Br(bcx, out_of, next_cx.llbb);
1328 pub fn with_scope(bcx: block,
1329 opt_node_info: Option<NodeInfo>,
1331 f: &fn(block) -> block) -> block {
1332 let _icx = push_ctxt("with_scope");
1334 debug!("with_scope(bcx=%s, opt_node_info=%?, name=%s)",
1335 bcx.to_str(), opt_node_info, name);
1336 let _indenter = indenter();
1338 let scope_cx = scope_block(bcx, opt_node_info, name);
1339 Br(bcx, scope_cx.llbb);
1340 leave_block(f(scope_cx), scope_cx)
1343 pub fn with_scope_result(bcx: block,
1344 opt_node_info: Option<NodeInfo>,
1346 f: &fn(block) -> Result) -> Result {
1347 let _icx = push_ctxt("with_scope_result");
1348 let scope_cx = scope_block(bcx, opt_node_info, name);
1349 Br(bcx, scope_cx.llbb);
1350 let Result {bcx, val} = f(scope_cx);
1351 rslt(leave_block(bcx, scope_cx), val)
1354 pub fn with_scope_datumblock(bcx: block, opt_node_info: Option<NodeInfo>,
1355 name: &str, f: &fn(block) -> datum::DatumBlock)
1356 -> datum::DatumBlock {
1357 use middle::trans::datum::DatumBlock;
1359 let _icx = push_ctxt("with_scope_result");
1360 let scope_cx = scope_block(bcx, opt_node_info, name);
1361 Br(bcx, scope_cx.llbb);
1362 let DatumBlock {bcx, datum} = f(scope_cx);
1363 DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1366 pub fn block_locals(b: &ast::blk, it: &fn(@ast::local)) {
1367 for b.node.stmts.iter().advance |s| {
1369 ast::stmt_decl(d, _) => {
1371 ast::decl_local(ref local) => it(*local),
1372 _ => {} /* fall through */
1375 _ => {} /* fall through */
1380 pub fn alloc_local(cx: block, local: &ast::local) -> block {
1381 let _icx = push_ctxt("alloc_local");
1382 let t = node_id_type(cx, local.node.id);
1383 let simple_name = match local.node.pat.node {
1384 ast::pat_ident(_, pth, None) => Some(path_to_ident(pth)),
1387 let val = alloc_ty(cx, t);
1388 if cx.sess().opts.debuginfo {
1389 for simple_name.iter().advance |name| {
1390 str::as_c_str(cx.ccx().sess.str_of(*name), |buf| {
1392 llvm::LLVMSetValueName(val, buf)
1397 cx.fcx.lllocals.insert(local.node.id, val);
1402 pub fn with_cond(bcx: block, val: ValueRef, f: &fn(block) -> block) -> block {
1403 let _icx = push_ctxt("with_cond");
1404 let next_cx = base::sub_block(bcx, "next");
1405 let cond_cx = base::sub_block(bcx, "cond");
1406 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1407 let after_cx = f(cond_cx);
1408 if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1412 pub fn call_memcpy(cx: block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1413 let _icx = push_ctxt("call_memcpy");
1415 let key = match ccx.sess.targ_cfg.arch {
1416 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1417 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1419 let memcpy = ccx.intrinsics.get_copy(&key);
1420 let src_ptr = PointerCast(cx, src, Type::i8p());
1421 let dst_ptr = PointerCast(cx, dst, Type::i8p());
1422 let size = IntCast(cx, n_bytes, ccx.int_type);
1423 let align = C_i32(align as i32);
1424 let volatile = C_i1(false);
1425 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile]);
1428 pub fn memcpy_ty(bcx: block, dst: ValueRef, src: ValueRef, t: ty::t) {
1429 let _icx = push_ctxt("memcpy_ty");
1430 let ccx = bcx.ccx();
1431 if ty::type_is_structural(t) {
1432 let llty = type_of::type_of(ccx, t);
1433 let llsz = llsize_of(ccx, llty);
1434 let llalign = llalign_of_min(ccx, llty);
1435 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1437 Store(bcx, Load(bcx, src), dst);
1441 pub fn zero_mem(cx: block, llptr: ValueRef, t: ty::t) {
1442 let _icx = push_ctxt("zero_mem");
1445 let llty = type_of::type_of(ccx, t);
1446 memzero(bcx, llptr, llty);
1449 // Always use this function instead of storing a zero constant to the memory
1450 // in question. If you store a zero constant, LLVM will drown in vreg
1451 // allocation for large data structures, and the generated code will be
1452 // awful. (A telltale sign of this is large quantities of
1453 // `mov [byte ptr foo],0` in the generated code.)
1454 pub fn memzero(cx: block, llptr: ValueRef, ty: Type) {
1455 let _icx = push_ctxt("memzero");
1458 let intrinsic_key = match ccx.sess.targ_cfg.arch {
1459 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1460 X86_64 => "llvm.memset.p0i8.i64"
1463 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1464 let llptr = PointerCast(cx, llptr, Type::i8().ptr_to());
1465 let llzeroval = C_u8(0);
1466 let size = IntCast(cx, machine::llsize_of(ccx, ty), ccx.int_type);
1467 let align = C_i32(llalign_of_min(ccx, ty) as i32);
1468 let volatile = C_i1(false);
1469 Call(cx, llintrinsicfn, [llptr, llzeroval, size, align, volatile]);
1472 pub fn alloc_ty(bcx: block, t: ty::t) -> ValueRef {
1473 let _icx = push_ctxt("alloc_ty");
1474 let ccx = bcx.ccx();
1475 let ty = type_of::type_of(ccx, t);
1476 assert!(!ty::type_has_params(t), "Type has params: %s", ty_to_str(ccx.tcx, t));
1477 let val = alloca(bcx, ty);
1481 pub fn alloca(cx: block, ty: Type) -> ValueRef {
1482 alloca_maybe_zeroed(cx, ty, false)
1485 pub fn alloca_maybe_zeroed(cx: block, ty: Type, zero: bool) -> ValueRef {
1486 let _icx = push_ctxt("alloca");
1489 return llvm::LLVMGetUndef(ty.to_ref());
1492 let initcx = base::raw_block(cx.fcx, false, cx.fcx.llstaticallocas);
1493 let p = Alloca(initcx, ty);
1494 if zero { memzero(initcx, p, ty); }
1498 pub fn arrayalloca(cx: block, ty: Type, v: ValueRef) -> ValueRef {
1499 let _icx = push_ctxt("arrayalloca");
1502 return llvm::LLVMGetUndef(ty.to_ref());
1505 return ArrayAlloca(base::raw_block(cx.fcx, false, cx.fcx.llstaticallocas), ty, v);
1508 pub struct BasicBlocks {
1513 // Creates the standard set of basic blocks for a function
1514 pub fn mk_standard_basic_blocks(llfn: ValueRef) -> BasicBlocks {
1516 let cx = task_llcx();
1518 sa: str::as_c_str("static_allocas",
1519 |buf| llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)),
1520 rt: str::as_c_str("return",
1521 |buf| llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf))
1526 // Creates and returns space for, or returns the argument representing, the
1527 // slot where the return value of the function must go.
1528 pub fn make_return_pointer(fcx: fn_ctxt, output_type: ty::t) -> ValueRef {
1530 if !ty::type_is_immediate(output_type) {
1531 llvm::LLVMGetParam(fcx.llfn, 0)
1533 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1534 alloca(raw_block(fcx, false, fcx.llstaticallocas), lloutputtype)
1539 // NB: must keep 4 fns in sync:
1542 // - create_llargs_for_fn_args.
1545 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1550 impl_id: Option<ast::def_id>,
1551 param_substs: Option<@param_substs>,
1554 for param_substs.iter().advance |p| { p.validate(); }
1556 debug!("new_fn_ctxt_w_id(path=%s, id=%?, impl_id=%?, \
1558 path_str(ccx.sess, path),
1561 param_substs.repr(ccx.tcx));
1563 let llbbs = mk_standard_basic_blocks(llfndecl);
1565 let substd_output_type = match param_substs {
1566 None => output_type,
1568 ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1571 let is_immediate = ty::type_is_immediate(substd_output_type);
1572 let fcx = @mut fn_ctxt_ {
1575 llvm::LLVMGetUndef(Type::i8p().to_ref())
1578 llstaticallocas: llbbs.sa,
1584 has_immediate_return_value: is_immediate,
1585 llargs: @mut HashMap::new(),
1586 lllocals: @mut HashMap::new(),
1587 llupvars: @mut HashMap::new(),
1590 param_substs: param_substs,
1595 fcx.llenv = unsafe {
1596 llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1598 if !ty::type_is_nil(substd_output_type) {
1599 fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1604 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1610 new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, None, None, sp)
1613 // NB: must keep 4 fns in sync:
1616 // - create_llargs_for_fn_args.
1620 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1621 // allocas created for them.
1623 // When we translate a function, we need to map its incoming arguments to the
1624 // spaces that have been created for them (by code in the llallocas field of
1625 // the function's fn_ctxt). create_llargs_for_fn_args populates the llargs
1626 // field of the fn_ctxt with
1627 pub fn create_llargs_for_fn_args(cx: fn_ctxt,
1631 let _icx = push_ctxt("create_llargs_for_fn_args");
1635 cx.llself = Some(ValSelfData {
1641 impl_owned_self(tt) => {
1642 cx.llself = Some(ValSelfData {
1651 // Return an array containing the ValueRefs that we get from
1652 // llvm::LLVMGetParam for each argument.
1653 vec::from_fn(args.len(), |i| {
1655 let arg_n = cx.arg_pos(i);
1657 let llarg = llvm::LLVMGetParam(cx.llfn, arg_n as c_uint);
1660 // `~` pointers never alias other parameters, because ownership was transferred
1661 ast::ty_uniq(_) => {
1662 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
1664 // FIXME: #6785: `&mut` can only alias `&const` and `@mut`, we should check for
1665 // those in the other parameters and then mark it as `noalias` if there aren't any
1674 pub fn copy_args_to_allocas(fcx: fn_ctxt,
1677 raw_llargs: &[ValueRef],
1678 arg_tys: &[ty::t]) -> block {
1679 let _icx = push_ctxt("copy_args_to_allocas");
1684 let self_val = PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to());
1685 fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1688 add_clean(bcx, slf.v, slf.t);
1694 for uint::range(0, arg_tys.len()) |arg_n| {
1695 let arg_ty = arg_tys[arg_n];
1696 let raw_llarg = raw_llargs[arg_n];
1697 let arg_id = args[arg_n].id;
1699 // For certain mode/type combinations, the raw llarg values are passed
1700 // by value. However, within the fn body itself, we want to always
1701 // have all locals and arguments be by-ref so that we can cancel the
1702 // cleanup and for better interaction with LLVM's debug info. So, if
1703 // the argument would be passed by value, we store it into an alloca.
1704 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1705 // the event it's not truly needed.
1706 // only by value if immediate:
1707 let llarg = if datum::appropriate_mode(arg_ty).is_by_value() {
1708 let alloc = alloc_ty(bcx, arg_ty);
1709 Store(bcx, raw_llarg, alloc);
1715 add_clean(bcx, llarg, arg_ty);
1717 bcx = _match::bind_irrefutable_pat(bcx,
1721 _match::BindArgument);
1723 fcx.llargs.insert(arg_id, llarg);
1725 if fcx.ccx.sess.opts.extra_debuginfo && fcx_has_nonzero_span(fcx) {
1726 debuginfo::create_arg(bcx, args[arg_n], args[arg_n].ty.span);
1733 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1734 // and builds the return block.
1735 pub fn finish_fn(fcx: fn_ctxt, lltop: BasicBlockRef) {
1736 let _icx = push_ctxt("finish_fn");
1737 tie_up_header_blocks(fcx, lltop);
1738 build_return_block(fcx);
1741 // Builds the return block for a function.
1742 pub fn build_return_block(fcx: fn_ctxt) {
1743 let ret_cx = raw_block(fcx, false, fcx.llreturn);
1745 // Return the value if this function immediate; otherwise, return void.
1746 if fcx.llretptr.is_some() && fcx.has_immediate_return_value {
1747 Ret(ret_cx, Load(ret_cx, fcx.llretptr.get()))
1753 pub fn tie_up_header_blocks(fcx: fn_ctxt, lltop: BasicBlockRef) {
1754 let _icx = push_ctxt("tie_up_header_blocks");
1755 match fcx.llloadenv {
1757 Br(raw_block(fcx, false, fcx.llstaticallocas), ll);
1758 Br(raw_block(fcx, false, ll), lltop);
1761 Br(raw_block(fcx, false, fcx.llstaticallocas), lltop);
1766 pub enum self_arg { impl_self(ty::t), impl_owned_self(ty::t), no_self, }
1768 // trans_closure: Builds an LLVM function out of a source function.
1769 // If the function closes over its environment a closure will be
1771 pub fn trans_closure(ccx: @mut CrateContext,
1773 decl: &ast::fn_decl,
1777 param_substs: Option<@param_substs>,
1779 impl_id: Option<ast::def_id>,
1780 attributes: &[ast::attribute],
1782 maybe_load_env: &fn(fn_ctxt),
1783 finish: &fn(block)) {
1784 ccx.stats.n_closures += 1;
1785 let _icx = push_ctxt("trans_closure");
1786 set_uwtable(llfndecl);
1788 debug!("trans_closure(..., param_substs=%s)",
1789 param_substs.repr(ccx.tcx));
1791 // Set up arguments to the function.
1792 let fcx = new_fn_ctxt_w_id(ccx,
1800 let raw_llargs = create_llargs_for_fn_args(fcx, self_arg, decl.inputs);
1802 // Set the fixed stack segment flag if necessary.
1803 if attr::attrs_contains_name(attributes, "fixed_stack_segment") {
1804 set_no_inline(fcx.llfn);
1805 set_fixed_stack_segment(fcx.llfn);
1808 // Create the first basic block in the function and keep a handle on it to
1809 // pass to finish_fn later.
1810 let bcx_top = top_scope_block(fcx, body.info());
1811 let mut bcx = bcx_top;
1812 let lltop = bcx.llbb;
1813 let block_ty = node_id_type(bcx, body.node.id);
1815 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1816 bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1818 maybe_load_env(fcx);
1820 // This call to trans_block is the place where we bridge between
1821 // translation calls that don't have a return value (trans_crate,
1822 // trans_mod, trans_item, et cetera) and those that do
1823 // (trans_block, trans_expr, et cetera).
1824 if body.node.expr.is_none() || ty::type_is_bot(block_ty) ||
1825 ty::type_is_nil(block_ty)
1827 bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1829 let dest = expr::SaveIn(fcx.llretptr.get());
1830 bcx = controlflow::trans_block(bcx, body, dest);
1834 cleanup_and_Br(bcx, bcx_top, fcx.llreturn);
1836 // Put return block after all other blocks.
1837 // This somewhat improves single-stepping experience in debugger.
1839 llvm::LLVMMoveBasicBlockAfter(fcx.llreturn, bcx.llbb);
1842 // Insert the mandatory first few basic blocks before lltop.
1843 finish_fn(fcx, lltop);
1846 // trans_fn: creates an LLVM function corresponding to a source language
1848 pub fn trans_fn(ccx: @mut CrateContext,
1850 decl: &ast::fn_decl,
1854 param_substs: Option<@param_substs>,
1856 impl_id: Option<ast::def_id>,
1857 attrs: &[ast::attribute]) {
1858 let do_time = ccx.sess.trans_stats();
1859 let start = if do_time { time::get_time() }
1860 else { time::Timespec::new(0, 0) };
1861 debug!("trans_fn(self_arg=%?, param_substs=%s)",
1863 param_substs.repr(ccx.tcx));
1864 let _icx = push_ctxt("trans_fn");
1865 ccx.stats.n_fns += 1;
1866 let the_path_str = path_str(ccx.sess, path);
1867 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1880 if ccx.sess.opts.extra_debuginfo
1881 && fcx_has_nonzero_span(fcx) {
1882 debuginfo::create_function(fcx);
1887 let end = time::get_time();
1888 ccx.log_fn_time(the_path_str, start, end);
1892 pub fn trans_enum_variant(ccx: @mut CrateContext,
1893 enum_id: ast::node_id,
1894 variant: &ast::variant,
1895 args: &[ast::variant_arg],
1897 param_substs: Option<@param_substs>,
1898 llfndecl: ValueRef) {
1899 let _icx = push_ctxt("trans_enum_variant");
1900 // Translate variant arguments to function arguments.
1901 let fn_args = do args.map |varg| {
1905 pat: ast_util::ident_to_pat(
1906 ccx.tcx.sess.next_node_id(),
1907 codemap::dummy_sp(),
1908 special_idents::arg),
1913 let ty_param_substs = match param_substs {
1914 Some(ref substs) => { copy substs.tys }
1917 let enum_ty = ty::subst_tps(ccx.tcx,
1920 ty::node_id_to_type(ccx.tcx, enum_id));
1921 let fcx = new_fn_ctxt_w_id(ccx,
1930 let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
1931 let bcx = top_scope_block(fcx, None);
1932 let lltop = bcx.llbb;
1933 let arg_tys = ty::ty_fn_args(node_id_type(bcx, variant.node.id));
1934 let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
1936 // XXX is there a better way to reconstruct the ty::t?
1937 let repr = adt::represent_type(ccx, enum_ty);
1939 debug!("trans_enum_variant: name=%s tps=%s repr=%? enum_ty=%s",
1940 unsafe { str::raw::from_c_str(llvm::LLVMGetValueName(llfndecl)) },
1941 ~"[" + ty_param_substs.map(|&t| ty_to_str(ccx.tcx, t)).connect(", ") + "]",
1942 repr, ty_to_str(ccx.tcx, enum_ty));
1944 adt::trans_start_init(bcx, repr, fcx.llretptr.get(), disr);
1945 for args.iter().enumerate().advance |(i, va)| {
1946 let lldestptr = adt::trans_field_ptr(bcx,
1952 // If this argument to this function is a enum, it'll have come in to
1953 // this function as an opaque blob due to the way that type_of()
1954 // works. So we have to cast to the destination's view of the type.
1955 let llarg = match fcx.llargs.find(&va.id) {
1957 _ => fail!("trans_enum_variant: how do we know this works?"),
1959 let arg_ty = arg_tys[i];
1960 memcpy_ty(bcx, lldestptr, llarg, arg_ty);
1963 finish_fn(fcx, lltop);
1966 // NB: In theory this should be merged with the function above. But the AST
1967 // structures are completely different, so very little code would be shared.
1968 pub fn trans_tuple_struct(ccx: @mut CrateContext,
1969 fields: &[@ast::struct_field],
1970 ctor_id: ast::node_id,
1971 param_substs: Option<@param_substs>,
1972 llfndecl: ValueRef) {
1973 let _icx = push_ctxt("trans_tuple_struct");
1975 // Translate struct fields to function arguments.
1976 let fn_args = do fields.map |field| {
1980 pat: ast_util::ident_to_pat(ccx.tcx.sess.next_node_id(),
1981 codemap::dummy_sp(),
1982 special_idents::arg),
1987 // XXX is there a better way to reconstruct the ty::t?
1988 let ty_param_substs = match param_substs {
1989 Some(ref substs) => { copy substs.tys }
1992 let ctor_ty = ty::subst_tps(ccx.tcx, ty_param_substs, None,
1993 ty::node_id_to_type(ccx.tcx, ctor_id));
1994 let tup_ty = match ty::get(ctor_ty).sty {
1995 ty::ty_bare_fn(ref bft) => bft.sig.output,
1996 _ => ccx.sess.bug(fmt!("trans_tuple_struct: unexpected ctor \
1998 ty_to_str(ccx.tcx, ctor_ty)))
2001 let fcx = new_fn_ctxt_w_id(ccx,
2010 let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
2012 let bcx = top_scope_block(fcx, None);
2013 let lltop = bcx.llbb;
2014 let arg_tys = ty::ty_fn_args(node_id_type(bcx, ctor_id));
2015 let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2017 let repr = adt::represent_type(ccx, tup_ty);
2018 adt::trans_start_init(bcx, repr, fcx.llretptr.get(), 0);
2020 for fields.iter().enumerate().advance |(i, field)| {
2021 let lldestptr = adt::trans_field_ptr(bcx,
2026 let llarg = fcx.llargs.get_copy(&field.node.id);
2027 let arg_ty = arg_tys[i];
2028 memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2032 finish_fn(fcx, lltop);
2035 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2036 id: ast::node_id, vi: @~[ty::VariantInfo],
2038 for enum_definition.variants.iter().advance |variant| {
2039 let disr_val = vi[*i].disr_val;
2042 match variant.node.kind {
2043 ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2044 let llfn = get_item_val(ccx, variant.node.id);
2045 trans_enum_variant(ccx, id, variant, *args,
2046 disr_val, None, llfn);
2048 ast::tuple_variant_kind(_) => {
2051 ast::struct_variant_kind(struct_def) => {
2052 trans_struct_def(ccx, struct_def);
2058 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2059 let _icx = push_ctxt("trans_item");
2060 let path = match ccx.tcx.items.get_copy(&item.id) {
2061 ast_map::node_item(_, p) => p,
2063 _ => fail!("trans_item"),
2066 ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2067 if purity == ast::extern_fn {
2068 let llfndecl = get_item_val(ccx, item.id);
2069 foreign::trans_foreign_fn(ccx,
2070 vec::append(/*bad*/copy *path,
2071 [path_name(item.ident)]),
2076 } else if !generics.is_type_parameterized() {
2077 let llfndecl = get_item_val(ccx, item.id);
2079 vec::append(/*bad*/copy *path, [path_name(item.ident)]),
2089 for body.node.stmts.iter().advance |stmt| {
2091 ast::stmt_decl(@codemap::spanned { node: ast::decl_item(i),
2100 ast::item_impl(ref generics, _, _, ref ms) => {
2101 meth::trans_impl(ccx, /*bad*/copy *path, item.ident, *ms,
2104 ast::item_mod(ref m) => {
2107 ast::item_enum(ref enum_definition, ref generics) => {
2108 if !generics.is_type_parameterized() {
2109 let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2111 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2114 ast::item_static(_, m, expr) => {
2115 consts::trans_const(ccx, m, item.id);
2116 // Do static_assert checking. It can't really be done much earlier because we need to get
2117 // the value of the bool out of LLVM
2118 for item.attrs.iter().advance |attr| {
2119 match attr.node.value.node {
2120 ast::meta_word(x) => {
2121 if x.slice(0, x.len()) == "static_assert" {
2122 if m == ast::m_mutbl {
2123 ccx.sess.span_fatal(expr.span,
2124 "cannot have static_assert \
2125 on a mutable static");
2127 let v = ccx.const_values.get_copy(&item.id);
2129 if !(llvm::LLVMConstIntGetZExtValue(v) as bool) {
2130 ccx.sess.span_fatal(expr.span, "static assertion failed");
2139 ast::item_foreign_mod(ref foreign_mod) => {
2140 foreign::trans_foreign_mod(ccx, path, foreign_mod);
2142 ast::item_struct(struct_def, ref generics) => {
2143 if !generics.is_type_parameterized() {
2144 trans_struct_def(ccx, struct_def);
2147 _ => {/* fall through */ }
2151 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2152 // If this is a tuple-like struct, translate the constructor.
2153 match struct_def.ctor_id {
2154 // We only need to translate a constructor if there are fields;
2155 // otherwise this is a unit-like struct.
2156 Some(ctor_id) if struct_def.fields.len() > 0 => {
2157 let llfndecl = get_item_val(ccx, ctor_id);
2158 trans_tuple_struct(ccx, struct_def.fields,
2159 ctor_id, None, llfndecl);
2161 Some(_) | None => {}
2165 // Translate a module. Doing this amounts to translating the items in the
2166 // module; there ends up being no artifact (aside from linkage names) of
2167 // separate modules in the compiled program. That's because modules exist
2168 // only as a convenience for humans working with the code, to organize names
2169 // and control visibility.
2170 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2171 let _icx = push_ctxt("trans_mod");
2172 for m.items.iter().advance |item| {
2173 trans_item(ccx, *item);
2177 pub fn register_fn(ccx: @mut CrateContext,
2180 node_id: ast::node_id,
2181 attrs: &[ast::attribute])
2183 let t = ty::node_id_to_type(ccx.tcx, node_id);
2184 register_fn_full(ccx, sp, path, node_id, attrs, t)
2187 pub fn register_fn_full(ccx: @mut CrateContext,
2190 node_id: ast::node_id,
2191 attrs: &[ast::attribute],
2194 let llfty = type_of_fn_from_ty(ccx, node_type);
2195 register_fn_fuller(ccx, sp, path, node_id, attrs, node_type,
2196 lib::llvm::CCallConv, llfty)
2199 pub fn register_fn_fuller(ccx: @mut CrateContext,
2202 node_id: ast::node_id,
2203 attrs: &[ast::attribute],
2205 cc: lib::llvm::CallConv,
2208 debug!("register_fn_fuller creating fn for item %d with path %s",
2210 ast_map::path_to_str(path, token::get_ident_interner()));
2212 let ps = if attr::attrs_contains_name(attrs, "no_mangle") {
2213 path_elt_to_str(*path.last(), token::get_ident_interner())
2215 mangle_exported_name(ccx, /*bad*/copy path, node_type)
2218 let llfn = decl_fn(ccx.llmod, ps, cc, fn_ty);
2219 ccx.item_symbols.insert(node_id, ps);
2221 // FIXME #4404 android JNI hacks
2222 let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2223 (*ccx.sess.building_library &&
2224 ccx.sess.targ_cfg.os == session::os_android));
2226 create_entry_wrapper(ccx, sp, llfn);
2231 pub fn is_entry_fn(sess: &Session, node_id: ast::node_id) -> bool {
2232 match *sess.entry_fn {
2233 Some((entry_id, _)) => node_id == entry_id,
2238 // Create a _rust_main(args: ~[str]) function which will be called from the
2239 // runtime rust_start function
2240 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2241 _sp: span, main_llfn: ValueRef) {
2242 let et = ccx.sess.entry_type.unwrap();
2243 if et == session::EntryMain {
2244 let llfn = create_main(ccx, main_llfn);
2245 create_entry_fn(ccx, llfn, true);
2247 create_entry_fn(ccx, main_llfn, false);
2250 fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
2251 let nt = ty::mk_nil();
2253 let llfty = type_of_fn(ccx, [], nt);
2254 let llfdecl = decl_fn(ccx.llmod, "_rust_main",
2255 lib::llvm::CCallConv, llfty);
2257 let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None);
2259 // the args vector built in create_entry_fn will need
2260 // be updated if this assertion starts to fail.
2261 assert!(fcx.has_immediate_return_value);
2263 let bcx = top_scope_block(fcx, None);
2264 let lltop = bcx.llbb;
2267 let llenvarg = unsafe {
2268 let env_arg = fcx.env_arg_pos();
2269 llvm::LLVMGetParam(llfdecl, env_arg as c_uint)
2271 let args = ~[llenvarg];
2272 Call(bcx, main_llfn, args);
2275 finish_fn(fcx, lltop);
2279 fn create_entry_fn(ccx: @mut CrateContext,
2280 rust_main: ValueRef,
2281 use_start_lang_item: bool) {
2282 let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()], &ccx.int_type);
2284 // FIXME #4404 android JNI hacks
2285 let llfn = if *ccx.sess.building_library {
2286 decl_cdecl_fn(ccx.llmod, "amain", llfty)
2288 let main_name = match ccx.sess.targ_cfg.os {
2289 session::os_win32 => ~"WinMain@16",
2292 decl_cdecl_fn(ccx.llmod, main_name, llfty)
2294 let llbb = str::as_c_str("top", |buf| {
2296 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2299 let bld = ccx.builder.B;
2301 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2303 let start_def_id = ccx.tcx.lang_items.start_fn();
2304 if start_def_id.crate != ast::local_crate {
2305 let start_fn_type = csearch::get_type(ccx.tcx,
2307 trans_external_path(ccx, start_def_id, start_fn_type);
2310 let crate_map = ccx.crate_map;
2311 let opaque_crate_map = do "crate_map".as_c_str |buf| {
2312 llvm::LLVMBuildPointerCast(bld, crate_map, Type::i8p().to_ref(), buf)
2315 let (start_fn, args) = if use_start_lang_item {
2316 let start_def_id = ccx.tcx.lang_items.start_fn();
2317 let start_fn = if start_def_id.crate == ast::local_crate {
2318 get_item_val(ccx, start_def_id.node)
2320 let start_fn_type = csearch::get_type(ccx.tcx,
2322 trans_external_path(ccx, start_def_id, start_fn_type)
2326 let opaque_rust_main = do "rust_main".as_c_str |buf| {
2327 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2331 C_null(Type::opaque_box(ccx).ptr_to()),
2333 llvm::LLVMGetParam(llfn, 0),
2334 llvm::LLVMGetParam(llfn, 1),
2340 debug!("using user-defined start fn");
2343 C_null(Type::opaque_box(ccx).ptr_to()),
2344 llvm::LLVMGetParam(llfn, 0 as c_uint),
2345 llvm::LLVMGetParam(llfn, 1 as c_uint),
2353 let result = llvm::LLVMBuildCall(bld,
2356 args.len() as c_uint,
2358 llvm::LLVMBuildRet(bld, result);
2363 pub fn fill_fn_pair(bcx: block, pair: ValueRef, llfn: ValueRef,
2364 llenvptr: ValueRef) {
2365 let ccx = bcx.ccx();
2366 let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2367 Store(bcx, llfn, code_cell);
2368 let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2369 let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2370 Store(bcx, llenvblobptr, env_cell);
2373 pub fn item_path(ccx: &CrateContext, i: &ast::item) -> path {
2374 let base = match ccx.tcx.items.get_copy(&i.id) {
2375 ast_map::node_item(_, p) => p,
2376 // separate map for paths?
2377 _ => fail!("item_path")
2379 vec::append(/*bad*/copy *base, [path_name(i.ident)])
2382 pub fn get_item_val(ccx: @mut CrateContext, id: ast::node_id) -> ValueRef {
2383 debug!("get_item_val(id=`%?`)", id);
2384 let val = ccx.item_vals.find_copy(&id);
2388 let mut exprt = false;
2389 let item = ccx.tcx.items.get_copy(&id);
2390 let val = match item {
2391 ast_map::node_item(i, pth) => {
2392 let my_path = vec::append(/*bad*/copy *pth,
2393 [path_name(i.ident)]);
2395 ast::item_static(_, m, expr) => {
2396 let typ = ty::node_id_to_type(ccx.tcx, i.id);
2397 let s = mangle_exported_name(ccx, my_path, typ);
2398 // We need the translated value here, because for enums the
2399 // LLVM type is not fully determined by the Rust type.
2400 let v = consts::const_expr(ccx, expr);
2401 ccx.const_values.insert(id, v);
2402 exprt = m == ast::m_mutbl;
2404 let llty = llvm::LLVMTypeOf(v);
2405 let g = str::as_c_str(s, |buf| {
2406 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2408 ccx.item_symbols.insert(i.id, s);
2412 ast::item_fn(_, purity, _, _, _) => {
2413 let llfn = if purity != ast::extern_fn {
2414 register_fn(ccx, i.span, my_path, i.id, i.attrs)
2416 foreign::register_foreign_fn(ccx,
2422 set_inline_hint_if_appr(i.attrs, llfn);
2425 _ => fail!("get_item_val: weird result in table")
2428 ast_map::node_trait_method(trait_method, _, pth) => {
2429 debug!("get_item_val(): processing a node_trait_method");
2430 match *trait_method {
2431 ast::required(_) => {
2432 ccx.sess.bug("unexpected variant: required trait method in \
2435 ast::provided(m) => {
2437 register_method(ccx, id, pth, m)
2441 ast_map::node_method(m, _, pth) => {
2443 register_method(ccx, id, pth, m)
2445 ast_map::node_foreign_item(ni, _, _, pth) => {
2448 ast::foreign_item_fn(*) => {
2449 register_fn(ccx, ni.span,
2450 vec::append(/*bad*/copy *pth,
2451 [path_name(ni.ident)]),
2455 ast::foreign_item_static(*) => {
2456 let typ = ty::node_id_to_type(ccx.tcx, ni.id);
2457 let ident = token::ident_to_str(&ni.ident);
2458 let g = do str::as_c_str(ident) |buf| {
2460 let ty = type_of(ccx, typ);
2461 llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf)
2469 ast_map::node_variant(ref v, enm, pth) => {
2472 ast::tuple_variant_kind(ref args) => {
2473 assert!(args.len() != 0u);
2474 let pth = vec::append(/*bad*/copy *pth,
2475 [path_name(enm.ident),
2476 path_name((*v).node.name)]);
2477 llfn = match enm.node {
2478 ast::item_enum(_, _) => {
2479 register_fn(ccx, (*v).span, pth, id, enm.attrs)
2481 _ => fail!("node_variant, shouldn't happen")
2484 ast::struct_variant_kind(_) => {
2485 fail!("struct variant kind unexpected in get_item_val")
2488 set_inline_hint(llfn);
2492 ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2493 // Only register the constructor if this is a tuple-like struct.
2494 match struct_def.ctor_id {
2496 ccx.tcx.sess.bug("attempt to register a constructor of \
2497 a non-tuple-like struct")
2500 let llfn = register_fn(ccx,
2502 /*bad*/copy *struct_path,
2505 set_inline_hint(llfn);
2512 ccx.sess.bug(fmt!("get_item_val(): unexpected variant: %?",
2516 if !(exprt || ccx.reachable.contains(&id)) {
2517 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2519 ccx.item_vals.insert(id, val);
2525 pub fn register_method(ccx: @mut CrateContext,
2527 pth: @ast_map::path,
2528 m: @ast::method) -> ValueRef {
2529 let mty = ty::node_id_to_type(ccx.tcx, id);
2530 let pth = vec::append(/*bad*/copy *pth, [path_name((ccx.names)("meth")),
2531 path_name(m.ident)]);
2532 let llfn = register_fn_full(ccx, m.span, pth, id, m.attrs, mty);
2533 set_inline_hint_if_appr(m.attrs, llfn);
2537 // The constant translation pass.
2538 pub fn trans_constant(ccx: &mut CrateContext, it: @ast::item) {
2539 let _icx = push_ctxt("trans_constant");
2541 ast::item_enum(ref enum_definition, _) => {
2542 let vi = ty::enum_variants(ccx.tcx,
2543 ast::def_id { crate: ast::local_crate,
2546 let path = item_path(ccx, it);
2547 for (*enum_definition).variants.iter().advance |variant| {
2548 let p = vec::append(/*bad*/copy path, [
2549 path_name(variant.node.name),
2550 path_name(special_idents::descrim)
2552 let s = mangle_exported_name(ccx, p, ty::mk_int()).to_managed();
2553 let disr_val = vi[i].disr_val;
2554 note_unique_llvm_symbol(ccx, s);
2555 let discrim_gvar = str::as_c_str(s, |buf| {
2557 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2561 llvm::LLVMSetInitializer(discrim_gvar, C_int(ccx, disr_val));
2562 llvm::LLVMSetGlobalConstant(discrim_gvar, True);
2564 ccx.discrims.insert(
2565 local_def(variant.node.id), discrim_gvar);
2566 ccx.discrim_symbols.insert(variant.node.id, s);
2574 pub fn trans_constants(ccx: @mut CrateContext, crate: &ast::crate) {
2577 visit::mk_simple_visitor(@visit::SimpleVisitor {
2578 visit_item: |a| trans_constant(ccx, a),
2579 ..*visit::default_simple_visitor()
2583 pub fn vp2i(cx: block, v: ValueRef) -> ValueRef {
2585 return PtrToInt(cx, v, ccx.int_type);
2588 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2590 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2595 ($name:expr, $args:expr, $ret:expr) => ({
2597 let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2598 intrinsics.insert(name, f);
2602 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2603 let i8p = Type::i8p();
2604 let mut intrinsics = HashMap::new();
2606 ifn!("llvm.memcpy.p0i8.p0i8.i32",
2607 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2608 ifn!("llvm.memcpy.p0i8.p0i8.i64",
2609 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2610 ifn!("llvm.memmove.p0i8.p0i8.i32",
2611 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2612 ifn!("llvm.memmove.p0i8.p0i8.i64",
2613 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2614 ifn!("llvm.memset.p0i8.i32",
2615 [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2616 ifn!("llvm.memset.p0i8.i64",
2617 [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2619 ifn!("llvm.trap", [], Type::void());
2620 ifn!("llvm.frameaddress", [Type::i32()], i8p);
2622 ifn!("llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2623 ifn!("llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2624 ifn!("llvm.pow.f32", [Type::f32(), Type::f32()], Type::f32());
2625 ifn!("llvm.pow.f64", [Type::f64(), Type::f64()], Type::f64());
2627 ifn!("llvm.sqrt.f32", [Type::f32()], Type::f32());
2628 ifn!("llvm.sqrt.f64", [Type::f64()], Type::f64());
2629 ifn!("llvm.sin.f32", [Type::f32()], Type::f32());
2630 ifn!("llvm.sin.f64", [Type::f64()], Type::f64());
2631 ifn!("llvm.cos.f32", [Type::f32()], Type::f32());
2632 ifn!("llvm.cos.f64", [Type::f64()], Type::f64());
2633 ifn!("llvm.exp.f32", [Type::f32()], Type::f32());
2634 ifn!("llvm.exp.f64", [Type::f64()], Type::f64());
2635 ifn!("llvm.exp2.f32", [Type::f32()], Type::f32());
2636 ifn!("llvm.exp2.f64", [Type::f64()], Type::f64());
2637 ifn!("llvm.log.f32", [Type::f32()], Type::f32());
2638 ifn!("llvm.log.f64", [Type::f64()], Type::f64());
2639 ifn!("llvm.log10.f32",[Type::f32()], Type::f32());
2640 ifn!("llvm.log10.f64",[Type::f64()], Type::f64());
2641 ifn!("llvm.log2.f32", [Type::f32()], Type::f32());
2642 ifn!("llvm.log2.f64", [Type::f64()], Type::f64());
2644 ifn!("llvm.fma.f32", [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2645 ifn!("llvm.fma.f64", [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2647 ifn!("llvm.fabs.f32", [Type::f32()], Type::f32());
2648 ifn!("llvm.fabs.f64", [Type::f64()], Type::f64());
2649 ifn!("llvm.floor.f32",[Type::f32()], Type::f32());
2650 ifn!("llvm.floor.f64",[Type::f64()], Type::f64());
2651 ifn!("llvm.ceil.f32", [Type::f32()], Type::f32());
2652 ifn!("llvm.ceil.f64", [Type::f64()], Type::f64());
2653 ifn!("llvm.trunc.f32",[Type::f32()], Type::f32());
2654 ifn!("llvm.trunc.f64",[Type::f64()], Type::f64());
2656 ifn!("llvm.ctpop.i8", [Type::i8()], Type::i8());
2657 ifn!("llvm.ctpop.i16",[Type::i16()], Type::i16());
2658 ifn!("llvm.ctpop.i32",[Type::i32()], Type::i32());
2659 ifn!("llvm.ctpop.i64",[Type::i64()], Type::i64());
2661 ifn!("llvm.ctlz.i8", [Type::i8() , Type::i1()], Type::i8());
2662 ifn!("llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2663 ifn!("llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2664 ifn!("llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2666 ifn!("llvm.cttz.i8", [Type::i8() , Type::i1()], Type::i8());
2667 ifn!("llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2668 ifn!("llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2669 ifn!("llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2671 ifn!("llvm.bswap.i16",[Type::i16()], Type::i16());
2672 ifn!("llvm.bswap.i32",[Type::i32()], Type::i32());
2673 ifn!("llvm.bswap.i64",[Type::i64()], Type::i64());
2678 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2679 ifn!("llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2680 ifn!("llvm.dbg.value", [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2683 pub fn trap(bcx: block) {
2684 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2685 Some(&x) => { Call(bcx, x, []); },
2686 _ => bcx.sess().bug("unbound llvm.trap in trap")
2690 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2691 if !ccx.sess.opts.gc || !ccx.uses_gc {
2695 let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2696 let gc_metadata = do str::as_c_str(gc_metadata_name) |buf| {
2698 llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2702 llvm::LLVMSetGlobalConstant(gc_metadata, True);
2703 lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2704 ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2708 pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
2709 let elttype = Type::struct_([ccx.int_type, ccx.int_type], false);
2710 let maptype = Type::array(&elttype, (ccx.module_data.len() + 1) as u64);
2711 let map = do "_rust_mod_map".as_c_str |buf| {
2713 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2716 lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2717 let mut elts: ~[ValueRef] = ~[];
2719 // This is not ideal, but the borrow checker doesn't
2720 // like the multiple borrows. At least, it doesn't
2721 // like them on the current snapshot. (2013-06-14)
2723 for ccx.module_data.each_key |k| {
2724 keys.push(k.to_managed());
2727 for keys.iter().advance |key| {
2728 let val = *ccx.module_data.find_equiv(key).get();
2729 let s_const = C_cstr(ccx, *key);
2730 let s_ptr = p2i(ccx, s_const);
2731 let v_ptr = p2i(ccx, val);
2732 let elt = C_struct([s_ptr, v_ptr]);
2735 let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
2738 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2744 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2745 llmod: ModuleRef) -> ValueRef {
2746 let targ_cfg = sess.targ_cfg;
2747 let int_type = Type::int(targ_cfg.arch);
2748 let mut n_subcrates = 1;
2749 let cstore = sess.cstore;
2750 while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2751 let mapname = if *sess.building_library {
2752 fmt!("%s_%s_%s", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2756 let sym_name = ~"_rust_crate_map_" + mapname;
2757 let arrtype = Type::array(&int_type, n_subcrates as u64);
2758 let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false);
2759 let map = str::as_c_str(sym_name, |buf| {
2761 llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2764 lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2768 pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) {
2769 let mut subcrates: ~[ValueRef] = ~[];
2771 let cstore = ccx.sess.cstore;
2772 while cstore::have_crate_data(cstore, i) {
2773 let cdata = cstore::get_crate_data(cstore, i);
2774 let nm = fmt!("_rust_crate_map_%s_%s_%s",
2776 cstore::get_crate_vers(cstore, i),
2777 cstore::get_crate_hash(cstore, i));
2778 let cr = str::as_c_str(nm, |buf| {
2780 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2783 subcrates.push(p2i(ccx, cr));
2786 subcrates.push(C_int(ccx, 0));
2789 let annihilate_def_id = ccx.tcx.lang_items.annihilate_fn();
2790 if annihilate_def_id.crate == ast::local_crate {
2791 llannihilatefn = get_item_val(ccx, annihilate_def_id.node);
2793 let annihilate_fn_type = csearch::get_type(ccx.tcx,
2794 annihilate_def_id).ty;
2795 llannihilatefn = trans_external_path(ccx,
2797 annihilate_fn_type);
2801 let mod_map = create_module_map(ccx);
2802 llvm::LLVMSetInitializer(map, C_struct(
2804 lib::llvm::llvm::LLVMConstPointerCast(llannihilatefn, Type::i8p().to_ref()),
2806 C_array(ccx.int_type, subcrates)]));
2810 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
2811 -> encoder::EncodeParams<'r> {
2813 let diag = cx.sess.diagnostic();
2814 let item_symbols = &cx.item_symbols;
2815 let discrim_symbols = &cx.discrim_symbols;
2816 let link_meta = &cx.link_meta;
2817 encoder::EncodeParams {
2820 reachable: cx.reachable,
2821 reexports2: cx.exp_map2,
2822 item_symbols: item_symbols,
2823 discrim_symbols: discrim_symbols,
2824 link_meta: link_meta,
2825 cstore: cx.sess.cstore,
2826 encode_inlined_item: ie
2830 pub fn write_metadata(cx: &mut CrateContext, crate: &ast::crate) {
2831 if !*cx.sess.building_library { return; }
2833 let encode_inlined_item: encoder::encode_inlined_item =
2834 |ecx, ebml_w, path, ii|
2835 astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
2837 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2838 let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
2839 let llconst = C_struct([llmeta]);
2840 let mut llglobal = str::as_c_str("rust_metadata", |buf| {
2842 llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
2846 llvm::LLVMSetInitializer(llglobal, llconst);
2847 str::as_c_str(cx.sess.targ_cfg.target_strs.meta_sect_name, |buf| {
2848 llvm::LLVMSetSection(llglobal, buf)
2850 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2852 let t_ptr_i8 = Type::i8p();
2853 llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
2854 let llvm_used = do "llvm.used".as_c_str |buf| {
2855 llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
2857 lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
2858 llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
2862 fn mk_global(ccx: &CrateContext,
2868 let llglobal = do str::as_c_str(name) |buf| {
2869 llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval).to_ref(), buf)
2871 llvm::LLVMSetInitializer(llglobal, llval);
2872 llvm::LLVMSetGlobalConstant(llglobal, True);
2875 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2882 // Writes the current ABI version into the crate.
2883 pub fn write_abi_version(ccx: &mut CrateContext) {
2884 mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version), false);
2887 pub fn trans_crate(sess: session::Session,
2891 emap2: resolve::ExportMap2,
2892 maps: astencode::Maps) -> (ContextRef, ModuleRef, LinkMeta) {
2894 let mut symbol_hasher = hash::default_state();
2895 let link_meta = link::build_link_meta(sess, crate, output, &mut symbol_hasher);
2896 let reachable = reachable::find_reachable(
2903 // Append ".rc" to crate name as LLVM module identifier.
2905 // LLVM code generator emits a ".file filename" directive
2906 // for ELF backends. Value of the "filename" is set as the
2907 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2908 // crashes if the module identifer is same as other symbols
2909 // such as a function name in the module.
2910 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2911 let llmod_id = link_meta.name.to_owned() + ".rc";
2913 // FIXME(#6511): get LLVM building with --enable-threads so this
2914 // function can be called
2915 // if !llvm::LLVMRustStartMultithreading() {
2916 // sess.bug("couldn't enable multi-threaded LLVM");
2919 let ccx = @mut CrateContext::new(sess, llmod_id, tcx, emap2, maps,
2920 symbol_hasher, link_meta, reachable);
2922 let _icx = push_ctxt("data");
2923 trans_constants(ccx, crate);
2927 let _icx = push_ctxt("text");
2928 trans_mod(ccx, &crate.node.module);
2931 decl_gc_metadata(ccx, llmod_id);
2932 fill_crate_map(ccx, ccx.crate_map);
2933 glue::emit_tydescs(ccx);
2934 write_abi_version(ccx);
2935 if ccx.sess.opts.debuginfo {
2936 debuginfo::finalize(ccx);
2939 // Translate the metadata.
2940 write_metadata(ccx, crate);
2941 if ccx.sess.trans_stats() {
2942 io::println("--- trans stats ---");
2943 io::println(fmt!("n_static_tydescs: %u",
2944 ccx.stats.n_static_tydescs));
2945 io::println(fmt!("n_glues_created: %u",
2946 ccx.stats.n_glues_created));
2947 io::println(fmt!("n_null_glues: %u", ccx.stats.n_null_glues));
2948 io::println(fmt!("n_real_glues: %u", ccx.stats.n_real_glues));
2950 io::println(fmt!("n_fns: %u", ccx.stats.n_fns));
2951 io::println(fmt!("n_monos: %u", ccx.stats.n_monos));
2952 io::println(fmt!("n_inlines: %u", ccx.stats.n_inlines));
2953 io::println(fmt!("n_closures: %u", ccx.stats.n_closures));
2956 if ccx.sess.count_llvm_insns() {
2957 for ccx.stats.llvm_insns.iter().advance |(&k, &v)| {
2958 io::println(fmt!("%-7u %s", v, k));
2962 let llcx = ccx.llcx;
2963 let link_meta = ccx.link_meta;
2964 let llmod = ccx.llmod;
2966 return (llcx, llmod, link_meta);