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.
27 use back::link::{mangle_exported_name};
28 use back::{link, abi};
30 use driver::session::Session;
31 use driver::driver::{CrateAnalysis, CrateTranslation};
32 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
33 use lib::llvm::{llvm, True};
35 use metadata::common::LinkMeta;
36 use metadata::{csearch, cstore, encoder};
37 use middle::astencode;
38 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
39 use middle::lang_items::{MallocFnLangItem, ClosureExchangeMallocFnLangItem};
40 use middle::trans::_match;
41 use middle::trans::adt;
42 use middle::trans::base;
43 use middle::trans::build::*;
44 use middle::trans::builder::{Builder, noname};
45 use middle::trans::callee;
46 use middle::trans::common::*;
47 use middle::trans::consts;
48 use middle::trans::controlflow;
49 use middle::trans::datum;
50 use middle::trans::debuginfo;
51 use middle::trans::expr;
52 use middle::trans::foreign;
53 use middle::trans::glue;
54 use middle::trans::inline;
55 use middle::trans::llrepr::LlvmRepr;
56 use middle::trans::machine;
57 use middle::trans::machine::{llalign_of_min, llsize_of};
58 use middle::trans::meth;
59 use middle::trans::monomorphize;
60 use middle::trans::tvec;
61 use middle::trans::type_of;
62 use middle::trans::type_of::*;
63 use middle::trans::value::Value;
65 use util::common::indenter;
66 use util::ppaux::{Repr, ty_to_str};
68 use middle::trans::type_::Type;
70 use std::c_str::ToCStr;
72 use std::hashmap::HashMap;
74 use std::libc::c_uint;
79 use syntax::ast::Name;
80 use syntax::ast_map::{path, path_elt_to_str, path_name, path_pretty_name};
81 use syntax::ast_util::{local_def};
83 use syntax::attr::AttrMetaMethods;
84 use syntax::codemap::Span;
85 use syntax::parse::token;
86 use syntax::parse::token::{special_idents};
87 use syntax::print::pprust::stmt_to_str;
88 use syntax::{ast, ast_util, codemap, ast_map};
89 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic};
91 use syntax::visit::Visitor;
93 pub use middle::trans::context::task_llcx;
95 static task_local_insn_key: local_data::Key<@~[&'static str]> = &local_data::Key;
97 pub fn with_insn_ctxt(blk: &fn(&[&'static str])) {
98 let opt = local_data::get(task_local_insn_key, |k| k.map_move(|k| *k));
104 pub fn init_insn_ctxt() {
105 local_data::set(task_local_insn_key, @~[]);
108 pub struct _InsnCtxt { _x: () }
111 impl Drop for _InsnCtxt {
113 do local_data::modify(task_local_insn_key) |c| {
114 do c.map_move |ctx| {
115 let mut ctx = (*ctx).clone();
123 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
124 debug!("new InsnCtxt: %s", s);
125 do local_data::modify(task_local_insn_key) |c| {
126 do c.map_move |ctx| {
127 let mut ctx = (*ctx).clone();
135 struct StatRecorder<'self> {
136 ccx: @mut CrateContext,
142 impl<'self> StatRecorder<'self> {
143 pub fn new(ccx: @mut CrateContext,
144 name: &'self str) -> StatRecorder<'self> {
145 let start = if ccx.sess.trans_stats() {
146 time::precise_time_ns()
150 let istart = ccx.stats.n_llvm_insns;
161 impl<'self> Drop for StatRecorder<'self> {
163 if self.ccx.sess.trans_stats() {
164 let end = time::precise_time_ns();
165 let elapsed = ((end - self.start) / 1_000_000) as uint;
166 let iend = self.ccx.stats.n_llvm_insns;
167 self.ccx.stats.fn_stats.push((self.name.to_owned(),
169 iend - self.istart));
170 self.ccx.stats.n_fns += 1;
171 // Reset LLVM insn count to avoid compound costs.
172 self.ccx.stats.n_llvm_insns = self.istart;
177 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
178 let llfn: ValueRef = do name.with_c_str |buf| {
180 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
184 lib::llvm::SetFunctionCallConv(llfn, cc);
188 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
189 return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
192 // Only use this if you are going to actually define the function. It's
193 // not valid to simply declare a function as internal.
194 pub fn decl_internal_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
195 let llfn = decl_cdecl_fn(llmod, name, ty);
196 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
200 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: &str,
201 cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
202 match externs.find_equiv(&name) {
203 Some(n) => return *n,
206 let f = decl_fn(llmod, name, cc, ty);
207 externs.insert(name.to_owned(), f);
211 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
212 name: &str, ty: Type) -> ValueRef {
213 match externs.find_equiv(&name) {
214 Some(n) => return *n,
218 let c = do name.with_c_str |buf| {
219 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
221 externs.insert(name.to_owned(), c);
225 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
226 let _icx = push_ctxt("umax");
227 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
228 return Select(cx, cond, b, a);
231 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
232 let _icx = push_ctxt("umin");
233 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
234 return Select(cx, cond, a, b);
237 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
238 // The type of the returned pointer is always i8*. If you care about the
239 // return type, use bump_ptr().
240 pub fn ptr_offs(bcx: @mut Block, base: ValueRef, sz: ValueRef) -> ValueRef {
241 let _icx = push_ctxt("ptr_offs");
242 let raw = PointerCast(bcx, base, Type::i8p());
243 InBoundsGEP(bcx, raw, [sz])
246 // Increment a pointer by a given amount and then cast it to be a pointer
248 pub fn bump_ptr(bcx: @mut Block, t: ty::t, base: ValueRef, sz: ValueRef) ->
250 let _icx = push_ctxt("bump_ptr");
252 let bumped = ptr_offs(bcx, base, sz);
253 let typ = type_of(ccx, t).ptr_to();
254 PointerCast(bcx, bumped, typ)
257 // Returns a pointer to the body for the box. The box may be an opaque
258 // box. The result will be casted to the type of body_t, if it is statically
261 // The runtime equivalent is box_body() in "rust_internal.h".
262 pub fn opaque_box_body(bcx: @mut Block,
264 boxptr: ValueRef) -> ValueRef {
265 let _icx = push_ctxt("opaque_box_body");
267 let ty = type_of(ccx, body_t);
268 let ty = Type::box(ccx, &ty);
269 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
270 GEPi(bcx, boxptr, [0u, abi::box_field_body])
273 // malloc_raw_dyn: allocates a box to contain a given type, but with a
274 // potentially dynamic size.
275 pub fn malloc_raw_dyn(bcx: @mut Block,
278 size: ValueRef) -> Result {
279 let _icx = push_ctxt("malloc_raw");
282 fn require_alloc_fn(bcx: @mut Block, t: ty::t, it: LangItem) -> ast::DefId {
283 let li = &bcx.tcx().lang_items;
284 match li.require(it) {
287 bcx.tcx().sess.fatal(fmt!("allocation of `%s` %s",
288 bcx.ty_to_str(t), s));
293 if heap == heap_exchange {
294 let llty_value = type_of::type_of(ccx, t);
298 let r = callee::trans_lang_call(
300 require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
303 rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
305 // we treat ~fn, @fn and @[] as @ here, which isn't ideal
306 let (mk_fn, langcall) = match heap {
307 heap_managed | heap_managed_unique => {
309 require_alloc_fn(bcx, t, MallocFnLangItem))
311 heap_exchange_closure => {
313 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem))
315 _ => fail!("heap_exchange already handled")
318 // Grab the TypeRef type of box_ptr_ty.
319 let box_ptr_ty = mk_fn(bcx.tcx(), t);
320 let llty = type_of(ccx, box_ptr_ty);
322 // Get the tydesc for the body:
323 let static_ti = get_tydesc(ccx, t);
324 glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
327 let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
328 let r = callee::trans_lang_call(
333 let r = rslt(r.bcx, PointerCast(r.bcx, r.val, llty));
334 maybe_set_managed_unique_rc(r.bcx, r.val, heap);
339 // malloc_raw: expects an unboxed type and returns a pointer to
340 // enough space for a box of that type. This includes a rust_opaque_box
342 pub fn malloc_raw(bcx: @mut Block, t: ty::t, heap: heap) -> Result {
343 let ty = type_of(bcx.ccx(), t);
344 let size = llsize_of(bcx.ccx(), ty);
345 malloc_raw_dyn(bcx, t, heap, size)
348 pub struct MallocResult {
354 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
355 // and pulls out the body
356 pub fn malloc_general_dyn(bcx: @mut Block, t: ty::t, heap: heap, size: ValueRef)
358 assert!(heap != heap_exchange);
359 let _icx = push_ctxt("malloc_general");
360 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
361 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
363 MallocResult { bcx: bcx, box: llbox, body: body }
366 pub fn malloc_general(bcx: @mut Block, t: ty::t, heap: heap) -> MallocResult {
367 let ty = type_of(bcx.ccx(), t);
368 assert!(heap != heap_exchange);
369 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
371 pub fn malloc_boxed(bcx: @mut Block, t: ty::t)
373 malloc_general(bcx, t, heap_managed)
376 pub fn heap_for_unique(bcx: @mut Block, t: ty::t) -> heap {
377 if ty::type_contents(bcx.tcx(), t).contains_managed() {
384 pub fn maybe_set_managed_unique_rc(bcx: @mut Block, bx: ValueRef, heap: heap) {
385 assert!(heap != heap_exchange);
386 if heap == heap_managed_unique {
387 // In cases where we are looking at a unique-typed allocation in the
388 // managed heap (thus have refcount 1 from the managed allocator),
389 // such as a ~(@foo) or such. These need to have their refcount forced
390 // to -2 so the annihilator ignores them.
391 let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
392 let rc_val = C_int(bcx.ccx(), -2);
393 Store(bcx, rc_val, rc);
397 // Type descriptor and type glue stuff
399 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
400 get_tydesc(ccx, t).tydesc
403 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
404 match ccx.tydescs.find(&t) {
411 ccx.stats.n_static_tydescs += 1u;
412 let inf = glue::declare_tydesc(ccx, t);
413 ccx.tydescs.insert(t, inf);
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 pub fn set_no_unwind(f: ValueRef) {
426 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
429 // Tell LLVM to emit the information necessary to unwind the stack for the
431 pub fn set_uwtable(f: ValueRef) {
432 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
435 pub fn set_inline_hint(f: ValueRef) {
436 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
439 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
441 // Set the inline hint if there is one
442 match find_inline_attr(attrs) {
443 InlineHint => set_inline_hint(llfn),
444 InlineAlways => set_always_inline(llfn),
445 InlineNever => set_no_inline(llfn),
446 InlineNone => { /* fallthrough */ }
449 // Add the no-split-stack attribute if requested
450 if contains_name(attrs, "no_split_stack") {
451 set_no_split_stack(llfn);
455 pub fn set_always_inline(f: ValueRef) {
456 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
459 pub fn set_fixed_stack_segment(f: ValueRef) {
460 do "fixed-stack-segment".to_c_str().with_ref |buf| {
461 unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
465 pub fn set_no_split_stack(f: ValueRef) {
466 do "no-split-stack".to_c_str().with_ref |buf| {
467 unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
471 pub fn set_glue_inlining(f: ValueRef, t: ty::t) {
472 if ty::type_is_structural(t) {
473 set_optimize_for_size(f);
474 } else { set_always_inline(f); }
477 // Double-check that we never ask LLVM to declare the same symbol twice. It
478 // silently mangles such symbols, breaking our linkage model.
479 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
480 if ccx.all_llvm_symbols.contains(&sym) {
481 ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
483 ccx.all_llvm_symbols.insert(sym);
487 pub fn get_res_dtor(ccx: @mut CrateContext,
489 parent_id: ast::DefId,
492 let _icx = push_ctxt("trans_res_dtor");
493 if !substs.is_empty() {
494 let did = if did.crate != ast::LOCAL_CRATE {
495 inline::maybe_instantiate_inline(ccx, did)
499 assert_eq!(did.crate, ast::LOCAL_CRATE);
500 let tsubsts = ty::substs {regions: ty::ErasedRegions,
502 tps: /*bad*/ substs.to_owned() };
503 let (val, _) = monomorphize::monomorphic_fn(ccx,
511 } else if did.crate == ast::LOCAL_CRATE {
512 get_item_val(ccx, did.node)
515 let name = csearch::get_symbol(ccx.sess.cstore, did);
516 let class_ty = ty::subst_tps(tcx,
519 ty::lookup_item_type(tcx, parent_id).ty);
520 let llty = type_of_dtor(ccx, class_ty);
521 get_extern_fn(&mut ccx.externs,
524 lib::llvm::CCallConv,
529 // Structural comparison: a rather involved form of glue.
530 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
531 if cx.sess.opts.save_temps {
532 do s.with_c_str |buf| {
534 llvm::LLVMSetValueName(v, buf)
541 // Used only for creating scalar comparison glue.
542 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
544 // NB: This produces an i1, not a Rust bool (i8).
545 pub fn compare_scalar_types(cx: @mut Block,
551 let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
553 match ty::get(t).sty {
554 ty::ty_nil => rslt(cx, f(nil_type)),
555 ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
556 ty::ty_char => rslt(cx, f(unsigned_int)),
557 ty::ty_int(_) => rslt(cx, f(signed_int)),
558 ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
559 ty::ty_float(_) => rslt(cx, f(floating_point)),
562 controlflow::trans_fail(
564 @"attempt to compare values of type type"),
568 // Should never get here, because t is scalar.
569 cx.sess().bug("non-scalar type passed to \
570 compare_scalar_types")
576 // A helper function to do the actual comparison of scalar values.
577 pub fn compare_scalar_values(cx: @mut Block,
583 let _icx = push_ctxt("compare_scalar_values");
584 fn die(cx: @mut Block) -> ! {
585 cx.tcx().sess.bug("compare_scalar_values: must be a\
586 comparison operator");
590 // We don't need to do actual comparisons for nil.
591 // () == () holds but () < () does not.
593 ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(true),
594 ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(false),
595 // refinements would be nice
601 ast::BiEq => lib::llvm::RealOEQ,
602 ast::BiNe => lib::llvm::RealUNE,
603 ast::BiLt => lib::llvm::RealOLT,
604 ast::BiLe => lib::llvm::RealOLE,
605 ast::BiGt => lib::llvm::RealOGT,
606 ast::BiGe => lib::llvm::RealOGE,
609 return FCmp(cx, cmp, lhs, rhs);
613 ast::BiEq => lib::llvm::IntEQ,
614 ast::BiNe => lib::llvm::IntNE,
615 ast::BiLt => lib::llvm::IntSLT,
616 ast::BiLe => lib::llvm::IntSLE,
617 ast::BiGt => lib::llvm::IntSGT,
618 ast::BiGe => lib::llvm::IntSGE,
621 return ICmp(cx, cmp, lhs, rhs);
625 ast::BiEq => lib::llvm::IntEQ,
626 ast::BiNe => lib::llvm::IntNE,
627 ast::BiLt => lib::llvm::IntULT,
628 ast::BiLe => lib::llvm::IntULE,
629 ast::BiGt => lib::llvm::IntUGT,
630 ast::BiGe => lib::llvm::IntUGE,
633 return ICmp(cx, cmp, lhs, rhs);
638 pub type val_and_ty_fn<'self> = &'self fn(@mut Block, ValueRef, ty::t) -> @mut Block;
640 pub fn load_inbounds(cx: @mut Block, p: ValueRef, idxs: &[uint]) -> ValueRef {
641 return Load(cx, GEPi(cx, p, idxs));
644 pub fn store_inbounds(cx: @mut Block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
645 Store(cx, v, GEPi(cx, p, idxs));
648 // Iterates through the elements of a structural type.
649 pub fn iter_structural_ty(cx: @mut Block, av: ValueRef, t: ty::t,
650 f: val_and_ty_fn) -> @mut Block {
651 let _icx = push_ctxt("iter_structural_ty");
653 fn iter_variant(cx: @mut Block, repr: &adt::Repr, av: ValueRef,
654 variant: @ty::VariantInfo,
655 tps: &[ty::t], f: val_and_ty_fn) -> @mut Block {
656 let _icx = push_ctxt("iter_variant");
660 for (i, &arg) in variant.args.iter().enumerate() {
662 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
663 ty::subst_tps(tcx, tps, None, arg));
669 match ty::get(t).sty {
670 ty::ty_struct(*) => {
671 let repr = adt::represent_type(cx.ccx(), t);
672 do expr::with_field_tys(cx.tcx(), t, None) |discr, field_tys| {
673 for (i, field_ty) in field_tys.iter().enumerate() {
674 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
675 cx = f(cx, llfld_a, field_ty.mt.ty);
679 ty::ty_estr(ty::vstore_fixed(_)) |
680 ty::ty_evec(_, ty::vstore_fixed(_)) => {
681 let (base, len) = tvec::get_base_and_len(cx, av, t);
682 cx = tvec::iter_vec_raw(cx, base, t, len, f);
684 ty::ty_tup(ref args) => {
685 let repr = adt::represent_type(cx.ccx(), t);
686 for (i, arg) in args.iter().enumerate() {
687 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
688 cx = f(cx, llfld_a, *arg);
691 ty::ty_enum(tid, ref substs) => {
694 let repr = adt::represent_type(ccx, t);
695 let variants = ty::enum_variants(ccx.tcx, tid);
696 let n_variants = (*variants).len();
698 // NB: we must hit the discriminant first so that structural
699 // comparison know not to proceed when the discriminants differ.
701 match adt::trans_switch(cx, repr, av) {
702 (_match::single, None) => {
703 cx = iter_variant(cx, repr, av, variants[0],
706 (_match::switch, Some(lldiscrim_a)) => {
707 cx = f(cx, lldiscrim_a, ty::mk_int());
708 let unr_cx = sub_block(cx, "enum-iter-unr");
710 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
712 let next_cx = sub_block(cx, "enum-iter-next");
714 for variant in (*variants).iter() {
716 sub_block(cx, ~"enum-iter-variant-" +
717 variant.disr_val.to_str());
719 iter_variant(variant_cx, repr, av, *variant,
720 substs.tps, |x,y,z| f(x,y,z));
721 match adt::trans_case(cx, repr, variant.disr_val) {
722 _match::single_result(r) => {
723 AddCase(llswitch, r.val, variant_cx.llbb)
725 _ => ccx.sess.unimpl("value from adt::trans_case \
726 in iter_structural_ty")
728 Br(variant_cx, next_cx.llbb);
732 _ => ccx.sess.unimpl("value from adt::trans_switch \
733 in iter_structural_ty")
736 _ => cx.sess().unimpl("type in iter_structural_ty")
741 pub fn cast_shift_expr_rhs(cx: @mut Block, op: ast::BinOp,
742 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
743 cast_shift_rhs(op, lhs, rhs,
744 |a,b| Trunc(cx, a, b),
745 |a,b| ZExt(cx, a, b))
748 pub fn cast_shift_const_rhs(op: ast::BinOp,
749 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
750 cast_shift_rhs(op, lhs, rhs,
751 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
752 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
755 pub fn cast_shift_rhs(op: ast::BinOp,
756 lhs: ValueRef, rhs: ValueRef,
757 trunc: &fn(ValueRef, Type) -> ValueRef,
758 zext: &fn(ValueRef, Type) -> ValueRef)
760 // Shifts may have any size int on the rhs
762 if ast_util::is_shift_binop(op) {
763 let rhs_llty = val_ty(rhs);
764 let lhs_llty = val_ty(lhs);
765 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
766 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
769 } else if lhs_sz > rhs_sz {
770 // FIXME (#1877: If shifting by negative
771 // values becomes not undefined then this is wrong.
782 pub fn fail_if_zero(cx: @mut Block, span: Span, divrem: ast::BinOp,
783 rhs: ValueRef, rhs_t: ty::t) -> @mut Block {
784 let text = if divrem == ast::BiDiv {
785 @"attempted to divide by zero"
787 @"attempted remainder with a divisor of zero"
789 let is_zero = match ty::get(rhs_t).sty {
791 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
792 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
795 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
796 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
799 cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
800 ty_to_str(cx.ccx().tcx, rhs_t));
803 do with_cond(cx, is_zero) |bcx| {
804 controlflow::trans_fail(bcx, Some(span), text)
808 pub fn null_env_ptr(ccx: &CrateContext) -> ValueRef {
809 C_null(Type::opaque_box(ccx).ptr_to())
812 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::DefId, t: ty::t)
814 let name = csearch::get_symbol(ccx.sess.cstore, did);
815 match ty::get(t).sty {
816 ty::ty_bare_fn(ref fn_ty) => {
817 // Currently llvm_calling_convention triggers unimpl/bug on
818 // Rust/RustIntrinsic, so those two are handled specially here.
819 let cconv = match fn_ty.abis.for_arch(ccx.sess.targ_cfg.arch) {
820 Some(Rust) | Some(RustIntrinsic) => lib::llvm::CCallConv,
822 let c = foreign::llvm_calling_convention(ccx, fn_ty.abis);
823 c.unwrap_or(lib::llvm::CCallConv)
826 let llty = type_of_fn_from_ty(ccx, t);
827 return get_extern_fn(&mut ccx.externs, ccx.llmod, name, cconv, llty);
829 ty::ty_closure(_) => {
830 let llty = type_of_fn_from_ty(ccx, t);
831 return get_extern_fn(&mut ccx.externs, ccx.llmod, name,
832 lib::llvm::CCallConv, llty);
835 let llty = type_of(ccx, t);
836 return get_extern_const(&mut ccx.externs, ccx.llmod, name, llty);
841 pub fn invoke(bcx: @mut Block, llfn: ValueRef, llargs: ~[ValueRef],
842 attributes: &[(uint, lib::llvm::Attribute)])
843 -> (ValueRef, @mut Block) {
844 let _icx = push_ctxt("invoke_");
846 return (C_null(Type::i8()), bcx);
849 match bcx.node_info {
850 None => debug!("invoke at ???"),
852 debug!("invoke at %s",
853 bcx.sess().codemap.span_to_str(node_info.span));
857 if need_invoke(bcx) {
859 debug!("invoking %x at %x",
860 ::std::cast::transmute(llfn),
861 ::std::cast::transmute(bcx.llbb));
862 for &llarg in llargs.iter() {
863 debug!("arg: %x", ::std::cast::transmute(llarg));
866 let normal_bcx = sub_block(bcx, "normal return");
867 let llresult = Invoke(bcx,
871 get_landing_pad(bcx));
872 return (llresult, normal_bcx);
875 debug!("calling %x at %x",
876 ::std::cast::transmute(llfn),
877 ::std::cast::transmute(bcx.llbb));
878 for &llarg in llargs.iter() {
879 debug!("arg: %x", ::std::cast::transmute(llarg));
882 let llresult = Call(bcx, llfn, llargs, attributes);
883 return (llresult, bcx);
887 pub fn need_invoke(bcx: @mut Block) -> bool {
888 if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
892 // Avoid using invoke if we are already inside a landing pad.
897 if have_cached_lpad(bcx) {
901 // Walk the scopes to look for cleanups
903 let mut cur_scope = cur.scope;
905 cur_scope = match cur_scope {
907 for cleanup in inf.cleanups.iter() {
909 clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
910 if cleanup_type == normal_exit_and_unwind {
919 cur = match cur.parent {
929 pub fn have_cached_lpad(bcx: @mut Block) -> bool {
931 do in_lpad_scope_cx(bcx) |inf| {
932 match inf.landing_pad {
933 Some(_) => res = true,
940 pub fn in_lpad_scope_cx(bcx: @mut Block, f: &fn(si: &mut ScopeInfo)) {
942 let mut cur_scope = bcx.scope;
944 cur_scope = match cur_scope {
946 if !inf.empty_cleanups() || (inf.parent.is_none() && bcx.parent.is_none()) {
953 bcx = block_parent(bcx);
960 pub fn get_landing_pad(bcx: @mut Block) -> BasicBlockRef {
961 let _icx = push_ctxt("get_landing_pad");
963 let mut cached = None;
964 let mut pad_bcx = bcx; // Guaranteed to be set below
965 do in_lpad_scope_cx(bcx) |inf| {
966 // If there is a valid landing pad still around, use it
967 match inf.landing_pad {
968 Some(target) => cached = Some(target),
970 pad_bcx = lpad_block(bcx, "unwind");
971 inf.landing_pad = Some(pad_bcx.llbb);
975 // Can't return from block above
976 match cached { Some(b) => return b, None => () }
977 // The landing pad return type (the type being propagated). Not sure what
978 // this represents but it's determined by the personality function and
979 // this is what the EH proposal example uses.
980 let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
981 // The exception handling personality function. This is the C++
982 // personality function __gxx_personality_v0, wrapped in our naming
984 let personality = bcx.ccx().upcalls.rust_personality;
985 // The only landing pad clause will be 'cleanup'
986 let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
987 // The landing pad block is a cleanup
988 SetCleanup(pad_bcx, llretval);
990 // Because we may have unwound across a stack boundary, we must call into
991 // the runtime to figure out which stack segment we are on and place the
992 // stack limit back into the TLS.
993 Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, [], []);
995 // We store the retval in a function-central alloca, so that calls to
996 // Resume can find it.
997 match bcx.fcx.personality {
998 Some(addr) => Store(pad_bcx, llretval, addr),
1000 let addr = alloca(pad_bcx, val_ty(llretval), "");
1001 bcx.fcx.personality = Some(addr);
1002 Store(pad_bcx, llretval, addr);
1006 // Unwind all parent scopes, and finish with a Resume instr
1007 cleanup_and_leave(pad_bcx, None, None);
1008 return pad_bcx.llbb;
1011 pub fn find_bcx_for_scope(bcx: @mut Block, scope_id: ast::NodeId) -> @mut Block {
1012 let mut bcx_sid = bcx;
1013 let mut cur_scope = bcx_sid.scope;
1015 cur_scope = match cur_scope {
1017 match inf.node_info {
1018 Some(NodeInfo { id, _ }) if id == scope_id => {
1021 // FIXME(#6268, #6248) hacky cleanup for nested method calls
1022 Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
1029 bcx_sid = match bcx_sid.parent {
1030 None => bcx.tcx().sess.bug(fmt!("no enclosing scope with id %d", scope_id)),
1031 Some(bcx_par) => bcx_par
1040 pub fn do_spill(bcx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1041 if ty::type_is_bot(t) {
1042 return C_null(Type::i8p());
1044 let llptr = alloc_ty(bcx, t, "");
1045 Store(bcx, v, llptr);
1049 // Since this function does *not* root, it is the caller's responsibility to
1050 // ensure that the referent is pointed to by a root.
1051 pub fn do_spill_noroot(cx: @mut Block, v: ValueRef) -> ValueRef {
1052 let llptr = alloca(cx, val_ty(v), "");
1053 Store(cx, v, llptr);
1057 pub fn spill_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1058 let _icx = push_ctxt("spill_if_immediate");
1059 if ty::type_is_immediate(cx.tcx(), t) { return do_spill(cx, v, t); }
1063 pub fn load_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1064 let _icx = push_ctxt("load_if_immediate");
1065 if ty::type_is_immediate(cx.tcx(), t) { return Load(cx, v); }
1069 pub fn trans_trace(bcx: @mut Block, sp_opt: Option<Span>, trace_str: @str) {
1070 if !bcx.sess().trace() { return; }
1071 let _icx = push_ctxt("trans_trace");
1072 add_comment(bcx, trace_str);
1073 let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1074 let (V_filename, V_line) = match sp_opt {
1076 let sess = bcx.sess();
1077 let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1078 (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1081 (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1084 let ccx = bcx.ccx();
1085 let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1086 let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1087 let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1088 Call(bcx, ccx.upcalls.trace, args, []);
1091 pub fn ignore_lhs(_bcx: @mut Block, local: &ast::Local) -> bool {
1092 match local.pat.node {
1093 ast::PatWild => true, _ => false
1097 pub fn init_local(bcx: @mut Block, local: &ast::Local) -> @mut Block {
1099 debug!("init_local(bcx=%s, local.id=%?)",
1100 bcx.to_str(), local.id);
1101 let _indenter = indenter();
1103 let _icx = push_ctxt("init_local");
1105 if ignore_lhs(bcx, local) {
1106 // Handle let _ = e; just like e;
1109 return expr::trans_into(bcx, init, expr::Ignore);
1111 None => { return bcx; }
1115 _match::store_local(bcx, local.pat, local.init)
1118 pub fn trans_stmt(cx: @mut Block, s: &ast::Stmt) -> @mut Block {
1119 let _icx = push_ctxt("trans_stmt");
1120 debug!("trans_stmt(%s)", stmt_to_str(s, cx.tcx().sess.intr()));
1122 if cx.sess().asm_comments() {
1123 add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1129 ast::StmtExpr(e, _) | ast::StmtSemi(e, _) => {
1130 bcx = expr::trans_into(cx, e, expr::Ignore);
1132 ast::StmtDecl(d, _) => {
1134 ast::DeclLocal(ref local) => {
1135 bcx = init_local(bcx, *local);
1136 if cx.sess().opts.extra_debuginfo {
1137 debuginfo::create_local_var_metadata(bcx, *local);
1140 ast::DeclItem(i) => trans_item(cx.fcx.ccx, i)
1143 ast::StmtMac(*) => cx.tcx().sess.bug("unexpanded macro")
1149 // You probably don't want to use this one. See the
1150 // next three functions instead.
1151 pub fn new_block(cx: @mut FunctionContext,
1152 parent: Option<@mut Block>,
1153 scope: Option<@mut ScopeInfo>,
1156 opt_node_info: Option<NodeInfo>)
1159 let llbb = do name.with_c_str |buf| {
1160 llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1162 let bcx = @mut Block::new(llbb,
1168 for cx in parent.iter() {
1178 pub fn simple_block_scope(parent: Option<@mut ScopeInfo>,
1179 node_info: Option<NodeInfo>) -> @mut ScopeInfo {
1187 node_info: node_info,
1191 // Use this when you're at the top block of a function or the like.
1192 pub fn top_scope_block(fcx: @mut FunctionContext, opt_node_info: Option<NodeInfo>)
1194 return new_block(fcx, None, Some(simple_block_scope(None, opt_node_info)), false,
1195 "function top level", opt_node_info);
1198 pub fn scope_block(bcx: @mut Block,
1199 opt_node_info: Option<NodeInfo>,
1200 n: &str) -> @mut Block {
1201 return new_block(bcx.fcx, Some(bcx), Some(simple_block_scope(None, opt_node_info)), bcx.is_lpad,
1205 pub fn loop_scope_block(bcx: @mut Block,
1206 loop_break: @mut Block,
1207 loop_label: Option<Name>,
1209 opt_node_info: Option<NodeInfo>) -> @mut Block {
1210 return new_block(bcx.fcx, Some(bcx), Some(@mut ScopeInfo {
1212 loop_break: Some(loop_break),
1213 loop_label: loop_label,
1217 node_info: opt_node_info,
1218 }), bcx.is_lpad, n, opt_node_info);
1221 // Use this when creating a block for the inside of a landing pad.
1222 pub fn lpad_block(bcx: @mut Block, n: &str) -> @mut Block {
1223 new_block(bcx.fcx, Some(bcx), None, true, n, None)
1226 // Use this when you're making a general CFG BB within a scope.
1227 pub fn sub_block(bcx: @mut Block, n: &str) -> @mut Block {
1228 new_block(bcx.fcx, Some(bcx), None, bcx.is_lpad, n, None)
1231 pub fn raw_block(fcx: @mut FunctionContext, is_lpad: bool, llbb: BasicBlockRef) -> @mut Block {
1232 @mut Block::new(llbb, None, is_lpad, None, fcx)
1236 // trans_block_cleanups: Go through all the cleanups attached to this
1237 // block and execute them.
1239 // When translating a block that introduces new variables during its scope, we
1240 // need to make sure those variables go out of scope when the block ends. We
1241 // do that by running a 'cleanup' function for each variable.
1242 // trans_block_cleanups runs all the cleanup functions for the block.
1243 pub fn trans_block_cleanups(bcx: @mut Block, cleanups: ~[cleanup]) -> @mut Block {
1244 trans_block_cleanups_(bcx, cleanups, false)
1247 pub fn trans_block_cleanups_(bcx: @mut Block,
1248 cleanups: &[cleanup],
1249 /* cleanup_cx: block, */
1250 is_lpad: bool) -> @mut Block {
1251 let _icx = push_ctxt("trans_block_cleanups");
1252 // NB: Don't short-circuit even if this block is unreachable because
1253 // GC-based cleanup needs to the see that the roots are live.
1255 bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1256 if bcx.unreachable && !no_lpads { return bcx; }
1258 for cu in cleanups.rev_iter() {
1260 clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1261 // Some types don't need to be cleaned up during
1262 // landing pads because they can be freed en mass later
1263 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1272 // In the last argument, Some(block) mean jump to this block, and none means
1273 // this is a landing pad and leaving should be accomplished with a resume
1275 pub fn cleanup_and_leave(bcx: @mut Block,
1276 upto: Option<BasicBlockRef>,
1277 leave: Option<BasicBlockRef>) {
1278 let _icx = push_ctxt("cleanup_and_leave");
1281 let is_lpad = leave == None;
1283 debug!("cleanup_and_leave: leaving %s", cur.to_str());
1285 if bcx.sess().trace() {
1288 (fmt!("cleanup_and_leave(%s)", cur.to_str())).to_managed());
1291 let mut cur_scope = cur.scope;
1293 cur_scope = match cur_scope {
1294 Some (inf) if !inf.empty_cleanups() => {
1295 let (sub_cx, dest, inf_cleanups) = {
1296 let inf = &mut *inf;
1298 let mut dest = None;
1300 let r = (*inf).cleanup_paths.rev_iter().find(|cp| cp.target == leave);
1301 for cp in r.iter() {
1302 if cp.size == inf.cleanups.len() {
1308 dest = Some(cp.dest);
1311 let sub_cx = sub_block(bcx, "cleanup");
1312 Br(bcx, sub_cx.llbb);
1313 inf.cleanup_paths.push(cleanup_path {
1315 size: inf.cleanups.len(),
1318 (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1320 bcx = trans_block_cleanups_(sub_cx,
1323 for &dest in dest.iter() {
1329 Some(inf) => inf.parent,
1335 Some(bb) => { if cur.llbb == bb { break; } }
1338 cur = match cur.parent {
1340 None => { assert!(upto.is_none()); break; }
1344 Some(target) => Br(bcx, target),
1345 None => { Resume(bcx, Load(bcx, bcx.fcx.personality.unwrap())); }
1349 pub fn cleanup_block(bcx: @mut Block, upto: Option<BasicBlockRef>) -> @mut Block{
1350 let _icx = push_ctxt("cleanup_block");
1354 debug!("cleanup_block: %s", cur.to_str());
1356 if bcx.sess().trace() {
1359 (fmt!("cleanup_block(%s)", cur.to_str())).to_managed());
1362 let mut cur_scope = cur.scope;
1364 cur_scope = match cur_scope {
1366 bcx = trans_block_cleanups_(bcx, inf.cleanups.to_owned(), false);
1374 Some(bb) => { if cur.llbb == bb { break; } }
1377 cur = match cur.parent {
1379 None => { assert!(upto.is_none()); break; }
1385 pub fn cleanup_and_Br(bcx: @mut Block, upto: @mut Block, target: BasicBlockRef) {
1386 let _icx = push_ctxt("cleanup_and_Br");
1387 cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1390 pub fn leave_block(bcx: @mut Block, out_of: @mut Block) -> @mut Block {
1391 let _icx = push_ctxt("leave_block");
1392 let next_cx = sub_block(block_parent(out_of), "next");
1393 if bcx.unreachable { Unreachable(next_cx); }
1394 cleanup_and_Br(bcx, out_of, next_cx.llbb);
1398 pub fn with_scope(bcx: @mut Block,
1399 opt_node_info: Option<NodeInfo>,
1401 f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1402 let _icx = push_ctxt("with_scope");
1404 debug!("with_scope(bcx=%s, opt_node_info=%?, name=%s)",
1405 bcx.to_str(), opt_node_info, name);
1406 let _indenter = indenter();
1408 let scope = simple_block_scope(bcx.scope, opt_node_info);
1409 bcx.scope = Some(scope);
1411 let ret = trans_block_cleanups_(ret, (scope.cleanups).clone(), false);
1412 bcx.scope = scope.parent;
1416 pub fn with_scope_result(bcx: @mut Block,
1417 opt_node_info: Option<NodeInfo>,
1419 f: &fn(@mut Block) -> Result) -> Result {
1420 let _icx = push_ctxt("with_scope_result");
1422 let scope = simple_block_scope(bcx.scope, opt_node_info);
1423 bcx.scope = Some(scope);
1424 let Result { bcx: out_bcx, val } = f(bcx);
1425 let out_bcx = trans_block_cleanups_(out_bcx,
1426 (scope.cleanups).clone(),
1428 bcx.scope = scope.parent;
1433 pub fn with_scope_datumblock(bcx: @mut Block, opt_node_info: Option<NodeInfo>,
1434 name: &str, f: &fn(@mut Block) -> datum::DatumBlock)
1435 -> datum::DatumBlock {
1436 use middle::trans::datum::DatumBlock;
1438 let _icx = push_ctxt("with_scope_result");
1439 let scope_cx = scope_block(bcx, opt_node_info, name);
1440 Br(bcx, scope_cx.llbb);
1441 let DatumBlock {bcx, datum} = f(scope_cx);
1442 DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1445 pub fn block_locals(b: &ast::Block, it: &fn(@ast::Local)) {
1446 for s in b.stmts.iter() {
1448 ast::StmtDecl(d, _) => {
1450 ast::DeclLocal(ref local) => it(*local),
1451 _ => {} /* fall through */
1454 _ => {} /* fall through */
1459 pub fn with_cond(bcx: @mut Block, val: ValueRef, f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1460 let _icx = push_ctxt("with_cond");
1461 let next_cx = base::sub_block(bcx, "next");
1462 let cond_cx = base::sub_block(bcx, "cond");
1463 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1464 let after_cx = f(cond_cx);
1465 if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1469 pub fn call_memcpy(cx: @mut Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1470 let _icx = push_ctxt("call_memcpy");
1472 let key = match ccx.sess.targ_cfg.arch {
1473 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1474 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1476 let memcpy = ccx.intrinsics.get_copy(&key);
1477 let src_ptr = PointerCast(cx, src, Type::i8p());
1478 let dst_ptr = PointerCast(cx, dst, Type::i8p());
1479 let size = IntCast(cx, n_bytes, ccx.int_type);
1480 let align = C_i32(align as i32);
1481 let volatile = C_i1(false);
1482 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1485 pub fn memcpy_ty(bcx: @mut Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1486 let _icx = push_ctxt("memcpy_ty");
1487 let ccx = bcx.ccx();
1488 if ty::type_is_structural(t) {
1489 let llty = type_of::type_of(ccx, t);
1490 let llsz = llsize_of(ccx, llty);
1491 let llalign = llalign_of_min(ccx, llty);
1492 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1494 Store(bcx, Load(bcx, src), dst);
1498 pub fn zero_mem(cx: @mut Block, llptr: ValueRef, t: ty::t) {
1499 if cx.unreachable { return; }
1500 let _icx = push_ctxt("zero_mem");
1503 let llty = type_of::type_of(ccx, t);
1504 memzero(&B(bcx), llptr, llty);
1507 // Always use this function instead of storing a zero constant to the memory
1508 // in question. If you store a zero constant, LLVM will drown in vreg
1509 // allocation for large data structures, and the generated code will be
1510 // awful. (A telltale sign of this is large quantities of
1511 // `mov [byte ptr foo],0` in the generated code.)
1512 pub fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1513 let _icx = push_ctxt("memzero");
1516 let intrinsic_key = match ccx.sess.targ_cfg.arch {
1517 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1518 X86_64 => "llvm.memset.p0i8.i64"
1521 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1522 let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1523 let llzeroval = C_u8(0);
1524 let size = machine::llsize_of(ccx, ty);
1525 let align = C_i32(llalign_of_min(ccx, ty) as i32);
1526 let volatile = C_i1(false);
1527 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1530 pub fn alloc_ty(bcx: @mut Block, t: ty::t, name: &str) -> ValueRef {
1531 let _icx = push_ctxt("alloc_ty");
1532 let ccx = bcx.ccx();
1533 let ty = type_of::type_of(ccx, t);
1534 assert!(!ty::type_has_params(t), "Type has params: %s", ty_to_str(ccx.tcx, t));
1535 let val = alloca(bcx, ty, name);
1539 pub fn alloca(cx: @mut Block, ty: Type, name: &str) -> ValueRef {
1540 alloca_maybe_zeroed(cx, ty, name, false)
1543 pub fn alloca_maybe_zeroed(cx: @mut Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1544 let _icx = push_ctxt("alloca");
1547 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1550 let p = Alloca(cx, ty, name);
1552 let b = cx.fcx.ccx.builder();
1553 b.position_before(cx.fcx.alloca_insert_pt.unwrap());
1559 pub fn arrayalloca(cx: @mut Block, ty: Type, v: ValueRef) -> ValueRef {
1560 let _icx = push_ctxt("arrayalloca");
1563 return llvm::LLVMGetUndef(ty.to_ref());
1566 return ArrayAlloca(cx, ty, v);
1569 pub struct BasicBlocks {
1573 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1575 let cx = task_llcx();
1576 do "static_allocas".with_c_str | buf| {
1577 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1582 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1584 let cx = task_llcx();
1585 do "return".with_c_str |buf| {
1586 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1591 // Creates and returns space for, or returns the argument representing, the
1592 // slot where the return value of the function must go.
1593 pub fn make_return_pointer(fcx: @mut FunctionContext, output_type: ty::t) -> ValueRef {
1595 if type_of::return_uses_outptr(fcx.ccx.tcx, output_type) {
1596 llvm::LLVMGetParam(fcx.llfn, 0)
1598 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1599 let bcx = fcx.entry_bcx.unwrap();
1600 Alloca(bcx, lloutputtype, "__make_return_pointer")
1605 // NB: must keep 4 fns in sync:
1608 // - create_llargs_for_fn_args.
1611 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1617 param_substs: Option<@param_substs>,
1618 opt_node_info: Option<NodeInfo>,
1620 -> @mut FunctionContext {
1621 for p in param_substs.iter() { p.validate(); }
1623 debug!("new_fn_ctxt_w_id(path=%s, id=%?, \
1625 path_str(ccx.sess, path),
1627 param_substs.repr(ccx.tcx));
1629 let substd_output_type = match param_substs {
1630 None => output_type,
1632 ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1635 let uses_outptr = type_of::return_uses_outptr(ccx.tcx, substd_output_type);
1636 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1638 let fcx = @mut FunctionContext {
1641 llvm::LLVMGetUndef(Type::i8p().to_ref())
1645 alloca_insert_pt: None,
1649 caller_expects_out_pointer: uses_outptr,
1650 llargs: @mut HashMap::new(),
1651 lllocals: @mut HashMap::new(),
1652 llupvars: @mut HashMap::new(),
1654 param_substs: param_substs,
1658 debug_context: debug_context,
1660 fcx.llenv = unsafe {
1661 llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1665 let entry_bcx = top_scope_block(fcx, opt_node_info);
1666 Load(entry_bcx, C_null(Type::i8p()));
1668 fcx.entry_bcx = Some(entry_bcx);
1669 fcx.alloca_insert_pt = Some(llvm::LLVMGetFirstInstruction(entry_bcx.llbb));
1672 if !ty::type_is_voidish(substd_output_type) {
1673 // If the function returns nil/bot, there is no real return
1674 // value, so do not set `llretptr`.
1675 if !skip_retptr || uses_outptr {
1676 // Otherwise, we normally allocate the llretptr, unless we
1677 // have been instructed to skip it for immediate return
1679 fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1685 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1690 -> @mut FunctionContext {
1691 new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, false, None, None, sp)
1694 // NB: must keep 4 fns in sync:
1697 // - create_llargs_for_fn_args.
1701 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1702 // allocas created for them.
1704 // When we translate a function, we need to map its incoming arguments to the
1705 // spaces that have been created for them (by code in the llallocas field of
1706 // the function's fn_ctxt). create_llargs_for_fn_args populates the llargs
1707 // field of the fn_ctxt with
1708 pub fn create_llargs_for_fn_args(cx: @mut FunctionContext,
1713 let _icx = push_ctxt("create_llargs_for_fn_args");
1716 impl_self(tt, self_mode) => {
1717 cx.llself = Some(ValSelfData {
1720 is_copy: self_mode == ty::ByCopy
1726 // Return an array containing the ValueRefs that we get from
1727 // llvm::LLVMGetParam for each argument.
1728 do vec::from_fn(args.len()) |i| {
1729 let arg_n = cx.arg_pos(i);
1730 let arg_ty = arg_tys[i];
1731 let llarg = unsafe {llvm::LLVMGetParam(cx.llfn, arg_n as c_uint) };
1733 match ty::get(arg_ty).sty {
1734 // `~` pointer parameters never alias because ownership is transferred
1736 ty::ty_evec(_, ty::vstore_uniq) |
1737 ty::ty_closure(ty::ClosureTy {sigil: ast::OwnedSigil, _}) => {
1739 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
1749 pub fn copy_args_to_allocas(fcx: @mut FunctionContext,
1752 raw_llargs: &[ValueRef],
1753 arg_tys: &[ty::t]) -> @mut Block {
1754 debug!("copy_args_to_allocas: raw_llargs=%s arg_tys=%s",
1755 raw_llargs.llrepr(fcx.ccx),
1756 arg_tys.repr(fcx.ccx.tcx));
1758 let _icx = push_ctxt("copy_args_to_allocas");
1763 let self_val = if slf.is_copy
1764 && datum::appropriate_mode(bcx.tcx(), slf.t).is_by_value() {
1765 let tmp = BitCast(bcx, slf.v, type_of(bcx.ccx(), slf.t));
1766 let alloc = alloc_ty(bcx, slf.t, "__self");
1767 Store(bcx, tmp, alloc);
1770 PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to())
1773 fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1774 add_clean(bcx, self_val, slf.t);
1776 if fcx.ccx.sess.opts.extra_debuginfo {
1777 debuginfo::create_self_argument_metadata(bcx, slf.t, self_val);
1783 for (arg_n, &arg_ty) in arg_tys.iter().enumerate() {
1784 let raw_llarg = raw_llargs[arg_n];
1786 // For certain mode/type combinations, the raw llarg values are passed
1787 // by value. However, within the fn body itself, we want to always
1788 // have all locals and arguments be by-ref so that we can cancel the
1789 // cleanup and for better interaction with LLVM's debug info. So, if
1790 // the argument would be passed by value, we store it into an alloca.
1791 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1792 // the event it's not truly needed.
1793 // only by value if immediate:
1794 let llarg = if datum::appropriate_mode(bcx.tcx(), arg_ty).is_by_value() {
1795 let alloc = alloc_ty(bcx, arg_ty, "__arg");
1796 Store(bcx, raw_llarg, alloc);
1801 bcx = _match::store_arg(bcx, args[arg_n].pat, llarg);
1803 if fcx.ccx.sess.opts.extra_debuginfo {
1804 debuginfo::create_argument_metadata(bcx, &args[arg_n]);
1811 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1812 // and builds the return block.
1813 pub fn finish_fn(fcx: @mut FunctionContext, last_bcx: @mut Block) {
1814 let _icx = push_ctxt("finish_fn");
1816 let ret_cx = match fcx.llreturn {
1818 if !last_bcx.terminated {
1819 Br(last_bcx, llreturn);
1821 raw_block(fcx, false, llreturn)
1825 build_return_block(fcx, ret_cx);
1829 // Builds the return block for a function.
1830 pub fn build_return_block(fcx: &FunctionContext, ret_cx: @mut Block) {
1831 // Return the value if this function immediate; otherwise, return void.
1832 if fcx.llretptr.is_none() || fcx.caller_expects_out_pointer {
1833 return RetVoid(ret_cx);
1836 let retptr = Value(fcx.llretptr.unwrap());
1837 let retval = match retptr.get_dominating_store(ret_cx) {
1838 // If there's only a single store to the ret slot, we can directly return
1839 // the value that was stored and omit the store and the alloca
1841 let retval = *s.get_operand(0).unwrap();
1842 s.erase_from_parent();
1844 if retptr.has_no_uses() {
1845 retptr.erase_from_parent();
1850 // Otherwise, load the return value from the ret slot
1851 None => Load(ret_cx, fcx.llretptr.unwrap())
1855 Ret(ret_cx, retval);
1858 pub enum self_arg { impl_self(ty::t, ty::SelfMode), no_self, }
1860 // trans_closure: Builds an LLVM function out of a source function.
1861 // If the function closes over its environment a closure will be
1863 pub fn trans_closure(ccx: @mut CrateContext,
1865 decl: &ast::fn_decl,
1869 param_substs: Option<@param_substs>,
1871 attributes: &[ast::Attribute],
1873 maybe_load_env: &fn(@mut FunctionContext)) {
1874 ccx.stats.n_closures += 1;
1875 let _icx = push_ctxt("trans_closure");
1876 set_uwtable(llfndecl);
1878 debug!("trans_closure(..., param_substs=%s)",
1879 param_substs.repr(ccx.tcx));
1881 let fcx = new_fn_ctxt_w_id(ccx,
1891 // Create the first basic block in the function and keep a handle on it to
1892 // pass to finish_fn later.
1893 let bcx_top = fcx.entry_bcx.unwrap();
1894 let mut bcx = bcx_top;
1895 let block_ty = node_id_type(bcx, body.id);
1897 // Set up arguments to the function.
1898 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1899 let raw_llargs = create_llargs_for_fn_args(fcx, self_arg,
1900 decl.inputs, arg_tys);
1902 // Set the fixed stack segment flag if necessary.
1903 if attr::contains_name(attributes, "fixed_stack_segment") {
1904 set_no_inline(fcx.llfn);
1905 set_fixed_stack_segment(fcx.llfn);
1908 bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1910 maybe_load_env(fcx);
1912 // Up until here, IR instructions for this function have explicitly not been annotated with
1913 // source code location, so we don't step into call setup code. From here on, source location
1914 // emitting should be enabled.
1915 debuginfo::start_emitting_source_locations(fcx);
1917 // This call to trans_block is the place where we bridge between
1918 // translation calls that don't have a return value (trans_crate,
1919 // trans_mod, trans_item, et cetera) and those that do
1920 // (trans_block, trans_expr, et cetera).
1921 if body.expr.is_none() || ty::type_is_voidish(block_ty) {
1922 bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1924 let dest = expr::SaveIn(fcx.llretptr.unwrap());
1925 bcx = controlflow::trans_block(bcx, body, dest);
1928 match fcx.llreturn {
1929 Some(llreturn) => cleanup_and_Br(bcx, bcx_top, llreturn),
1930 None => bcx = cleanup_block(bcx, Some(bcx_top.llbb))
1933 // Put return block after all other blocks.
1934 // This somewhat improves single-stepping experience in debugger.
1936 for &llreturn in fcx.llreturn.iter() {
1937 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1941 // Insert the mandatory first few basic blocks before lltop.
1942 finish_fn(fcx, bcx);
1945 // trans_fn: creates an LLVM function corresponding to a source language
1947 pub fn trans_fn(ccx: @mut CrateContext,
1949 decl: &ast::fn_decl,
1953 param_substs: Option<@param_substs>,
1955 attrs: &[ast::Attribute]) {
1957 let the_path_str = path_str(ccx.sess, path);
1958 let _s = StatRecorder::new(ccx, the_path_str);
1959 debug!("trans_fn(self_arg=%?, param_substs=%s)",
1961 param_substs.repr(ccx.tcx));
1962 let _icx = push_ctxt("trans_fn");
1963 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1965 match ty::get(output_type).sty {
1966 // `~` pointer return values never alias because ownership is transferred
1968 ty::ty_evec(_, ty::vstore_uniq) => {
1970 llvm::LLVMAddReturnAttribute(llfndecl, lib::llvm::NoAliasAttribute as c_uint);
1989 fn insert_synthetic_type_entries(bcx: @mut Block,
1990 fn_args: &[ast::arg],
1994 * For tuple-like structs and enum-variants, we generate
1995 * synthetic AST nodes for the arguments. These have no types
1996 * in the type table and no entries in the moves table,
1997 * so the code in `copy_args_to_allocas` and `bind_irrefutable_pat`
1998 * gets upset. This hack of a function bridges the gap by inserting types.
2000 * This feels horrible. I think we should just have a special path
2001 * for these functions and not try to use the generic code, but
2002 * that's not the problem I'm trying to solve right now. - nmatsakis
2005 let tcx = bcx.tcx();
2006 for i in range(0u, fn_args.len()) {
2007 debug!("setting type of argument %u (pat node %d) to %s",
2008 i, fn_args[i].pat.id, bcx.ty_to_str(arg_tys[i]));
2010 let pat_id = fn_args[i].pat.id;
2011 let arg_ty = arg_tys[i];
2012 tcx.node_types.insert(pat_id as uint, arg_ty);
2016 pub fn trans_enum_variant(ccx: @mut CrateContext,
2017 _enum_id: ast::NodeId,
2018 variant: &ast::variant,
2019 args: &[ast::variant_arg],
2021 param_substs: Option<@param_substs>,
2022 llfndecl: ValueRef) {
2023 let _icx = push_ctxt("trans_enum_variant");
2025 trans_enum_variant_or_tuple_like_struct(
2034 pub fn trans_tuple_struct(ccx: @mut CrateContext,
2035 fields: &[@ast::struct_field],
2036 ctor_id: ast::NodeId,
2037 param_substs: Option<@param_substs>,
2038 llfndecl: ValueRef) {
2039 let _icx = push_ctxt("trans_tuple_struct");
2041 trans_enum_variant_or_tuple_like_struct(
2051 fn id(&self) -> ast::NodeId;
2052 fn ty<'a>(&'a self) -> &'a ast::Ty;
2055 impl IdAndTy for ast::variant_arg {
2056 fn id(&self) -> ast::NodeId { self.id }
2057 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.ty }
2060 impl IdAndTy for @ast::struct_field {
2061 fn id(&self) -> ast::NodeId { self.node.id }
2062 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.node.ty }
2065 pub fn trans_enum_variant_or_tuple_like_struct<A:IdAndTy>(
2066 ccx: @mut CrateContext,
2067 ctor_id: ast::NodeId,
2070 param_substs: Option<@param_substs>,
2073 // Translate variant arguments to function arguments.
2074 let fn_args = do args.map |varg| {
2077 ty: (*varg.ty()).clone(),
2078 pat: ast_util::ident_to_pat(
2079 ccx.tcx.sess.next_node_id(),
2080 codemap::dummy_sp(),
2081 special_idents::arg),
2086 let no_substs: &[ty::t] = [];
2087 let ty_param_substs = match param_substs {
2088 Some(ref substs) => {
2089 let v: &[ty::t] = substs.tys;
2093 let v: &[ty::t] = no_substs;
2098 let ctor_ty = ty::subst_tps(ccx.tcx,
2101 ty::node_id_to_type(ccx.tcx, ctor_id));
2103 let result_ty = match ty::get(ctor_ty).sty {
2104 ty::ty_bare_fn(ref bft) => bft.sig.output,
2106 fmt!("trans_enum_variant_or_tuple_like_struct: \
2107 unexpected ctor return type %s",
2108 ty_to_str(ccx.tcx, ctor_ty)))
2111 let fcx = new_fn_ctxt_w_id(ccx,
2121 let arg_tys = ty::ty_fn_args(ctor_ty);
2123 let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args, arg_tys);
2125 let bcx = fcx.entry_bcx.unwrap();
2127 insert_synthetic_type_entries(bcx, fn_args, arg_tys);
2128 let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2130 let repr = adt::represent_type(ccx, result_ty);
2131 adt::trans_start_init(bcx, repr, fcx.llretptr.unwrap(), disr);
2132 for (i, fn_arg) in fn_args.iter().enumerate() {
2133 let lldestptr = adt::trans_field_ptr(bcx,
2135 fcx.llretptr.unwrap(),
2138 let llarg = fcx.llargs.get_copy(&fn_arg.pat.id);
2139 let arg_ty = arg_tys[i];
2140 memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2142 finish_fn(fcx, bcx);
2145 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2146 id: ast::NodeId, vi: @~[@ty::VariantInfo],
2148 for variant in enum_definition.variants.iter() {
2149 let disr_val = vi[*i].disr_val;
2152 match variant.node.kind {
2153 ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2154 let llfn = get_item_val(ccx, variant.node.id);
2155 trans_enum_variant(ccx, id, variant, *args,
2156 disr_val, None, llfn);
2158 ast::tuple_variant_kind(_) => {
2161 ast::struct_variant_kind(struct_def) => {
2162 trans_struct_def(ccx, struct_def);
2168 pub struct TransItemVisitor;
2170 impl Visitor<@mut CrateContext> for TransItemVisitor {
2171 fn visit_item(&mut self, i: @ast::item, ccx: @mut CrateContext) {
2176 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2177 let _icx = push_ctxt("trans_item");
2178 let path = match ccx.tcx.items.get_copy(&item.id) {
2179 ast_map::node_item(_, p) => p,
2181 _ => fail!("trans_item"),
2184 ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2185 if purity == ast::extern_fn {
2186 let llfndecl = get_item_val(ccx, item.id);
2187 foreign::trans_rust_fn_with_foreign_abi(
2189 &vec::append((*path).clone(),
2190 [path_name(item.ident)]),
2195 } else if !generics.is_type_parameterized() {
2196 let llfndecl = get_item_val(ccx, item.id);
2198 vec::append((*path).clone(), [path_name(item.ident)]),
2207 // Be sure to travel more than just one layer deep to catch nested
2208 // items in blocks and such.
2209 let mut v = TransItemVisitor;
2210 v.visit_block(body, ccx);
2213 ast::item_impl(ref generics, _, _, ref ms) => {
2214 meth::trans_impl(ccx,
2221 ast::item_mod(ref m) => {
2224 ast::item_enum(ref enum_definition, ref generics) => {
2225 if !generics.is_type_parameterized() {
2226 let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2228 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2231 ast::item_static(_, m, expr) => {
2232 consts::trans_const(ccx, m, item.id);
2233 // Do static_assert checking. It can't really be done much earlier
2234 // because we need to get the value of the bool out of LLVM
2235 if attr::contains_name(item.attrs, "static_assert") {
2236 if m == ast::MutMutable {
2237 ccx.sess.span_fatal(expr.span,
2238 "cannot have static_assert on a mutable \
2241 let v = ccx.const_values.get_copy(&item.id);
2243 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2244 ccx.sess.span_fatal(expr.span, "static assertion failed");
2249 ast::item_foreign_mod(ref foreign_mod) => {
2250 foreign::trans_foreign_mod(ccx, foreign_mod);
2252 ast::item_struct(struct_def, ref generics) => {
2253 if !generics.is_type_parameterized() {
2254 trans_struct_def(ccx, struct_def);
2257 ast::item_trait(*) => {
2258 // Inside of this trait definition, we won't be actually translating any
2259 // functions, but the trait still needs to be walked. Otherwise default
2260 // methods with items will not get translated and will cause ICE's when
2261 // metadata time comes around.
2262 let mut v = TransItemVisitor;
2263 visit::walk_item(&mut v, item, ccx);
2265 _ => {/* fall through */ }
2269 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2270 // If this is a tuple-like struct, translate the constructor.
2271 match struct_def.ctor_id {
2272 // We only need to translate a constructor if there are fields;
2273 // otherwise this is a unit-like struct.
2274 Some(ctor_id) if struct_def.fields.len() > 0 => {
2275 let llfndecl = get_item_val(ccx, ctor_id);
2276 trans_tuple_struct(ccx, struct_def.fields,
2277 ctor_id, None, llfndecl);
2279 Some(_) | None => {}
2283 // Translate a module. Doing this amounts to translating the items in the
2284 // module; there ends up being no artifact (aside from linkage names) of
2285 // separate modules in the compiled program. That's because modules exist
2286 // only as a convenience for humans working with the code, to organize names
2287 // and control visibility.
2288 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2289 let _icx = push_ctxt("trans_mod");
2290 for item in m.items.iter() {
2291 trans_item(ccx, *item);
2295 pub fn register_fn(ccx: @mut CrateContext,
2298 node_id: ast::NodeId,
2301 let llfty = type_of_fn_from_ty(ccx, node_type);
2302 register_fn_llvmty(ccx, sp, sym, node_id, lib::llvm::CCallConv, llfty)
2305 pub fn register_fn_llvmty(ccx: @mut CrateContext,
2308 node_id: ast::NodeId,
2309 cc: lib::llvm::CallConv,
2312 debug!("register_fn_fuller creating fn for item %d with path %s",
2314 ast_map::path_to_str(item_path(ccx, &node_id), token::get_ident_interner()));
2316 let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty);
2317 ccx.item_symbols.insert(node_id, sym);
2319 // FIXME #4404 android JNI hacks
2320 let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2321 (*ccx.sess.building_library &&
2322 ccx.sess.targ_cfg.os == session::OsAndroid));
2324 create_entry_wrapper(ccx, sp, llfn);
2329 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2330 match *sess.entry_fn {
2331 Some((entry_id, _)) => node_id == entry_id,
2336 // Create a _rust_main(args: ~[str]) function which will be called from the
2337 // runtime rust_start function
2338 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2340 main_llfn: ValueRef) {
2341 let et = ccx.sess.entry_type.unwrap();
2343 session::EntryMain => {
2344 let llfn = create_main(ccx, main_llfn);
2345 create_entry_fn(ccx, llfn, true);
2347 session::EntryStart => create_entry_fn(ccx, main_llfn, false),
2348 session::EntryNone => {} // Do nothing.
2351 fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
2352 let nt = ty::mk_nil();
2353 let llfty = type_of_rust_fn(ccx, [], nt);
2354 let llfdecl = decl_fn(ccx.llmod, "_rust_main",
2355 lib::llvm::CCallConv, llfty);
2357 let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None);
2359 // the args vector built in create_entry_fn will need
2360 // be updated if this assertion starts to fail.
2361 assert!(!fcx.caller_expects_out_pointer);
2363 let bcx = fcx.entry_bcx.unwrap();
2365 let llenvarg = unsafe {
2366 let env_arg = fcx.env_arg_pos();
2367 llvm::LLVMGetParam(llfdecl, env_arg as c_uint)
2369 let args = ~[llenvarg];
2370 Call(bcx, main_llfn, args, []);
2372 finish_fn(fcx, bcx);
2376 fn create_entry_fn(ccx: @mut CrateContext,
2377 rust_main: ValueRef,
2378 use_start_lang_item: bool) {
2379 let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
2382 // FIXME #4404 android JNI hacks
2383 let main_name = if *ccx.sess.building_library {
2388 let llfn = decl_cdecl_fn(ccx.llmod, main_name, llfty);
2389 let llbb = do "top".with_c_str |buf| {
2391 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2394 let bld = ccx.builder.B;
2396 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2398 let crate_map = ccx.crate_map;
2399 let opaque_crate_map = do "crate_map".with_c_str |buf| {
2400 llvm::LLVMBuildPointerCast(bld, crate_map, Type::i8p().to_ref(), buf)
2403 let (start_fn, args) = if use_start_lang_item {
2404 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2406 Err(s) => { ccx.tcx.sess.fatal(s); }
2408 let start_fn = if start_def_id.crate == ast::LOCAL_CRATE {
2409 get_item_val(ccx, start_def_id.node)
2411 let start_fn_type = csearch::get_type(ccx.tcx,
2413 trans_external_path(ccx, start_def_id, start_fn_type)
2417 let opaque_rust_main = do "rust_main".with_c_str |buf| {
2418 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2422 C_null(Type::opaque_box(ccx).ptr_to()),
2424 llvm::LLVMGetParam(llfn, 0),
2425 llvm::LLVMGetParam(llfn, 1),
2431 debug!("using user-defined start fn");
2433 C_null(Type::opaque_box(ccx).ptr_to()),
2434 llvm::LLVMGetParam(llfn, 0 as c_uint),
2435 llvm::LLVMGetParam(llfn, 1 as c_uint),
2442 let result = do args.as_imm_buf |buf, len| {
2443 llvm::LLVMBuildCall(bld, start_fn, buf, len as c_uint, noname())
2446 llvm::LLVMBuildRet(bld, result);
2451 pub fn fill_fn_pair(bcx: @mut Block, pair: ValueRef, llfn: ValueRef,
2452 llenvptr: ValueRef) {
2453 let ccx = bcx.ccx();
2454 let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2455 Store(bcx, llfn, code_cell);
2456 let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2457 let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2458 Store(bcx, llenvblobptr, env_cell);
2461 pub fn item_path(ccx: &CrateContext, id: &ast::NodeId) -> path {
2462 ty::item_path(ccx.tcx, ast_util::local_def(*id))
2465 fn exported_name(ccx: @mut CrateContext, path: path, ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
2466 match attr::first_attr_value_str_by_name(attrs, "export_name") {
2467 // Use provided name
2468 Some(name) => name.to_owned(),
2471 _ if attr::contains_name(attrs, "no_mangle")
2472 => path_elt_to_str(*path.last(), token::get_ident_interner()),
2474 // Usual name mangling
2475 _ => mangle_exported_name(ccx, path, ty)
2479 pub fn get_item_val(ccx: @mut CrateContext, id: ast::NodeId) -> ValueRef {
2480 debug!("get_item_val(id=`%?`)", id);
2482 let val = ccx.item_vals.find_copy(&id);
2486 let mut exprt = false;
2487 let item = ccx.tcx.items.get_copy(&id);
2488 let val = match item {
2489 ast_map::node_item(i, pth) => {
2491 let elt = path_pretty_name(i.ident, id as u64);
2492 let my_path = vec::append_one((*pth).clone(), elt);
2493 let ty = ty::node_id_to_type(ccx.tcx, i.id);
2494 let sym = exported_name(ccx, my_path, ty, i.attrs);
2496 let v = match i.node {
2497 ast::item_static(_, m, expr) => {
2498 // We need the translated value here, because for enums the
2499 // LLVM type is not fully determined by the Rust type.
2500 let v = consts::const_expr(ccx, expr);
2501 ccx.const_values.insert(id, v);
2502 exprt = (m == ast::MutMutable || i.vis == ast::public);
2505 let llty = llvm::LLVMTypeOf(v);
2506 let g = do sym.with_c_str |buf| {
2507 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2510 // Apply the `unnamed_addr` attribute if
2512 if attr::contains_name(i.attrs,
2513 "address_insignificant"){
2514 lib::llvm::SetUnnamedAddr(g, true);
2515 lib::llvm::SetLinkage(g,
2516 lib::llvm::InternalLinkage);
2519 ccx.item_symbols.insert(i.id, sym);
2524 ast::item_fn(_, purity, _, _, _) => {
2525 let llfn = if purity != ast::extern_fn {
2526 register_fn(ccx, i.span, sym, i.id, ty)
2528 foreign::register_rust_fn_with_foreign_abi(ccx,
2533 set_llvm_fn_attrs(i.attrs, llfn);
2537 _ => fail!("get_item_val: weird result in table")
2540 match (attr::first_attr_value_str_by_name(i.attrs, "link_section")) {
2541 Some(sect) => unsafe {
2542 do sect.with_c_str |buf| {
2543 llvm::LLVMSetSection(v, buf);
2552 ast_map::node_trait_method(trait_method, _, pth) => {
2553 debug!("get_item_val(): processing a node_trait_method");
2554 match *trait_method {
2555 ast::required(_) => {
2556 ccx.sess.bug("unexpected variant: required trait method in \
2559 ast::provided(m) => {
2561 register_method(ccx, id, pth, m)
2566 ast_map::node_method(m, _, pth) => {
2567 register_method(ccx, id, pth, m)
2570 ast_map::node_foreign_item(ni, abis, _, pth) => {
2571 let ty = ty::node_id_to_type(ccx.tcx, ni.id);
2575 ast::foreign_item_fn(*) => {
2576 let path = vec::append((*pth).clone(), [path_name(ni.ident)]);
2577 foreign::register_foreign_item_fn(ccx, abis, &path, ni)
2579 ast::foreign_item_static(*) => {
2580 let ident = token::ident_to_str(&ni.ident);
2581 let g = do ident.with_c_str |buf| {
2583 let ty = type_of(ccx, ty);
2584 llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf)
2592 ast_map::node_variant(ref v, enm, pth) => {
2595 ast::tuple_variant_kind(ref args) => {
2596 assert!(args.len() != 0u);
2597 let pth = vec::append((*pth).clone(),
2598 [path_name(enm.ident),
2599 path_name((*v).node.name)]);
2600 let ty = ty::node_id_to_type(ccx.tcx, id);
2601 let sym = exported_name(ccx, pth, ty, enm.attrs);
2603 llfn = match enm.node {
2604 ast::item_enum(_, _) => {
2605 register_fn(ccx, (*v).span, sym, id, ty)
2607 _ => fail!("node_variant, shouldn't happen")
2610 ast::struct_variant_kind(_) => {
2611 fail!("struct variant kind unexpected in get_item_val")
2614 set_inline_hint(llfn);
2618 ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2619 // Only register the constructor if this is a tuple-like struct.
2620 match struct_def.ctor_id {
2622 ccx.tcx.sess.bug("attempt to register a constructor of \
2623 a non-tuple-like struct")
2626 let ty = ty::node_id_to_type(ccx.tcx, ctor_id);
2627 let sym = exported_name(ccx, (*struct_path).clone(), ty,
2629 let llfn = register_fn(ccx, struct_item.span,
2631 set_inline_hint(llfn);
2638 ccx.sess.bug(fmt!("get_item_val(): unexpected variant: %?",
2643 if !exprt && !ccx.reachable.contains(&id) {
2644 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2647 ccx.item_vals.insert(id, val);
2653 pub fn register_method(ccx: @mut CrateContext,
2655 path: @ast_map::path,
2656 m: @ast::method) -> ValueRef {
2657 let mty = ty::node_id_to_type(ccx.tcx, id);
2659 let mut path = (*path).clone();
2660 path.push(path_pretty_name(m.ident, token::gensym("meth") as u64));
2662 let sym = exported_name(ccx, path, mty, m.attrs);
2664 let llfn = register_fn(ccx, m.span, sym, id, mty);
2665 set_llvm_fn_attrs(m.attrs, llfn);
2669 pub fn vp2i(cx: @mut Block, v: ValueRef) -> ValueRef {
2671 return PtrToInt(cx, v, ccx.int_type);
2674 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2676 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2681 ($intrinsics:ident, $name:expr, $args:expr, $ret:expr) => ({
2683 let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2684 $intrinsics.insert(name, f);
2688 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2689 let i8p = Type::i8p();
2690 let mut intrinsics = HashMap::new();
2692 ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i32",
2693 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2694 ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i64",
2695 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2696 ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i32",
2697 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2698 ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i64",
2699 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2700 ifn!(intrinsics, "llvm.memset.p0i8.i32",
2701 [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2702 ifn!(intrinsics, "llvm.memset.p0i8.i64",
2703 [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2705 ifn!(intrinsics, "llvm.trap", [], Type::void());
2706 ifn!(intrinsics, "llvm.frameaddress", [Type::i32()], i8p);
2708 ifn!(intrinsics, "llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2709 ifn!(intrinsics, "llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2710 ifn!(intrinsics, "llvm.pow.f32", [Type::f32(), Type::f32()], Type::f32());
2711 ifn!(intrinsics, "llvm.pow.f64", [Type::f64(), Type::f64()], Type::f64());
2713 ifn!(intrinsics, "llvm.sqrt.f32", [Type::f32()], Type::f32());
2714 ifn!(intrinsics, "llvm.sqrt.f64", [Type::f64()], Type::f64());
2715 ifn!(intrinsics, "llvm.sin.f32", [Type::f32()], Type::f32());
2716 ifn!(intrinsics, "llvm.sin.f64", [Type::f64()], Type::f64());
2717 ifn!(intrinsics, "llvm.cos.f32", [Type::f32()], Type::f32());
2718 ifn!(intrinsics, "llvm.cos.f64", [Type::f64()], Type::f64());
2719 ifn!(intrinsics, "llvm.exp.f32", [Type::f32()], Type::f32());
2720 ifn!(intrinsics, "llvm.exp.f64", [Type::f64()], Type::f64());
2721 ifn!(intrinsics, "llvm.exp2.f32", [Type::f32()], Type::f32());
2722 ifn!(intrinsics, "llvm.exp2.f64", [Type::f64()], Type::f64());
2723 ifn!(intrinsics, "llvm.log.f32", [Type::f32()], Type::f32());
2724 ifn!(intrinsics, "llvm.log.f64", [Type::f64()], Type::f64());
2725 ifn!(intrinsics, "llvm.log10.f32",[Type::f32()], Type::f32());
2726 ifn!(intrinsics, "llvm.log10.f64",[Type::f64()], Type::f64());
2727 ifn!(intrinsics, "llvm.log2.f32", [Type::f32()], Type::f32());
2728 ifn!(intrinsics, "llvm.log2.f64", [Type::f64()], Type::f64());
2730 ifn!(intrinsics, "llvm.fma.f32", [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2731 ifn!(intrinsics, "llvm.fma.f64", [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2733 ifn!(intrinsics, "llvm.fabs.f32", [Type::f32()], Type::f32());
2734 ifn!(intrinsics, "llvm.fabs.f64", [Type::f64()], Type::f64());
2735 ifn!(intrinsics, "llvm.floor.f32",[Type::f32()], Type::f32());
2736 ifn!(intrinsics, "llvm.floor.f64",[Type::f64()], Type::f64());
2737 ifn!(intrinsics, "llvm.ceil.f32", [Type::f32()], Type::f32());
2738 ifn!(intrinsics, "llvm.ceil.f64", [Type::f64()], Type::f64());
2739 ifn!(intrinsics, "llvm.trunc.f32",[Type::f32()], Type::f32());
2740 ifn!(intrinsics, "llvm.trunc.f64",[Type::f64()], Type::f64());
2742 ifn!(intrinsics, "llvm.ctpop.i8", [Type::i8()], Type::i8());
2743 ifn!(intrinsics, "llvm.ctpop.i16",[Type::i16()], Type::i16());
2744 ifn!(intrinsics, "llvm.ctpop.i32",[Type::i32()], Type::i32());
2745 ifn!(intrinsics, "llvm.ctpop.i64",[Type::i64()], Type::i64());
2747 ifn!(intrinsics, "llvm.ctlz.i8", [Type::i8() , Type::i1()], Type::i8());
2748 ifn!(intrinsics, "llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2749 ifn!(intrinsics, "llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2750 ifn!(intrinsics, "llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2752 ifn!(intrinsics, "llvm.cttz.i8", [Type::i8() , Type::i1()], Type::i8());
2753 ifn!(intrinsics, "llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2754 ifn!(intrinsics, "llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2755 ifn!(intrinsics, "llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2757 ifn!(intrinsics, "llvm.bswap.i16",[Type::i16()], Type::i16());
2758 ifn!(intrinsics, "llvm.bswap.i32",[Type::i32()], Type::i32());
2759 ifn!(intrinsics, "llvm.bswap.i64",[Type::i64()], Type::i64());
2761 ifn!(intrinsics, "llvm.sadd.with.overflow.i8",
2762 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2763 ifn!(intrinsics, "llvm.sadd.with.overflow.i16",
2764 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2765 ifn!(intrinsics, "llvm.sadd.with.overflow.i32",
2766 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2767 ifn!(intrinsics, "llvm.sadd.with.overflow.i64",
2768 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2770 ifn!(intrinsics, "llvm.uadd.with.overflow.i8",
2771 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2772 ifn!(intrinsics, "llvm.uadd.with.overflow.i16",
2773 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2774 ifn!(intrinsics, "llvm.uadd.with.overflow.i32",
2775 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2776 ifn!(intrinsics, "llvm.uadd.with.overflow.i64",
2777 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2779 ifn!(intrinsics, "llvm.ssub.with.overflow.i8",
2780 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2781 ifn!(intrinsics, "llvm.ssub.with.overflow.i16",
2782 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2783 ifn!(intrinsics, "llvm.ssub.with.overflow.i32",
2784 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2785 ifn!(intrinsics, "llvm.ssub.with.overflow.i64",
2786 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2788 ifn!(intrinsics, "llvm.usub.with.overflow.i8",
2789 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2790 ifn!(intrinsics, "llvm.usub.with.overflow.i16",
2791 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2792 ifn!(intrinsics, "llvm.usub.with.overflow.i32",
2793 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2794 ifn!(intrinsics, "llvm.usub.with.overflow.i64",
2795 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2797 ifn!(intrinsics, "llvm.smul.with.overflow.i8",
2798 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2799 ifn!(intrinsics, "llvm.smul.with.overflow.i16",
2800 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2801 ifn!(intrinsics, "llvm.smul.with.overflow.i32",
2802 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2803 ifn!(intrinsics, "llvm.smul.with.overflow.i64",
2804 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2806 ifn!(intrinsics, "llvm.umul.with.overflow.i8",
2807 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2808 ifn!(intrinsics, "llvm.umul.with.overflow.i16",
2809 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2810 ifn!(intrinsics, "llvm.umul.with.overflow.i32",
2811 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2812 ifn!(intrinsics, "llvm.umul.with.overflow.i64",
2813 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2818 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2819 ifn!(intrinsics, "llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2821 "llvm.dbg.value", [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2824 pub fn trap(bcx: @mut Block) {
2825 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2826 Some(&x) => { Call(bcx, x, [], []); },
2827 _ => bcx.sess().bug("unbound llvm.trap in trap")
2831 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2832 if !ccx.sess.opts.gc || !ccx.uses_gc {
2836 let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2837 let gc_metadata = do gc_metadata_name.with_c_str |buf| {
2839 llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2843 llvm::LLVMSetGlobalConstant(gc_metadata, True);
2844 lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2845 ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2849 pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
2850 let elttype = Type::struct_([ccx.int_type, ccx.int_type], false);
2851 let maptype = Type::array(&elttype, (ccx.module_data.len() + 1) as u64);
2852 let map = do "_rust_mod_map".with_c_str |buf| {
2854 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2857 lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2858 let mut elts: ~[ValueRef] = ~[];
2860 // This is not ideal, but the borrow checker doesn't
2861 // like the multiple borrows. At least, it doesn't
2862 // like them on the current snapshot. (2013-06-14)
2864 for (k, _) in ccx.module_data.iter() {
2865 keys.push(k.to_managed());
2868 for key in keys.iter() {
2869 let val = *ccx.module_data.find_equiv(key).unwrap();
2870 let s_const = C_cstr(ccx, *key);
2871 let s_ptr = p2i(ccx, s_const);
2872 let v_ptr = p2i(ccx, val);
2873 let elt = C_struct([s_ptr, v_ptr]);
2876 let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
2879 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2885 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2886 llmod: ModuleRef) -> ValueRef {
2887 let targ_cfg = sess.targ_cfg;
2888 let int_type = Type::int(targ_cfg.arch);
2889 let mut n_subcrates = 1;
2890 let cstore = sess.cstore;
2891 while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2892 let mapname = if *sess.building_library {
2893 fmt!("%s_%s_%s", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2897 let sym_name = ~"_rust_crate_map_" + mapname;
2898 let arrtype = Type::array(&int_type, n_subcrates as u64);
2899 let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false);
2900 let map = do sym_name.with_c_str |buf| {
2902 llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2905 lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2909 pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) {
2910 let mut subcrates: ~[ValueRef] = ~[];
2912 let cstore = ccx.sess.cstore;
2913 while cstore::have_crate_data(cstore, i) {
2914 let cdata = cstore::get_crate_data(cstore, i);
2915 let nm = fmt!("_rust_crate_map_%s_%s_%s",
2917 cstore::get_crate_vers(cstore, i),
2918 cstore::get_crate_hash(cstore, i));
2919 let cr = do nm.with_c_str |buf| {
2921 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2924 subcrates.push(p2i(ccx, cr));
2927 subcrates.push(C_int(ccx, 0));
2930 let mod_map = create_module_map(ccx);
2931 llvm::LLVMSetInitializer(map, C_struct(
2933 // FIXME #8431 This used to be the annihilate function, now it's nothing
2934 C_null(Type::i8p()),
2936 C_array(ccx.int_type, subcrates)]));
2940 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
2941 -> encoder::EncodeParams<'r> {
2943 let diag = cx.sess.diagnostic();
2944 let item_symbols = &cx.item_symbols;
2945 let discrim_symbols = &cx.discrim_symbols;
2946 let link_meta = &cx.link_meta;
2947 encoder::EncodeParams {
2950 reexports2: cx.exp_map2,
2951 item_symbols: item_symbols,
2952 discrim_symbols: discrim_symbols,
2953 link_meta: link_meta,
2954 cstore: cx.sess.cstore,
2955 encode_inlined_item: ie,
2956 reachable: cx.reachable,
2960 pub fn write_metadata(cx: &mut CrateContext, crate: &ast::Crate) {
2961 if !*cx.sess.building_library { return; }
2963 let encode_inlined_item: encoder::encode_inlined_item =
2964 |ecx, ebml_w, path, ii|
2965 astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
2967 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2968 let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
2969 let llconst = C_struct([llmeta]);
2970 let mut llglobal = do "rust_metadata".with_c_str |buf| {
2972 llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
2976 llvm::LLVMSetInitializer(llglobal, llconst);
2977 do cx.sess.targ_cfg.target_strs.meta_sect_name.with_c_str |buf| {
2978 llvm::LLVMSetSection(llglobal, buf)
2980 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2982 let t_ptr_i8 = Type::i8p();
2983 llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
2984 let llvm_used = do "llvm.used".with_c_str |buf| {
2985 llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
2987 lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
2988 llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
2992 fn mk_global(ccx: &CrateContext,
2998 let llglobal = do name.with_c_str |buf| {
2999 llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval).to_ref(), buf)
3001 llvm::LLVMSetInitializer(llglobal, llval);
3002 llvm::LLVMSetGlobalConstant(llglobal, True);
3005 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
3012 // Writes the current ABI version into the crate.
3013 pub fn write_abi_version(ccx: &mut CrateContext) {
3014 mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version), false);
3017 pub fn trans_crate(sess: session::Session,
3019 analysis: &CrateAnalysis,
3020 output: &Path) -> CrateTranslation {
3021 // Before we touch LLVM, make sure that multithreading is enabled.
3022 if unsafe { !llvm::LLVMRustStartMultithreading() } {
3023 //sess.bug("couldn't enable multi-threaded LLVM");
3026 let mut symbol_hasher = hash::default_state();
3027 let link_meta = link::build_link_meta(sess, crate, output, &mut symbol_hasher);
3029 // Append ".rc" to crate name as LLVM module identifier.
3031 // LLVM code generator emits a ".file filename" directive
3032 // for ELF backends. Value of the "filename" is set as the
3033 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
3034 // crashes if the module identifer is same as other symbols
3035 // such as a function name in the module.
3036 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
3037 let llmod_id = link_meta.name.to_owned() + ".rc";
3039 let ccx = @mut CrateContext::new(sess,
3046 analysis.reachable);
3048 if ccx.sess.opts.debuginfo {
3049 debuginfo::initialize(ccx, crate);
3053 let _icx = push_ctxt("text");
3054 trans_mod(ccx, &crate.module);
3057 decl_gc_metadata(ccx, llmod_id);
3058 fill_crate_map(ccx, ccx.crate_map);
3059 glue::emit_tydescs(ccx);
3060 write_abi_version(ccx);
3061 if ccx.sess.opts.debuginfo {
3062 debuginfo::finalize(ccx);
3065 // Translate the metadata.
3066 write_metadata(ccx, crate);
3067 if ccx.sess.trans_stats() {
3068 io::println("--- trans stats ---");
3069 printfln!("n_static_tydescs: %u", ccx.stats.n_static_tydescs);
3070 printfln!("n_glues_created: %u", ccx.stats.n_glues_created);
3071 printfln!("n_null_glues: %u", ccx.stats.n_null_glues);
3072 printfln!("n_real_glues: %u", ccx.stats.n_real_glues);
3074 printfln!("n_fns: %u", ccx.stats.n_fns);
3075 printfln!("n_monos: %u", ccx.stats.n_monos);
3076 printfln!("n_inlines: %u", ccx.stats.n_inlines);
3077 printfln!("n_closures: %u", ccx.stats.n_closures);
3078 io::println("fn stats:");
3079 do sort::quick_sort(ccx.stats.fn_stats) |&(_, _, insns_a), &(_, _, insns_b)| {
3082 for tuple in ccx.stats.fn_stats.iter() {
3084 (ref name, ms, insns) => {
3085 printfln!("%u insns, %u ms, %s", insns, ms, *name);
3090 if ccx.sess.count_llvm_insns() {
3091 for (k, v) in ccx.stats.llvm_insns.iter() {
3092 printfln!("%-7u %s", *v, *k);
3096 let llcx = ccx.llcx;
3097 let link_meta = ccx.link_meta;
3098 let llmod = ccx.llmod;
3100 return CrateTranslation {