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::machine;
56 use middle::trans::machine::{llalign_of_min, llsize_of};
57 use middle::trans::meth;
58 use middle::trans::monomorphize;
59 use middle::trans::tvec;
60 use middle::trans::type_of;
61 use middle::trans::type_of::*;
62 use middle::trans::value::Value;
64 use util::common::indenter;
65 use util::ppaux::{Repr, ty_to_str};
67 use middle::trans::type_::Type;
69 use std::c_str::ToCStr;
71 use std::hashmap::HashMap;
73 use std::libc::c_uint;
79 use syntax::ast::ident;
80 use syntax::ast_map::{path, path_elt_to_str, path_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;
89 use syntax::{ast, ast_util, codemap, ast_map};
90 use syntax::abi::{X86, X86_64, Arm, Mips};
92 pub use middle::trans::context::task_llcx;
94 static task_local_insn_key: local_data::Key<@~[&'static str]> = &local_data::Key;
96 pub fn with_insn_ctxt(blk: &fn(&[&'static str])) {
97 let opt = local_data::get(task_local_insn_key, |k| k.map_move(|k| *k));
103 pub fn init_insn_ctxt() {
104 local_data::set(task_local_insn_key, @~[]);
107 pub struct _InsnCtxt { _x: () }
110 impl Drop for _InsnCtxt {
112 do local_data::modify(task_local_insn_key) |c| {
113 do c.map_move |ctx| {
114 let mut ctx = (*ctx).clone();
122 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
123 debug!("new InsnCtxt: %s", s);
124 do local_data::modify(task_local_insn_key) |c| {
125 do c.map_move |ctx| {
126 let mut ctx = (*ctx).clone();
134 fn fcx_has_nonzero_span(fcx: &FunctionContext) -> bool {
137 Some(span) => *span.lo != 0 || *span.hi != 0
141 struct StatRecorder<'self> {
142 ccx: @mut CrateContext,
148 impl<'self> StatRecorder<'self> {
149 pub fn new(ccx: @mut CrateContext,
150 name: &'self str) -> StatRecorder<'self> {
151 let start = if ccx.sess.trans_stats() {
152 time::precise_time_ns()
156 let istart = ccx.stats.n_llvm_insns;
167 impl<'self> Drop for StatRecorder<'self> {
169 if self.ccx.sess.trans_stats() {
170 let end = time::precise_time_ns();
171 let elapsed = ((end - self.start) / 1_000_000) as uint;
172 let iend = self.ccx.stats.n_llvm_insns;
173 self.ccx.stats.fn_stats.push((self.name.to_owned(),
175 iend - self.istart));
176 self.ccx.stats.n_fns += 1;
177 // Reset LLVM insn count to avoid compound costs.
178 self.ccx.stats.n_llvm_insns = self.istart;
183 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
184 let llfn: ValueRef = do name.to_c_str().with_ref |buf| {
186 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
190 lib::llvm::SetFunctionCallConv(llfn, cc);
194 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
195 return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
198 // Only use this if you are going to actually define the function. It's
199 // not valid to simply declare a function as internal.
200 pub fn decl_internal_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
201 let llfn = decl_cdecl_fn(llmod, name, ty);
202 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
206 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: @str,
207 cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
208 match externs.find_copy(&name) {
212 let f = decl_fn(llmod, name, cc, ty);
213 externs.insert(name, f);
217 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
218 name: @str, ty: Type) -> ValueRef {
219 match externs.find_copy(&name) {
224 let c = do name.to_c_str().with_ref |buf| {
225 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
227 externs.insert(name, c);
231 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
232 let _icx = push_ctxt("umax");
233 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
234 return Select(cx, cond, b, a);
237 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
238 let _icx = push_ctxt("umin");
239 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
240 return Select(cx, cond, a, b);
243 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
244 // The type of the returned pointer is always i8*. If you care about the
245 // return type, use bump_ptr().
246 pub fn ptr_offs(bcx: @mut Block, base: ValueRef, sz: ValueRef) -> ValueRef {
247 let _icx = push_ctxt("ptr_offs");
248 let raw = PointerCast(bcx, base, Type::i8p());
249 InBoundsGEP(bcx, raw, [sz])
252 // Increment a pointer by a given amount and then cast it to be a pointer
254 pub fn bump_ptr(bcx: @mut Block, t: ty::t, base: ValueRef, sz: ValueRef) ->
256 let _icx = push_ctxt("bump_ptr");
258 let bumped = ptr_offs(bcx, base, sz);
259 let typ = type_of(ccx, t).ptr_to();
260 PointerCast(bcx, bumped, typ)
263 // Returns a pointer to the body for the box. The box may be an opaque
264 // box. The result will be casted to the type of body_t, if it is statically
267 // The runtime equivalent is box_body() in "rust_internal.h".
268 pub fn opaque_box_body(bcx: @mut Block,
270 boxptr: ValueRef) -> ValueRef {
271 let _icx = push_ctxt("opaque_box_body");
273 let ty = type_of(ccx, body_t);
274 let ty = Type::box(ccx, &ty);
275 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
276 GEPi(bcx, boxptr, [0u, abi::box_field_body])
279 // malloc_raw_dyn: allocates a box to contain a given type, but with a
280 // potentially dynamic size.
281 pub fn malloc_raw_dyn(bcx: @mut Block,
284 size: ValueRef) -> Result {
285 let _icx = push_ctxt("malloc_raw");
288 fn require_alloc_fn(bcx: @mut Block, t: ty::t, it: LangItem) -> ast::def_id {
289 let li = &bcx.tcx().lang_items;
290 match li.require(it) {
293 bcx.tcx().sess.fatal(fmt!("allocation of `%s` %s",
294 bcx.ty_to_str(t), s));
299 if heap == heap_exchange {
300 let llty_value = type_of::type_of(ccx, t);
304 let r = callee::trans_lang_call(
306 require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
309 rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
311 // we treat ~fn, @fn and @[] as @ here, which isn't ideal
312 let (mk_fn, langcall) = match heap {
313 heap_managed | heap_managed_unique => {
315 require_alloc_fn(bcx, t, MallocFnLangItem))
317 heap_exchange_closure => {
319 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem))
321 _ => fail!("heap_exchange already handled")
324 // Grab the TypeRef type of box_ptr_ty.
325 let box_ptr_ty = mk_fn(bcx.tcx(), t);
326 let llty = type_of(ccx, box_ptr_ty);
328 // Get the tydesc for the body:
329 let static_ti = get_tydesc(ccx, t);
330 glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
333 let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
334 let r = callee::trans_lang_call(
339 let r = rslt(r.bcx, PointerCast(r.bcx, r.val, llty));
340 maybe_set_managed_unique_rc(r.bcx, r.val, heap);
345 // malloc_raw: expects an unboxed type and returns a pointer to
346 // enough space for a box of that type. This includes a rust_opaque_box
348 pub fn malloc_raw(bcx: @mut Block, t: ty::t, heap: heap) -> Result {
349 let ty = type_of(bcx.ccx(), t);
350 let size = llsize_of(bcx.ccx(), ty);
351 malloc_raw_dyn(bcx, t, heap, size)
354 pub struct MallocResult {
360 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
361 // and pulls out the body
362 pub fn malloc_general_dyn(bcx: @mut Block, t: ty::t, heap: heap, size: ValueRef)
364 assert!(heap != heap_exchange);
365 let _icx = push_ctxt("malloc_general");
366 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
367 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
369 MallocResult { bcx: bcx, box: llbox, body: body }
372 pub fn malloc_general(bcx: @mut Block, t: ty::t, heap: heap) -> MallocResult {
373 let ty = type_of(bcx.ccx(), t);
374 assert!(heap != heap_exchange);
375 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
377 pub fn malloc_boxed(bcx: @mut Block, t: ty::t)
379 malloc_general(bcx, t, heap_managed)
382 pub fn heap_for_unique(bcx: @mut Block, t: ty::t) -> heap {
383 if ty::type_contents(bcx.tcx(), t).contains_managed() {
390 pub fn maybe_set_managed_unique_rc(bcx: @mut Block, bx: ValueRef, heap: heap) {
391 assert!(heap != heap_exchange);
392 if heap == heap_managed_unique {
393 // In cases where we are looking at a unique-typed allocation in the
394 // managed heap (thus have refcount 1 from the managed allocator),
395 // such as a ~(@foo) or such. These need to have their refcount forced
396 // to -2 so the annihilator ignores them.
397 let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
398 let rc_val = C_int(bcx.ccx(), -2);
399 Store(bcx, rc_val, rc);
403 // Type descriptor and type glue stuff
405 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
406 get_tydesc(ccx, t).tydesc
409 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
410 match ccx.tydescs.find(&t) {
417 ccx.stats.n_static_tydescs += 1u;
418 let inf = glue::declare_tydesc(ccx, t);
419 ccx.tydescs.insert(t, inf);
423 pub fn set_optimize_for_size(f: ValueRef) {
424 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
427 pub fn set_no_inline(f: ValueRef) {
428 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
431 pub fn set_no_unwind(f: ValueRef) {
432 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
435 // Tell LLVM to emit the information necessary to unwind the stack for the
437 pub fn set_uwtable(f: ValueRef) {
438 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
441 pub fn set_inline_hint(f: ValueRef) {
442 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
445 pub fn set_inline_hint_if_appr(attrs: &[ast::Attribute],
448 match find_inline_attr(attrs) {
449 InlineHint => set_inline_hint(llfn),
450 InlineAlways => set_always_inline(llfn),
451 InlineNever => set_no_inline(llfn),
452 InlineNone => { /* fallthrough */ }
456 pub fn set_always_inline(f: ValueRef) {
457 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
460 pub fn set_fixed_stack_segment(f: ValueRef) {
461 lib::llvm::SetFixedStackSegmentAttribute(f);
464 pub fn set_glue_inlining(f: ValueRef, t: ty::t) {
465 if ty::type_is_structural(t) {
466 set_optimize_for_size(f);
467 } else { set_always_inline(f); }
470 // Double-check that we never ask LLVM to declare the same symbol twice. It
471 // silently mangles such symbols, breaking our linkage model.
472 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
473 if ccx.all_llvm_symbols.contains(&sym) {
474 ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
476 ccx.all_llvm_symbols.insert(sym);
480 pub fn get_res_dtor(ccx: @mut CrateContext,
482 parent_id: ast::def_id,
485 let _icx = push_ctxt("trans_res_dtor");
486 if !substs.is_empty() {
487 let did = if did.crate != ast::LOCAL_CRATE {
488 inline::maybe_instantiate_inline(ccx, did)
492 assert_eq!(did.crate, ast::LOCAL_CRATE);
493 let tsubsts = ty::substs {regions: ty::ErasedRegions,
495 tps: /*bad*/ substs.to_owned() };
496 let (val, _) = monomorphize::monomorphic_fn(ccx,
504 } else if did.crate == ast::LOCAL_CRATE {
505 get_item_val(ccx, did.node)
508 let name = csearch::get_symbol(ccx.sess.cstore, did);
509 let class_ty = ty::subst_tps(tcx,
512 ty::lookup_item_type(tcx, parent_id).ty);
513 let llty = type_of_dtor(ccx, class_ty);
514 let name = name.to_managed(); // :-(
515 get_extern_fn(&mut ccx.externs,
518 lib::llvm::CCallConv,
523 // Structural comparison: a rather involved form of glue.
524 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
525 if cx.sess.opts.save_temps {
526 do s.to_c_str().with_ref |buf| {
528 llvm::LLVMSetValueName(v, buf)
535 // Used only for creating scalar comparison glue.
536 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
538 // NB: This produces an i1, not a Rust bool (i8).
539 pub fn compare_scalar_types(cx: @mut Block,
545 let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
547 match ty::get(t).sty {
548 ty::ty_nil => rslt(cx, f(nil_type)),
549 ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
550 ty::ty_int(_) => rslt(cx, f(signed_int)),
551 ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
552 ty::ty_float(_) => rslt(cx, f(floating_point)),
555 controlflow::trans_fail(
557 @"attempt to compare values of type type"),
561 // Should never get here, because t is scalar.
562 cx.sess().bug("non-scalar type passed to \
563 compare_scalar_types")
569 // A helper function to do the actual comparison of scalar values.
570 pub fn compare_scalar_values(cx: @mut Block,
576 let _icx = push_ctxt("compare_scalar_values");
577 fn die(cx: @mut Block) -> ! {
578 cx.tcx().sess.bug("compare_scalar_values: must be a\
579 comparison operator");
583 // We don't need to do actual comparisons for nil.
584 // () == () holds but () < () does not.
586 ast::eq | ast::le | ast::ge => return C_i1(true),
587 ast::ne | ast::lt | ast::gt => return C_i1(false),
588 // refinements would be nice
594 ast::eq => lib::llvm::RealOEQ,
595 ast::ne => lib::llvm::RealUNE,
596 ast::lt => lib::llvm::RealOLT,
597 ast::le => lib::llvm::RealOLE,
598 ast::gt => lib::llvm::RealOGT,
599 ast::ge => lib::llvm::RealOGE,
602 return FCmp(cx, cmp, lhs, rhs);
606 ast::eq => lib::llvm::IntEQ,
607 ast::ne => lib::llvm::IntNE,
608 ast::lt => lib::llvm::IntSLT,
609 ast::le => lib::llvm::IntSLE,
610 ast::gt => lib::llvm::IntSGT,
611 ast::ge => lib::llvm::IntSGE,
614 return ICmp(cx, cmp, lhs, rhs);
618 ast::eq => lib::llvm::IntEQ,
619 ast::ne => lib::llvm::IntNE,
620 ast::lt => lib::llvm::IntULT,
621 ast::le => lib::llvm::IntULE,
622 ast::gt => lib::llvm::IntUGT,
623 ast::ge => lib::llvm::IntUGE,
626 return ICmp(cx, cmp, lhs, rhs);
631 pub type val_and_ty_fn<'self> = &'self fn(@mut Block, ValueRef, ty::t) -> @mut Block;
633 pub fn load_inbounds(cx: @mut Block, p: ValueRef, idxs: &[uint]) -> ValueRef {
634 return Load(cx, GEPi(cx, p, idxs));
637 pub fn store_inbounds(cx: @mut Block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
638 Store(cx, v, GEPi(cx, p, idxs));
641 // Iterates through the elements of a structural type.
642 pub fn iter_structural_ty(cx: @mut Block, av: ValueRef, t: ty::t,
643 f: val_and_ty_fn) -> @mut Block {
644 let _icx = push_ctxt("iter_structural_ty");
646 fn iter_variant(cx: @mut Block, repr: &adt::Repr, av: ValueRef,
647 variant: @ty::VariantInfo,
648 tps: &[ty::t], f: val_and_ty_fn) -> @mut Block {
649 let _icx = push_ctxt("iter_variant");
653 for (i, &arg) in variant.args.iter().enumerate() {
655 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
656 ty::subst_tps(tcx, tps, None, arg));
662 match ty::get(t).sty {
663 ty::ty_struct(*) => {
664 let repr = adt::represent_type(cx.ccx(), t);
665 do expr::with_field_tys(cx.tcx(), t, None) |discr, field_tys| {
666 for (i, field_ty) in field_tys.iter().enumerate() {
667 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
668 cx = f(cx, llfld_a, field_ty.mt.ty);
672 ty::ty_estr(ty::vstore_fixed(_)) |
673 ty::ty_evec(_, ty::vstore_fixed(_)) => {
674 let (base, len) = tvec::get_base_and_len(cx, av, t);
675 cx = tvec::iter_vec_raw(cx, base, t, len, f);
677 ty::ty_tup(ref args) => {
678 let repr = adt::represent_type(cx.ccx(), t);
679 for (i, arg) in args.iter().enumerate() {
680 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
681 cx = f(cx, llfld_a, *arg);
684 ty::ty_enum(tid, ref substs) => {
687 let repr = adt::represent_type(ccx, t);
688 let variants = ty::enum_variants(ccx.tcx, tid);
689 let n_variants = (*variants).len();
691 // NB: we must hit the discriminant first so that structural
692 // comparison know not to proceed when the discriminants differ.
694 match adt::trans_switch(cx, repr, av) {
695 (_match::single, None) => {
696 cx = iter_variant(cx, repr, av, variants[0],
699 (_match::switch, Some(lldiscrim_a)) => {
700 cx = f(cx, lldiscrim_a, ty::mk_int());
701 let unr_cx = sub_block(cx, "enum-iter-unr");
703 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
705 let next_cx = sub_block(cx, "enum-iter-next");
707 for variant in (*variants).iter() {
709 sub_block(cx, ~"enum-iter-variant-" +
710 uint::to_str(variant.disr_val));
712 iter_variant(variant_cx, repr, av, *variant,
713 substs.tps, |x,y,z| f(x,y,z));
714 match adt::trans_case(cx, repr, variant.disr_val) {
715 _match::single_result(r) => {
716 AddCase(llswitch, r.val, variant_cx.llbb)
718 _ => ccx.sess.unimpl("value from adt::trans_case \
719 in iter_structural_ty")
721 Br(variant_cx, next_cx.llbb);
725 _ => ccx.sess.unimpl("value from adt::trans_switch \
726 in iter_structural_ty")
729 _ => cx.sess().unimpl("type in iter_structural_ty")
734 pub fn cast_shift_expr_rhs(cx: @mut Block, op: ast::binop,
735 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
736 cast_shift_rhs(op, lhs, rhs,
737 |a,b| Trunc(cx, a, b),
738 |a,b| ZExt(cx, a, b))
741 pub fn cast_shift_const_rhs(op: ast::binop,
742 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
743 cast_shift_rhs(op, lhs, rhs,
744 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
745 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
748 pub fn cast_shift_rhs(op: ast::binop,
749 lhs: ValueRef, rhs: ValueRef,
750 trunc: &fn(ValueRef, Type) -> ValueRef,
751 zext: &fn(ValueRef, Type) -> ValueRef)
753 // Shifts may have any size int on the rhs
755 if ast_util::is_shift_binop(op) {
756 let rhs_llty = val_ty(rhs);
757 let lhs_llty = val_ty(lhs);
758 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
759 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
762 } else if lhs_sz > rhs_sz {
763 // FIXME (#1877: If shifting by negative
764 // values becomes not undefined then this is wrong.
775 pub fn fail_if_zero(cx: @mut Block, span: span, divrem: ast::binop,
776 rhs: ValueRef, rhs_t: ty::t) -> @mut Block {
777 let text = if divrem == ast::div {
778 @"attempted to divide by zero"
780 @"attempted remainder with a divisor of zero"
782 let is_zero = match ty::get(rhs_t).sty {
784 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
785 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
788 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
789 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
792 cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
793 ty_to_str(cx.ccx().tcx, rhs_t));
796 do with_cond(cx, is_zero) |bcx| {
797 controlflow::trans_fail(bcx, Some(span), text)
801 pub fn null_env_ptr(bcx: @mut Block) -> ValueRef {
802 C_null(Type::opaque_box(bcx.ccx()).ptr_to())
805 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::def_id, t: ty::t)
807 let name = csearch::get_symbol(ccx.sess.cstore, did).to_managed(); // Sad
808 match ty::get(t).sty {
809 ty::ty_bare_fn(_) | ty::ty_closure(_) => {
810 let llty = type_of_fn_from_ty(ccx, t);
811 return get_extern_fn(&mut ccx.externs, ccx.llmod, name,
812 lib::llvm::CCallConv, llty);
815 let llty = type_of(ccx, t);
816 return get_extern_const(&mut ccx.externs, ccx.llmod, name, llty);
821 pub fn invoke(bcx: @mut Block, llfn: ValueRef, llargs: ~[ValueRef])
822 -> (ValueRef, @mut Block) {
823 let _icx = push_ctxt("invoke_");
825 return (C_null(Type::i8()), bcx);
828 match bcx.node_info {
829 None => debug!("invoke at ???"),
831 debug!("invoke at %s",
832 bcx.sess().codemap.span_to_str(node_info.span));
836 if need_invoke(bcx) {
838 debug!("invoking %x at %x",
839 ::std::cast::transmute(llfn),
840 ::std::cast::transmute(bcx.llbb));
841 for &llarg in llargs.iter() {
842 debug!("arg: %x", ::std::cast::transmute(llarg));
845 let normal_bcx = sub_block(bcx, "normal return");
846 let llresult = Invoke(bcx,
850 get_landing_pad(bcx));
851 return (llresult, normal_bcx);
854 debug!("calling %x at %x",
855 ::std::cast::transmute(llfn),
856 ::std::cast::transmute(bcx.llbb));
857 for &llarg in llargs.iter() {
858 debug!("arg: %x", ::std::cast::transmute(llarg));
861 let llresult = Call(bcx, llfn, llargs);
862 return (llresult, bcx);
866 pub fn need_invoke(bcx: @mut Block) -> bool {
867 if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
871 // Avoid using invoke if we are already inside a landing pad.
876 if have_cached_lpad(bcx) {
880 // Walk the scopes to look for cleanups
882 let mut cur_scope = cur.scope;
884 cur_scope = match cur_scope {
886 for cleanup in inf.cleanups.iter() {
888 clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
889 if cleanup_type == normal_exit_and_unwind {
898 cur = match cur.parent {
908 pub fn have_cached_lpad(bcx: @mut Block) -> bool {
910 do in_lpad_scope_cx(bcx) |inf| {
911 match inf.landing_pad {
912 Some(_) => res = true,
919 pub fn in_lpad_scope_cx(bcx: @mut Block, f: &fn(si: &mut ScopeInfo)) {
921 let mut cur_scope = bcx.scope;
923 cur_scope = match cur_scope {
925 if !inf.empty_cleanups() || (inf.parent.is_none() && bcx.parent.is_none()) {
932 bcx = block_parent(bcx);
939 pub fn get_landing_pad(bcx: @mut Block) -> BasicBlockRef {
940 let _icx = push_ctxt("get_landing_pad");
942 let mut cached = None;
943 let mut pad_bcx = bcx; // Guaranteed to be set below
944 do in_lpad_scope_cx(bcx) |inf| {
945 // If there is a valid landing pad still around, use it
946 match inf.landing_pad {
947 Some(target) => cached = Some(target),
949 pad_bcx = lpad_block(bcx, "unwind");
950 inf.landing_pad = Some(pad_bcx.llbb);
954 // Can't return from block above
955 match cached { Some(b) => return b, None => () }
956 // The landing pad return type (the type being propagated). Not sure what
957 // this represents but it's determined by the personality function and
958 // this is what the EH proposal example uses.
959 let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
960 // The exception handling personality function. This is the C++
961 // personality function __gxx_personality_v0, wrapped in our naming
963 let personality = bcx.ccx().upcalls.rust_personality;
964 // The only landing pad clause will be 'cleanup'
965 let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
966 // The landing pad block is a cleanup
967 SetCleanup(pad_bcx, llretval);
969 // Because we may have unwound across a stack boundary, we must call into
970 // the runtime to figure out which stack segment we are on and place the
971 // stack limit back into the TLS.
972 Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, []);
974 // We store the retval in a function-central alloca, so that calls to
975 // Resume can find it.
976 match bcx.fcx.personality {
977 Some(addr) => Store(pad_bcx, llretval, addr),
979 let addr = alloca(pad_bcx, val_ty(llretval), "");
980 bcx.fcx.personality = Some(addr);
981 Store(pad_bcx, llretval, addr);
985 // Unwind all parent scopes, and finish with a Resume instr
986 cleanup_and_leave(pad_bcx, None, None);
990 pub fn find_bcx_for_scope(bcx: @mut Block, scope_id: ast::NodeId) -> @mut Block {
991 let mut bcx_sid = bcx;
992 let mut cur_scope = bcx_sid.scope;
994 cur_scope = match cur_scope {
996 match inf.node_info {
997 Some(NodeInfo { id, _ }) if id == scope_id => {
1000 // FIXME(#6268, #6248) hacky cleanup for nested method calls
1001 Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
1008 bcx_sid = match bcx_sid.parent {
1009 None => bcx.tcx().sess.bug(fmt!("no enclosing scope with id %d", scope_id)),
1010 Some(bcx_par) => bcx_par
1019 pub fn do_spill(bcx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1020 if ty::type_is_bot(t) {
1021 return C_null(Type::i8p());
1023 let llptr = alloc_ty(bcx, t, "");
1024 Store(bcx, v, llptr);
1028 // Since this function does *not* root, it is the caller's responsibility to
1029 // ensure that the referent is pointed to by a root.
1030 pub fn do_spill_noroot(cx: @mut Block, v: ValueRef) -> ValueRef {
1031 let llptr = alloca(cx, val_ty(v), "");
1032 Store(cx, v, llptr);
1036 pub fn spill_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1037 let _icx = push_ctxt("spill_if_immediate");
1038 if ty::type_is_immediate(cx.tcx(), t) { return do_spill(cx, v, t); }
1042 pub fn load_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1043 let _icx = push_ctxt("load_if_immediate");
1044 if ty::type_is_immediate(cx.tcx(), t) { return Load(cx, v); }
1048 pub fn trans_trace(bcx: @mut Block, sp_opt: Option<span>, trace_str: @str) {
1049 if !bcx.sess().trace() { return; }
1050 let _icx = push_ctxt("trans_trace");
1051 add_comment(bcx, trace_str);
1052 let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1053 let (V_filename, V_line) = match sp_opt {
1055 let sess = bcx.sess();
1056 let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1057 (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1060 (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1063 let ccx = bcx.ccx();
1064 let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1065 let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1066 let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1067 Call(bcx, ccx.upcalls.trace, args);
1070 pub fn ignore_lhs(_bcx: @mut Block, local: &ast::Local) -> bool {
1071 match local.pat.node {
1072 ast::pat_wild => true, _ => false
1076 pub fn init_local(bcx: @mut Block, local: &ast::Local) -> @mut Block {
1078 debug!("init_local(bcx=%s, local.id=%?)",
1079 bcx.to_str(), local.id);
1080 let _indenter = indenter();
1082 let _icx = push_ctxt("init_local");
1084 if ignore_lhs(bcx, local) {
1085 // Handle let _ = e; just like e;
1088 return expr::trans_into(bcx, init, expr::Ignore);
1090 None => { return bcx; }
1094 _match::store_local(bcx, local.pat, local.init)
1097 pub fn trans_stmt(cx: @mut Block, s: &ast::stmt) -> @mut Block {
1098 let _icx = push_ctxt("trans_stmt");
1099 debug!("trans_stmt(%s)", stmt_to_str(s, cx.tcx().sess.intr()));
1101 if cx.sess().asm_comments() {
1102 add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1106 debuginfo::update_source_pos(cx, s.span);
1109 ast::stmt_expr(e, _) | ast::stmt_semi(e, _) => {
1110 bcx = expr::trans_into(cx, e, expr::Ignore);
1112 ast::stmt_decl(d, _) => {
1114 ast::decl_local(ref local) => {
1115 bcx = init_local(bcx, *local);
1116 if cx.sess().opts.extra_debuginfo
1117 && fcx_has_nonzero_span(bcx.fcx) {
1118 debuginfo::create_local_var_metadata(bcx, *local);
1121 ast::decl_item(i) => trans_item(cx.fcx.ccx, i)
1124 ast::stmt_mac(*) => cx.tcx().sess.bug("unexpanded macro")
1130 // You probably don't want to use this one. See the
1131 // next three functions instead.
1132 pub fn new_block(cx: @mut FunctionContext,
1133 parent: Option<@mut Block>,
1134 scope: Option<@mut ScopeInfo>,
1137 opt_node_info: Option<NodeInfo>)
1140 let llbb = do name.to_c_str().with_ref |buf| {
1141 llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1143 let bcx = @mut Block::new(llbb,
1149 for cx in parent.iter() {
1159 pub fn simple_block_scope(parent: Option<@mut ScopeInfo>,
1160 node_info: Option<NodeInfo>) -> @mut ScopeInfo {
1168 node_info: node_info,
1172 // Use this when you're at the top block of a function or the like.
1173 pub fn top_scope_block(fcx: @mut FunctionContext, opt_node_info: Option<NodeInfo>)
1175 return new_block(fcx, None, Some(simple_block_scope(None, opt_node_info)), false,
1176 "function top level", opt_node_info);
1179 pub fn scope_block(bcx: @mut Block,
1180 opt_node_info: Option<NodeInfo>,
1181 n: &str) -> @mut Block {
1182 return new_block(bcx.fcx, Some(bcx), Some(simple_block_scope(None, opt_node_info)), bcx.is_lpad,
1186 pub fn loop_scope_block(bcx: @mut Block,
1187 loop_break: @mut Block,
1188 loop_label: Option<ident>,
1190 opt_node_info: Option<NodeInfo>) -> @mut Block {
1191 return new_block(bcx.fcx, Some(bcx), Some(@mut ScopeInfo {
1193 loop_break: Some(loop_break),
1194 loop_label: loop_label,
1198 node_info: opt_node_info,
1199 }), bcx.is_lpad, n, opt_node_info);
1202 // Use this when creating a block for the inside of a landing pad.
1203 pub fn lpad_block(bcx: @mut Block, n: &str) -> @mut Block {
1204 new_block(bcx.fcx, Some(bcx), None, true, n, None)
1207 // Use this when you're making a general CFG BB within a scope.
1208 pub fn sub_block(bcx: @mut Block, n: &str) -> @mut Block {
1209 new_block(bcx.fcx, Some(bcx), None, bcx.is_lpad, n, None)
1212 pub fn raw_block(fcx: @mut FunctionContext, is_lpad: bool, llbb: BasicBlockRef) -> @mut Block {
1213 @mut Block::new(llbb, None, is_lpad, None, fcx)
1217 // trans_block_cleanups: Go through all the cleanups attached to this
1218 // block and execute them.
1220 // When translating a block that introduces new variables during its scope, we
1221 // need to make sure those variables go out of scope when the block ends. We
1222 // do that by running a 'cleanup' function for each variable.
1223 // trans_block_cleanups runs all the cleanup functions for the block.
1224 pub fn trans_block_cleanups(bcx: @mut Block, cleanups: ~[cleanup]) -> @mut Block {
1225 trans_block_cleanups_(bcx, cleanups, false)
1228 pub fn trans_block_cleanups_(bcx: @mut Block,
1229 cleanups: &[cleanup],
1230 /* cleanup_cx: block, */
1231 is_lpad: bool) -> @mut Block {
1232 let _icx = push_ctxt("trans_block_cleanups");
1233 // NB: Don't short-circuit even if this block is unreachable because
1234 // GC-based cleanup needs to the see that the roots are live.
1236 bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1237 if bcx.unreachable && !no_lpads { return bcx; }
1239 for cu in cleanups.rev_iter() {
1241 clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1242 // Some types don't need to be cleaned up during
1243 // landing pads because they can be freed en mass later
1244 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1253 // In the last argument, Some(block) mean jump to this block, and none means
1254 // this is a landing pad and leaving should be accomplished with a resume
1256 pub fn cleanup_and_leave(bcx: @mut Block,
1257 upto: Option<BasicBlockRef>,
1258 leave: Option<BasicBlockRef>) {
1259 let _icx = push_ctxt("cleanup_and_leave");
1262 let is_lpad = leave == None;
1264 debug!("cleanup_and_leave: leaving %s", cur.to_str());
1266 if bcx.sess().trace() {
1269 (fmt!("cleanup_and_leave(%s)", cur.to_str())).to_managed());
1272 let mut cur_scope = cur.scope;
1274 cur_scope = match cur_scope {
1275 Some (inf) if !inf.empty_cleanups() => {
1276 let (sub_cx, dest, inf_cleanups) = {
1277 let inf = &mut *inf;
1279 let mut dest = None;
1281 let r = (*inf).cleanup_paths.rev_iter().find(|cp| cp.target == leave);
1282 for cp in r.iter() {
1283 if cp.size == inf.cleanups.len() {
1289 dest = Some(cp.dest);
1292 let sub_cx = sub_block(bcx, "cleanup");
1293 Br(bcx, sub_cx.llbb);
1294 inf.cleanup_paths.push(cleanup_path {
1296 size: inf.cleanups.len(),
1299 (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1301 bcx = trans_block_cleanups_(sub_cx,
1304 for &dest in dest.iter() {
1310 Some(inf) => inf.parent,
1316 Some(bb) => { if cur.llbb == bb { break; } }
1319 cur = match cur.parent {
1321 None => { assert!(upto.is_none()); break; }
1325 Some(target) => Br(bcx, target),
1326 None => { Resume(bcx, Load(bcx, bcx.fcx.personality.unwrap())); }
1330 pub fn cleanup_block(bcx: @mut Block, upto: Option<BasicBlockRef>) -> @mut Block{
1331 let _icx = push_ctxt("cleanup_block");
1335 debug!("cleanup_block: %s", cur.to_str());
1337 if bcx.sess().trace() {
1340 (fmt!("cleanup_block(%s)", cur.to_str())).to_managed());
1343 let mut cur_scope = cur.scope;
1345 cur_scope = match cur_scope {
1347 bcx = trans_block_cleanups_(bcx, inf.cleanups.to_owned(), false);
1355 Some(bb) => { if cur.llbb == bb { break; } }
1358 cur = match cur.parent {
1360 None => { assert!(upto.is_none()); break; }
1366 pub fn cleanup_and_Br(bcx: @mut Block, upto: @mut Block, target: BasicBlockRef) {
1367 let _icx = push_ctxt("cleanup_and_Br");
1368 cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1371 pub fn leave_block(bcx: @mut Block, out_of: @mut Block) -> @mut Block {
1372 let _icx = push_ctxt("leave_block");
1373 let next_cx = sub_block(block_parent(out_of), "next");
1374 if bcx.unreachable { Unreachable(next_cx); }
1375 cleanup_and_Br(bcx, out_of, next_cx.llbb);
1379 pub fn with_scope(bcx: @mut Block,
1380 opt_node_info: Option<NodeInfo>,
1382 f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1383 let _icx = push_ctxt("with_scope");
1385 debug!("with_scope(bcx=%s, opt_node_info=%?, name=%s)",
1386 bcx.to_str(), opt_node_info, name);
1387 let _indenter = indenter();
1389 let scope = simple_block_scope(bcx.scope, opt_node_info);
1390 bcx.scope = Some(scope);
1392 let ret = trans_block_cleanups_(ret, (scope.cleanups).clone(), false);
1393 bcx.scope = scope.parent;
1397 pub fn with_scope_result(bcx: @mut Block,
1398 opt_node_info: Option<NodeInfo>,
1400 f: &fn(@mut Block) -> Result) -> Result {
1401 let _icx = push_ctxt("with_scope_result");
1403 let scope = simple_block_scope(bcx.scope, opt_node_info);
1404 bcx.scope = Some(scope);
1405 let Result { bcx: out_bcx, val } = f(bcx);
1406 let out_bcx = trans_block_cleanups_(out_bcx,
1407 (scope.cleanups).clone(),
1409 bcx.scope = scope.parent;
1414 pub fn with_scope_datumblock(bcx: @mut Block, opt_node_info: Option<NodeInfo>,
1415 name: &str, f: &fn(@mut Block) -> datum::DatumBlock)
1416 -> datum::DatumBlock {
1417 use middle::trans::datum::DatumBlock;
1419 let _icx = push_ctxt("with_scope_result");
1420 let scope_cx = scope_block(bcx, opt_node_info, name);
1421 Br(bcx, scope_cx.llbb);
1422 let DatumBlock {bcx, datum} = f(scope_cx);
1423 DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1426 pub fn block_locals(b: &ast::Block, it: &fn(@ast::Local)) {
1427 for s in b.stmts.iter() {
1429 ast::stmt_decl(d, _) => {
1431 ast::decl_local(ref local) => it(*local),
1432 _ => {} /* fall through */
1435 _ => {} /* fall through */
1440 pub fn with_cond(bcx: @mut Block, val: ValueRef, f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1441 let _icx = push_ctxt("with_cond");
1442 let next_cx = base::sub_block(bcx, "next");
1443 let cond_cx = base::sub_block(bcx, "cond");
1444 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1445 let after_cx = f(cond_cx);
1446 if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1450 pub fn call_memcpy(cx: @mut Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1451 let _icx = push_ctxt("call_memcpy");
1453 let key = match ccx.sess.targ_cfg.arch {
1454 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1455 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1457 let memcpy = ccx.intrinsics.get_copy(&key);
1458 let src_ptr = PointerCast(cx, src, Type::i8p());
1459 let dst_ptr = PointerCast(cx, dst, Type::i8p());
1460 let size = IntCast(cx, n_bytes, ccx.int_type);
1461 let align = C_i32(align as i32);
1462 let volatile = C_i1(false);
1463 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile]);
1466 pub fn memcpy_ty(bcx: @mut Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1467 let _icx = push_ctxt("memcpy_ty");
1468 let ccx = bcx.ccx();
1469 if ty::type_is_structural(t) {
1470 let llty = type_of::type_of(ccx, t);
1471 let llsz = llsize_of(ccx, llty);
1472 let llalign = llalign_of_min(ccx, llty);
1473 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1475 Store(bcx, Load(bcx, src), dst);
1479 pub fn zero_mem(cx: @mut Block, llptr: ValueRef, t: ty::t) {
1480 if cx.unreachable { return; }
1481 let _icx = push_ctxt("zero_mem");
1484 let llty = type_of::type_of(ccx, t);
1485 memzero(&B(bcx), llptr, llty);
1488 // Always use this function instead of storing a zero constant to the memory
1489 // in question. If you store a zero constant, LLVM will drown in vreg
1490 // allocation for large data structures, and the generated code will be
1491 // awful. (A telltale sign of this is large quantities of
1492 // `mov [byte ptr foo],0` in the generated code.)
1493 pub fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1494 let _icx = push_ctxt("memzero");
1497 let intrinsic_key = match ccx.sess.targ_cfg.arch {
1498 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1499 X86_64 => "llvm.memset.p0i8.i64"
1502 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1503 let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1504 let llzeroval = C_u8(0);
1505 let size = machine::llsize_of(ccx, ty);
1506 let align = C_i32(llalign_of_min(ccx, ty) as i32);
1507 let volatile = C_i1(false);
1508 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile]);
1511 pub fn alloc_ty(bcx: @mut Block, t: ty::t, name: &str) -> ValueRef {
1512 let _icx = push_ctxt("alloc_ty");
1513 let ccx = bcx.ccx();
1514 let ty = type_of::type_of(ccx, t);
1515 assert!(!ty::type_has_params(t), "Type has params: %s", ty_to_str(ccx.tcx, t));
1516 let val = alloca(bcx, ty, name);
1520 pub fn alloca(cx: @mut Block, ty: Type, name: &str) -> ValueRef {
1521 alloca_maybe_zeroed(cx, ty, name, false)
1524 pub fn alloca_maybe_zeroed(cx: @mut Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1525 let _icx = push_ctxt("alloca");
1528 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1531 let p = Alloca(cx, ty, name);
1533 let b = cx.fcx.ccx.builder();
1534 b.position_before(cx.fcx.alloca_insert_pt.unwrap());
1540 pub fn arrayalloca(cx: @mut Block, ty: Type, v: ValueRef) -> ValueRef {
1541 let _icx = push_ctxt("arrayalloca");
1544 return llvm::LLVMGetUndef(ty.to_ref());
1547 return ArrayAlloca(cx, ty, v);
1550 pub struct BasicBlocks {
1554 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1556 let cx = task_llcx();
1557 do "static_allocas".to_c_str().with_ref | buf| {
1558 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1563 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1565 let cx = task_llcx();
1566 do "return".to_c_str().with_ref |buf| {
1567 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1572 // Creates and returns space for, or returns the argument representing, the
1573 // slot where the return value of the function must go.
1574 pub fn make_return_pointer(fcx: @mut FunctionContext, output_type: ty::t) -> ValueRef {
1576 if !ty::type_is_immediate(fcx.ccx.tcx, output_type) {
1577 llvm::LLVMGetParam(fcx.llfn, 0)
1579 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1580 let bcx = fcx.entry_bcx.unwrap();
1581 Alloca(bcx, lloutputtype, "__make_return_pointer")
1586 // NB: must keep 4 fns in sync:
1589 // - create_llargs_for_fn_args.
1592 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1598 param_substs: Option<@param_substs>,
1599 opt_node_info: Option<NodeInfo>,
1601 -> @mut FunctionContext {
1602 for p in param_substs.iter() { p.validate(); }
1604 debug!("new_fn_ctxt_w_id(path=%s, id=%?, \
1606 path_str(ccx.sess, path),
1608 param_substs.repr(ccx.tcx));
1610 let substd_output_type = match param_substs {
1611 None => output_type,
1613 ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1616 let is_immediate = ty::type_is_immediate(ccx.tcx, substd_output_type);
1617 let fcx = @mut FunctionContext {
1620 llvm::LLVMGetUndef(Type::i8p().to_ref())
1624 alloca_insert_pt: None,
1629 has_immediate_return_value: is_immediate,
1630 llargs: @mut HashMap::new(),
1631 lllocals: @mut HashMap::new(),
1632 llupvars: @mut HashMap::new(),
1634 param_substs: param_substs,
1639 fcx.llenv = unsafe {
1640 llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1644 let entry_bcx = top_scope_block(fcx, opt_node_info);
1645 Load(entry_bcx, C_null(Type::i8p()));
1647 fcx.entry_bcx = Some(entry_bcx);
1648 fcx.alloca_insert_pt = Some(llvm::LLVMGetFirstInstruction(entry_bcx.llbb));
1651 if !ty::type_is_nil(substd_output_type) && !(is_immediate && skip_retptr) {
1652 fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1657 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1662 -> @mut FunctionContext {
1663 new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, false, None, None, sp)
1666 // NB: must keep 4 fns in sync:
1669 // - create_llargs_for_fn_args.
1673 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1674 // allocas created for them.
1676 // When we translate a function, we need to map its incoming arguments to the
1677 // spaces that have been created for them (by code in the llallocas field of
1678 // the function's fn_ctxt). create_llargs_for_fn_args populates the llargs
1679 // field of the fn_ctxt with
1680 pub fn create_llargs_for_fn_args(cx: @mut FunctionContext,
1684 let _icx = push_ctxt("create_llargs_for_fn_args");
1687 impl_self(tt, self_mode) => {
1688 cx.llself = Some(ValSelfData {
1691 is_copy: self_mode == ty::ByCopy
1697 // Return an array containing the ValueRefs that we get from
1698 // llvm::LLVMGetParam for each argument.
1699 vec::from_fn(args.len(), |i| {
1701 let arg_n = cx.arg_pos(i);
1703 let llarg = llvm::LLVMGetParam(cx.llfn, arg_n as c_uint);
1705 // FIXME #7260: aliasing should be determined by monomorphized ty::t
1707 // `~` pointers never alias other parameters, because ownership was transferred
1708 ast::ty_uniq(_) => {
1709 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
1711 // FIXME: #6785: `&mut` can only alias `&const` and `@mut`, we should check for
1712 // those in the other parameters and then mark it as `noalias` if there aren't any
1721 pub fn copy_args_to_allocas(fcx: @mut FunctionContext,
1724 raw_llargs: &[ValueRef],
1725 arg_tys: &[ty::t]) -> @mut Block {
1726 let _icx = push_ctxt("copy_args_to_allocas");
1731 let self_val = if slf.is_copy
1732 && datum::appropriate_mode(bcx.tcx(), slf.t).is_by_value() {
1733 let tmp = BitCast(bcx, slf.v, type_of(bcx.ccx(), slf.t));
1734 let alloc = alloc_ty(bcx, slf.t, "__self");
1735 Store(bcx, tmp, alloc);
1738 PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to())
1741 fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1742 add_clean(bcx, self_val, slf.t);
1747 for (arg_n, &arg_ty) in arg_tys.iter().enumerate() {
1748 let raw_llarg = raw_llargs[arg_n];
1750 // For certain mode/type combinations, the raw llarg values are passed
1751 // by value. However, within the fn body itself, we want to always
1752 // have all locals and arguments be by-ref so that we can cancel the
1753 // cleanup and for better interaction with LLVM's debug info. So, if
1754 // the argument would be passed by value, we store it into an alloca.
1755 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1756 // the event it's not truly needed.
1757 // only by value if immediate:
1758 let llarg = if datum::appropriate_mode(bcx.tcx(), arg_ty).is_by_value() {
1759 let alloc = alloc_ty(bcx, arg_ty, "__arg");
1760 Store(bcx, raw_llarg, alloc);
1765 bcx = _match::store_arg(bcx, args[arg_n].pat, llarg);
1767 if fcx.ccx.sess.opts.extra_debuginfo && fcx_has_nonzero_span(fcx) {
1768 debuginfo::create_argument_metadata(bcx, &args[arg_n]);
1775 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1776 // and builds the return block.
1777 pub fn finish_fn(fcx: @mut FunctionContext, last_bcx: @mut Block) {
1778 let _icx = push_ctxt("finish_fn");
1780 let ret_cx = match fcx.llreturn {
1782 if !last_bcx.terminated {
1783 Br(last_bcx, llreturn);
1785 raw_block(fcx, false, llreturn)
1789 build_return_block(fcx, ret_cx);
1793 // Builds the return block for a function.
1794 pub fn build_return_block(fcx: &FunctionContext, ret_cx: @mut Block) {
1795 // Return the value if this function immediate; otherwise, return void.
1796 if fcx.llretptr.is_none() || !fcx.has_immediate_return_value {
1797 return RetVoid(ret_cx);
1800 let retptr = Value(fcx.llretptr.unwrap());
1801 let retval = match retptr.get_dominating_store(ret_cx) {
1802 // If there's only a single store to the ret slot, we can directly return
1803 // the value that was stored and omit the store and the alloca
1805 let retval = *s.get_operand(0).unwrap();
1806 s.erase_from_parent();
1808 if retptr.has_no_uses() {
1809 retptr.erase_from_parent();
1814 // Otherwise, load the return value from the ret slot
1815 None => Load(ret_cx, fcx.llretptr.unwrap())
1819 Ret(ret_cx, retval);
1822 pub enum self_arg { impl_self(ty::t, ty::SelfMode), no_self, }
1824 // trans_closure: Builds an LLVM function out of a source function.
1825 // If the function closes over its environment a closure will be
1827 pub fn trans_closure(ccx: @mut CrateContext,
1829 decl: &ast::fn_decl,
1833 param_substs: Option<@param_substs>,
1835 attributes: &[ast::Attribute],
1837 maybe_load_env: &fn(@mut FunctionContext),
1838 finish: &fn(@mut Block)) {
1839 ccx.stats.n_closures += 1;
1840 let _icx = push_ctxt("trans_closure");
1841 set_uwtable(llfndecl);
1843 debug!("trans_closure(..., param_substs=%s)",
1844 param_substs.repr(ccx.tcx));
1846 // Set up arguments to the function.
1847 let fcx = new_fn_ctxt_w_id(ccx,
1856 let raw_llargs = create_llargs_for_fn_args(fcx, self_arg, decl.inputs);
1858 // Set the fixed stack segment flag if necessary.
1859 if attr::contains_name(attributes, "fixed_stack_segment") {
1860 set_no_inline(fcx.llfn);
1861 set_fixed_stack_segment(fcx.llfn);
1864 // Create the first basic block in the function and keep a handle on it to
1865 // pass to finish_fn later.
1866 let bcx_top = fcx.entry_bcx.unwrap();
1867 let mut bcx = bcx_top;
1868 let block_ty = node_id_type(bcx, body.id);
1870 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1871 bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1873 maybe_load_env(fcx);
1875 // This call to trans_block is the place where we bridge between
1876 // translation calls that don't have a return value (trans_crate,
1877 // trans_mod, trans_item, et cetera) and those that do
1878 // (trans_block, trans_expr, et cetera).
1879 if body.expr.is_none() || ty::type_is_bot(block_ty) ||
1880 ty::type_is_nil(block_ty)
1882 bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1884 let dest = expr::SaveIn(fcx.llretptr.unwrap());
1885 bcx = controlflow::trans_block(bcx, body, dest);
1889 match fcx.llreturn {
1890 Some(llreturn) => cleanup_and_Br(bcx, bcx_top, llreturn),
1891 None => bcx = cleanup_block(bcx, Some(bcx_top.llbb))
1894 // Put return block after all other blocks.
1895 // This somewhat improves single-stepping experience in debugger.
1897 for &llreturn in fcx.llreturn.iter() {
1898 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1902 // Insert the mandatory first few basic blocks before lltop.
1903 finish_fn(fcx, bcx);
1906 // trans_fn: creates an LLVM function corresponding to a source language
1908 pub fn trans_fn(ccx: @mut CrateContext,
1910 decl: &ast::fn_decl,
1914 param_substs: Option<@param_substs>,
1916 attrs: &[ast::Attribute]) {
1918 let the_path_str = path_str(ccx.sess, path);
1919 let _s = StatRecorder::new(ccx, the_path_str);
1920 debug!("trans_fn(self_arg=%?, param_substs=%s)",
1922 param_substs.repr(ccx.tcx));
1923 let _icx = push_ctxt("trans_fn");
1924 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1936 if ccx.sess.opts.extra_debuginfo
1937 && fcx_has_nonzero_span(fcx) {
1938 debuginfo::create_function_metadata(fcx);
1944 fn insert_synthetic_type_entries(bcx: @mut Block,
1945 fn_args: &[ast::arg],
1949 * For tuple-like structs and enum-variants, we generate
1950 * synthetic AST nodes for the arguments. These have no types
1951 * in the type table and no entries in the moves table,
1952 * so the code in `copy_args_to_allocas` and `bind_irrefutable_pat`
1953 * gets upset. This hack of a function bridges the gap by inserting types.
1955 * This feels horrible. I think we should just have a special path
1956 * for these functions and not try to use the generic code, but
1957 * that's not the problem I'm trying to solve right now. - nmatsakis
1960 let tcx = bcx.tcx();
1961 for i in range(0u, fn_args.len()) {
1962 debug!("setting type of argument %u (pat node %d) to %s",
1963 i, fn_args[i].pat.id, bcx.ty_to_str(arg_tys[i]));
1965 let pat_id = fn_args[i].pat.id;
1966 let arg_ty = arg_tys[i];
1967 tcx.node_types.insert(pat_id as uint, arg_ty);
1971 pub fn trans_enum_variant(ccx: @mut CrateContext,
1972 _enum_id: ast::NodeId,
1973 variant: &ast::variant,
1974 args: &[ast::variant_arg],
1976 param_substs: Option<@param_substs>,
1977 llfndecl: ValueRef) {
1978 let _icx = push_ctxt("trans_enum_variant");
1980 trans_enum_variant_or_tuple_like_struct(
1989 pub fn trans_tuple_struct(ccx: @mut CrateContext,
1990 fields: &[@ast::struct_field],
1991 ctor_id: ast::NodeId,
1992 param_substs: Option<@param_substs>,
1993 llfndecl: ValueRef) {
1994 let _icx = push_ctxt("trans_tuple_struct");
1996 trans_enum_variant_or_tuple_like_struct(
2006 fn id(&self) -> ast::NodeId;
2007 fn ty<'a>(&'a self) -> &'a ast::Ty;
2010 impl IdAndTy for ast::variant_arg {
2011 fn id(&self) -> ast::NodeId { self.id }
2012 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.ty }
2015 impl IdAndTy for @ast::struct_field {
2016 fn id(&self) -> ast::NodeId { self.node.id }
2017 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.node.ty }
2020 pub fn trans_enum_variant_or_tuple_like_struct<A:IdAndTy>(
2021 ccx: @mut CrateContext,
2022 ctor_id: ast::NodeId,
2025 param_substs: Option<@param_substs>,
2028 // Translate variant arguments to function arguments.
2029 let fn_args = do args.map |varg| {
2032 ty: (*varg.ty()).clone(),
2033 pat: ast_util::ident_to_pat(
2034 ccx.tcx.sess.next_node_id(),
2035 codemap::dummy_sp(),
2036 special_idents::arg),
2041 let no_substs: &[ty::t] = [];
2042 let ty_param_substs = match param_substs {
2043 Some(ref substs) => {
2044 let v: &[ty::t] = substs.tys;
2048 let v: &[ty::t] = no_substs;
2053 let ctor_ty = ty::subst_tps(ccx.tcx,
2056 ty::node_id_to_type(ccx.tcx, ctor_id));
2058 let result_ty = match ty::get(ctor_ty).sty {
2059 ty::ty_bare_fn(ref bft) => bft.sig.output,
2061 fmt!("trans_enum_variant_or_tuple_like_struct: \
2062 unexpected ctor return type %s",
2063 ty_to_str(ccx.tcx, ctor_ty)))
2066 let fcx = new_fn_ctxt_w_id(ccx,
2076 let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
2078 let bcx = fcx.entry_bcx.unwrap();
2079 let arg_tys = ty::ty_fn_args(ctor_ty);
2081 insert_synthetic_type_entries(bcx, fn_args, arg_tys);
2082 let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2084 let repr = adt::represent_type(ccx, result_ty);
2085 adt::trans_start_init(bcx, repr, fcx.llretptr.unwrap(), disr);
2086 for (i, fn_arg) in fn_args.iter().enumerate() {
2087 let lldestptr = adt::trans_field_ptr(bcx,
2089 fcx.llretptr.unwrap(),
2092 let llarg = fcx.llargs.get_copy(&fn_arg.pat.id);
2093 let arg_ty = arg_tys[i];
2094 memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2096 finish_fn(fcx, bcx);
2099 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2100 id: ast::NodeId, vi: @~[@ty::VariantInfo],
2102 for variant in enum_definition.variants.iter() {
2103 let disr_val = vi[*i].disr_val;
2106 match variant.node.kind {
2107 ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2108 let llfn = get_item_val(ccx, variant.node.id);
2109 trans_enum_variant(ccx, id, variant, *args,
2110 disr_val, None, llfn);
2112 ast::tuple_variant_kind(_) => {
2115 ast::struct_variant_kind(struct_def) => {
2116 trans_struct_def(ccx, struct_def);
2122 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2123 let _icx = push_ctxt("trans_item");
2124 let path = match ccx.tcx.items.get_copy(&item.id) {
2125 ast_map::node_item(_, p) => p,
2127 _ => fail!("trans_item"),
2130 ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2131 if purity == ast::extern_fn {
2132 let llfndecl = get_item_val(ccx, item.id);
2133 foreign::trans_foreign_fn(ccx,
2134 vec::append((*path).clone(),
2135 [path_name(item.ident)]),
2140 } else if !generics.is_type_parameterized() {
2141 let llfndecl = get_item_val(ccx, item.id);
2143 vec::append((*path).clone(), [path_name(item.ident)]),
2152 for stmt in body.stmts.iter() {
2154 ast::stmt_decl(@codemap::spanned { node: ast::decl_item(i),
2163 ast::item_impl(ref generics, _, _, ref ms) => {
2164 meth::trans_impl(ccx,
2171 ast::item_mod(ref m) => {
2174 ast::item_enum(ref enum_definition, ref generics) => {
2175 if !generics.is_type_parameterized() {
2176 let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2178 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2181 ast::item_static(_, m, expr) => {
2182 consts::trans_const(ccx, m, item.id);
2183 // Do static_assert checking. It can't really be done much earlier
2184 // because we need to get the value of the bool out of LLVM
2185 if attr::contains_name(item.attrs, "static_assert") {
2186 if m == ast::m_mutbl {
2187 ccx.sess.span_fatal(expr.span,
2188 "cannot have static_assert on a mutable \
2191 let v = ccx.const_values.get_copy(&item.id);
2193 if !(llvm::LLVMConstIntGetZExtValue(v) as bool) {
2194 ccx.sess.span_fatal(expr.span, "static assertion failed");
2199 ast::item_foreign_mod(ref foreign_mod) => {
2200 foreign::trans_foreign_mod(ccx, path, foreign_mod);
2202 ast::item_struct(struct_def, ref generics) => {
2203 if !generics.is_type_parameterized() {
2204 trans_struct_def(ccx, struct_def);
2207 _ => {/* fall through */ }
2211 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2212 // If this is a tuple-like struct, translate the constructor.
2213 match struct_def.ctor_id {
2214 // We only need to translate a constructor if there are fields;
2215 // otherwise this is a unit-like struct.
2216 Some(ctor_id) if struct_def.fields.len() > 0 => {
2217 let llfndecl = get_item_val(ccx, ctor_id);
2218 trans_tuple_struct(ccx, struct_def.fields,
2219 ctor_id, None, llfndecl);
2221 Some(_) | None => {}
2225 // Translate a module. Doing this amounts to translating the items in the
2226 // module; there ends up being no artifact (aside from linkage names) of
2227 // separate modules in the compiled program. That's because modules exist
2228 // only as a convenience for humans working with the code, to organize names
2229 // and control visibility.
2230 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2231 let _icx = push_ctxt("trans_mod");
2232 for item in m.items.iter() {
2233 trans_item(ccx, *item);
2237 pub fn register_fn(ccx: @mut CrateContext,
2240 node_id: ast::NodeId,
2243 let llfty = type_of_fn_from_ty(ccx, node_type);
2244 register_fn_llvmty(ccx, sp, sym, node_id, lib::llvm::CCallConv, llfty)
2247 pub fn register_fn_llvmty(ccx: @mut CrateContext,
2250 node_id: ast::NodeId,
2251 cc: lib::llvm::CallConv,
2254 debug!("register_fn_fuller creating fn for item %d with path %s",
2256 ast_map::path_to_str(item_path(ccx, &node_id), token::get_ident_interner()));
2258 let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty);
2259 ccx.item_symbols.insert(node_id, sym);
2261 // FIXME #4404 android JNI hacks
2262 let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2263 (*ccx.sess.building_library &&
2264 ccx.sess.targ_cfg.os == session::os_android));
2266 create_entry_wrapper(ccx, sp, llfn);
2271 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2272 match *sess.entry_fn {
2273 Some((entry_id, _)) => node_id == entry_id,
2278 // Create a _rust_main(args: ~[str]) function which will be called from the
2279 // runtime rust_start function
2280 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2282 main_llfn: ValueRef) {
2283 let et = ccx.sess.entry_type.unwrap();
2285 session::EntryMain => {
2286 let llfn = create_main(ccx, main_llfn);
2287 create_entry_fn(ccx, llfn, true);
2289 session::EntryStart => create_entry_fn(ccx, main_llfn, false),
2290 session::EntryNone => {} // Do nothing.
2293 fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
2294 let nt = ty::mk_nil();
2296 let llfty = type_of_fn(ccx, [], nt);
2297 let llfdecl = decl_fn(ccx.llmod, "_rust_main",
2298 lib::llvm::CCallConv, llfty);
2300 let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None);
2302 // the args vector built in create_entry_fn will need
2303 // be updated if this assertion starts to fail.
2304 assert!(fcx.has_immediate_return_value);
2306 let bcx = fcx.entry_bcx.unwrap();
2308 let llenvarg = unsafe {
2309 let env_arg = fcx.env_arg_pos();
2310 llvm::LLVMGetParam(llfdecl, env_arg as c_uint)
2312 let args = ~[llenvarg];
2313 Call(bcx, main_llfn, args);
2315 finish_fn(fcx, bcx);
2319 fn create_entry_fn(ccx: @mut CrateContext,
2320 rust_main: ValueRef,
2321 use_start_lang_item: bool) {
2322 let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
2325 // FIXME #4404 android JNI hacks
2326 let llfn = if *ccx.sess.building_library {
2327 decl_cdecl_fn(ccx.llmod, "amain", llfty)
2329 let main_name = match ccx.sess.targ_cfg.os {
2330 session::os_win32 => ~"WinMain@16",
2333 decl_cdecl_fn(ccx.llmod, main_name, llfty)
2335 let llbb = do "top".to_c_str().with_ref |buf| {
2337 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2340 let bld = ccx.builder.B;
2342 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2344 let crate_map = ccx.crate_map;
2345 let opaque_crate_map = do "crate_map".to_c_str().with_ref |buf| {
2346 llvm::LLVMBuildPointerCast(bld, crate_map, Type::i8p().to_ref(), buf)
2349 let (start_fn, args) = if use_start_lang_item {
2350 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2352 Err(s) => { ccx.tcx.sess.fatal(s); }
2354 let start_fn = if start_def_id.crate == ast::LOCAL_CRATE {
2355 get_item_val(ccx, start_def_id.node)
2357 let start_fn_type = csearch::get_type(ccx.tcx,
2359 trans_external_path(ccx, start_def_id, start_fn_type)
2363 let opaque_rust_main = do "rust_main".to_c_str().with_ref |buf| {
2364 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2368 C_null(Type::opaque_box(ccx).ptr_to()),
2370 llvm::LLVMGetParam(llfn, 0),
2371 llvm::LLVMGetParam(llfn, 1),
2377 debug!("using user-defined start fn");
2379 C_null(Type::opaque_box(ccx).ptr_to()),
2380 llvm::LLVMGetParam(llfn, 0 as c_uint),
2381 llvm::LLVMGetParam(llfn, 1 as c_uint),
2388 let result = do args.as_imm_buf |buf, len| {
2389 llvm::LLVMBuildCall(bld, start_fn, buf, len as c_uint, noname())
2392 llvm::LLVMBuildRet(bld, result);
2397 pub fn fill_fn_pair(bcx: @mut Block, pair: ValueRef, llfn: ValueRef,
2398 llenvptr: ValueRef) {
2399 let ccx = bcx.ccx();
2400 let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2401 Store(bcx, llfn, code_cell);
2402 let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2403 let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2404 Store(bcx, llenvblobptr, env_cell);
2407 pub fn item_path(ccx: &CrateContext, id: &ast::NodeId) -> path {
2408 match ccx.tcx.items.get_copy(id) {
2409 ast_map::node_item(i, p) =>
2410 vec::append((*p).clone(), [path_name(i.ident)]),
2411 // separate map for paths?
2412 _ => fail!("item_path")
2416 fn exported_name(ccx: @mut CrateContext, path: path, ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
2417 if attr::contains_name(attrs, "no_mangle") {
2418 path_elt_to_str(*path.last(), token::get_ident_interner())
2420 mangle_exported_name(ccx, path, ty)
2424 pub fn get_item_val(ccx: @mut CrateContext, id: ast::NodeId) -> ValueRef {
2425 debug!("get_item_val(id=`%?`)", id);
2427 let val = ccx.item_vals.find_copy(&id);
2431 let mut exprt = false;
2432 let item = ccx.tcx.items.get_copy(&id);
2433 let val = match item {
2434 ast_map::node_item(i, pth) => {
2436 let my_path = vec::append((*pth).clone(), [path_name(i.ident)]);
2437 let ty = ty::node_id_to_type(ccx.tcx, i.id);
2438 let sym = exported_name(ccx, my_path, ty, i.attrs);
2440 let v = match i.node {
2441 ast::item_static(_, m, expr) => {
2442 // We need the translated value here, because for enums the
2443 // LLVM type is not fully determined by the Rust type.
2444 let v = consts::const_expr(ccx, expr);
2445 ccx.const_values.insert(id, v);
2446 exprt = (m == ast::m_mutbl || i.vis == ast::public);
2449 let llty = llvm::LLVMTypeOf(v);
2450 let g = do sym.to_c_str().with_ref |buf| {
2451 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2454 // Apply the `unnamed_addr` attribute if
2456 if attr::contains_name(i.attrs,
2457 "address_insignificant"){
2458 lib::llvm::SetUnnamedAddr(g, true);
2459 lib::llvm::SetLinkage(g,
2460 lib::llvm::InternalLinkage);
2463 ccx.item_symbols.insert(i.id, sym);
2468 ast::item_fn(_, purity, _, _, _) => {
2469 let llfn = if purity != ast::extern_fn {
2470 register_fn(ccx, i.span, sym, i.id, ty)
2472 foreign::register_foreign_fn(ccx, i.span, sym, i.id)
2474 set_inline_hint_if_appr(i.attrs, llfn);
2478 _ => fail!("get_item_val: weird result in table")
2481 match (attr::first_attr_value_str_by_name(i.attrs, "link_section")) {
2482 Some(sect) => unsafe {
2483 do sect.to_c_str().with_ref |buf| {
2484 llvm::LLVMSetSection(v, buf);
2493 ast_map::node_trait_method(trait_method, _, pth) => {
2494 debug!("get_item_val(): processing a node_trait_method");
2495 match *trait_method {
2496 ast::required(_) => {
2497 ccx.sess.bug("unexpected variant: required trait method in \
2500 ast::provided(m) => {
2502 register_method(ccx, id, pth, m)
2507 ast_map::node_method(m, _, pth) => {
2508 register_method(ccx, id, pth, m)
2511 ast_map::node_foreign_item(ni, _, _, pth) => {
2512 let ty = ty::node_id_to_type(ccx.tcx, ni.id);
2516 ast::foreign_item_fn(*) => {
2517 let path = vec::append((*pth).clone(), [path_name(ni.ident)]);
2518 let sym = exported_name(ccx, path, ty, ni.attrs);
2520 register_fn(ccx, ni.span, sym, ni.id, ty)
2522 ast::foreign_item_static(*) => {
2523 let ident = token::ident_to_str(&ni.ident);
2524 let g = do ident.to_c_str().with_ref |buf| {
2526 let ty = type_of(ccx, ty);
2527 llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf)
2535 ast_map::node_variant(ref v, enm, pth) => {
2538 ast::tuple_variant_kind(ref args) => {
2539 assert!(args.len() != 0u);
2540 let pth = vec::append((*pth).clone(),
2541 [path_name(enm.ident),
2542 path_name((*v).node.name)]);
2543 let ty = ty::node_id_to_type(ccx.tcx, id);
2544 let sym = exported_name(ccx, pth, ty, enm.attrs);
2546 llfn = match enm.node {
2547 ast::item_enum(_, _) => {
2548 register_fn(ccx, (*v).span, sym, id, ty)
2550 _ => fail!("node_variant, shouldn't happen")
2553 ast::struct_variant_kind(_) => {
2554 fail!("struct variant kind unexpected in get_item_val")
2557 set_inline_hint(llfn);
2561 ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2562 // Only register the constructor if this is a tuple-like struct.
2563 match struct_def.ctor_id {
2565 ccx.tcx.sess.bug("attempt to register a constructor of \
2566 a non-tuple-like struct")
2569 let ty = ty::node_id_to_type(ccx.tcx, ctor_id);
2570 let sym = exported_name(ccx, (*struct_path).clone(), ty,
2572 let llfn = register_fn(ccx, struct_item.span,
2574 set_inline_hint(llfn);
2581 ccx.sess.bug(fmt!("get_item_val(): unexpected variant: %?",
2586 if !exprt && !ccx.reachable.contains(&id) {
2587 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2590 ccx.item_vals.insert(id, val);
2596 pub fn register_method(ccx: @mut CrateContext,
2598 path: @ast_map::path,
2599 m: @ast::method) -> ValueRef {
2600 let mty = ty::node_id_to_type(ccx.tcx, id);
2602 let mut path = (*path).clone();
2603 path.push(path_name(gensym_name("meth")));
2604 path.push(path_name(m.ident));
2606 let sym = exported_name(ccx, path, mty, m.attrs);
2608 let llfn = register_fn(ccx, m.span, sym, id, mty);
2609 set_inline_hint_if_appr(m.attrs, llfn);
2613 // The constant translation pass.
2614 pub fn trans_constant(ccx: &mut CrateContext, it: @ast::item) {
2615 let _icx = push_ctxt("trans_constant");
2617 ast::item_enum(ref enum_definition, _) => {
2618 let vi = ty::enum_variants(ccx.tcx,
2619 ast::def_id { crate: ast::LOCAL_CRATE,
2622 let path = item_path(ccx, &it.id);
2623 for variant in (*enum_definition).variants.iter() {
2624 let p = vec::append(path.clone(), [
2625 path_name(variant.node.name),
2626 path_name(special_idents::descrim)
2628 let s = mangle_exported_name(ccx, p, ty::mk_int()).to_managed();
2629 let disr_val = vi[i].disr_val;
2630 note_unique_llvm_symbol(ccx, s);
2631 let discrim_gvar = do s.to_c_str().with_ref |buf| {
2633 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2637 llvm::LLVMSetInitializer(discrim_gvar, C_uint(ccx, disr_val));
2638 llvm::LLVMSetGlobalConstant(discrim_gvar, True);
2640 ccx.discrims.insert(
2641 local_def(variant.node.id), discrim_gvar);
2642 ccx.discrim_symbols.insert(variant.node.id, s);
2650 pub fn trans_constants(ccx: @mut CrateContext, crate: &ast::Crate) {
2651 oldvisit::visit_crate(
2653 oldvisit::mk_simple_visitor(@oldvisit::SimpleVisitor {
2654 visit_item: |a| trans_constant(ccx, a),
2655 ..*oldvisit::default_simple_visitor()
2659 pub fn vp2i(cx: @mut Block, v: ValueRef) -> ValueRef {
2661 return PtrToInt(cx, v, ccx.int_type);
2664 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2666 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2671 ($name:expr, $args:expr, $ret:expr) => ({
2673 let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2674 intrinsics.insert(name, f);
2678 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2679 let i8p = Type::i8p();
2680 let mut intrinsics = HashMap::new();
2682 ifn!("llvm.memcpy.p0i8.p0i8.i32",
2683 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2684 ifn!("llvm.memcpy.p0i8.p0i8.i64",
2685 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2686 ifn!("llvm.memmove.p0i8.p0i8.i32",
2687 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2688 ifn!("llvm.memmove.p0i8.p0i8.i64",
2689 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2690 ifn!("llvm.memset.p0i8.i32",
2691 [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2692 ifn!("llvm.memset.p0i8.i64",
2693 [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2695 ifn!("llvm.trap", [], Type::void());
2696 ifn!("llvm.frameaddress", [Type::i32()], i8p);
2698 ifn!("llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2699 ifn!("llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2700 ifn!("llvm.pow.f32", [Type::f32(), Type::f32()], Type::f32());
2701 ifn!("llvm.pow.f64", [Type::f64(), Type::f64()], Type::f64());
2703 ifn!("llvm.sqrt.f32", [Type::f32()], Type::f32());
2704 ifn!("llvm.sqrt.f64", [Type::f64()], Type::f64());
2705 ifn!("llvm.sin.f32", [Type::f32()], Type::f32());
2706 ifn!("llvm.sin.f64", [Type::f64()], Type::f64());
2707 ifn!("llvm.cos.f32", [Type::f32()], Type::f32());
2708 ifn!("llvm.cos.f64", [Type::f64()], Type::f64());
2709 ifn!("llvm.exp.f32", [Type::f32()], Type::f32());
2710 ifn!("llvm.exp.f64", [Type::f64()], Type::f64());
2711 ifn!("llvm.exp2.f32", [Type::f32()], Type::f32());
2712 ifn!("llvm.exp2.f64", [Type::f64()], Type::f64());
2713 ifn!("llvm.log.f32", [Type::f32()], Type::f32());
2714 ifn!("llvm.log.f64", [Type::f64()], Type::f64());
2715 ifn!("llvm.log10.f32",[Type::f32()], Type::f32());
2716 ifn!("llvm.log10.f64",[Type::f64()], Type::f64());
2717 ifn!("llvm.log2.f32", [Type::f32()], Type::f32());
2718 ifn!("llvm.log2.f64", [Type::f64()], Type::f64());
2720 ifn!("llvm.fma.f32", [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2721 ifn!("llvm.fma.f64", [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2723 ifn!("llvm.fabs.f32", [Type::f32()], Type::f32());
2724 ifn!("llvm.fabs.f64", [Type::f64()], Type::f64());
2725 ifn!("llvm.floor.f32",[Type::f32()], Type::f32());
2726 ifn!("llvm.floor.f64",[Type::f64()], Type::f64());
2727 ifn!("llvm.ceil.f32", [Type::f32()], Type::f32());
2728 ifn!("llvm.ceil.f64", [Type::f64()], Type::f64());
2729 ifn!("llvm.trunc.f32",[Type::f32()], Type::f32());
2730 ifn!("llvm.trunc.f64",[Type::f64()], Type::f64());
2732 ifn!("llvm.ctpop.i8", [Type::i8()], Type::i8());
2733 ifn!("llvm.ctpop.i16",[Type::i16()], Type::i16());
2734 ifn!("llvm.ctpop.i32",[Type::i32()], Type::i32());
2735 ifn!("llvm.ctpop.i64",[Type::i64()], Type::i64());
2737 ifn!("llvm.ctlz.i8", [Type::i8() , Type::i1()], Type::i8());
2738 ifn!("llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2739 ifn!("llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2740 ifn!("llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2742 ifn!("llvm.cttz.i8", [Type::i8() , Type::i1()], Type::i8());
2743 ifn!("llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2744 ifn!("llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2745 ifn!("llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2747 ifn!("llvm.bswap.i16",[Type::i16()], Type::i16());
2748 ifn!("llvm.bswap.i32",[Type::i32()], Type::i32());
2749 ifn!("llvm.bswap.i64",[Type::i64()], Type::i64());
2751 ifn!("llvm.sadd.with.overflow.i8",
2752 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2753 ifn!("llvm.sadd.with.overflow.i16",
2754 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2755 ifn!("llvm.sadd.with.overflow.i32",
2756 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2757 ifn!("llvm.sadd.with.overflow.i64",
2758 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2760 ifn!("llvm.uadd.with.overflow.i8",
2761 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2762 ifn!("llvm.uadd.with.overflow.i16",
2763 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2764 ifn!("llvm.uadd.with.overflow.i32",
2765 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2766 ifn!("llvm.uadd.with.overflow.i64",
2767 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2769 ifn!("llvm.ssub.with.overflow.i8",
2770 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2771 ifn!("llvm.ssub.with.overflow.i16",
2772 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2773 ifn!("llvm.ssub.with.overflow.i32",
2774 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2775 ifn!("llvm.ssub.with.overflow.i64",
2776 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2778 ifn!("llvm.usub.with.overflow.i8",
2779 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2780 ifn!("llvm.usub.with.overflow.i16",
2781 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2782 ifn!("llvm.usub.with.overflow.i32",
2783 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2784 ifn!("llvm.usub.with.overflow.i64",
2785 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2787 ifn!("llvm.smul.with.overflow.i8",
2788 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2789 ifn!("llvm.smul.with.overflow.i16",
2790 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2791 ifn!("llvm.smul.with.overflow.i32",
2792 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2793 ifn!("llvm.smul.with.overflow.i64",
2794 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2796 ifn!("llvm.umul.with.overflow.i8",
2797 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2798 ifn!("llvm.umul.with.overflow.i16",
2799 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2800 ifn!("llvm.umul.with.overflow.i32",
2801 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2802 ifn!("llvm.umul.with.overflow.i64",
2803 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2808 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2809 ifn!("llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2810 ifn!("llvm.dbg.value", [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2813 pub fn trap(bcx: @mut Block) {
2814 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2815 Some(&x) => { Call(bcx, x, []); },
2816 _ => bcx.sess().bug("unbound llvm.trap in trap")
2820 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2821 if !ccx.sess.opts.gc || !ccx.uses_gc {
2825 let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2826 let gc_metadata = do gc_metadata_name.to_c_str().with_ref |buf| {
2828 llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2832 llvm::LLVMSetGlobalConstant(gc_metadata, True);
2833 lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2834 ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2838 pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
2839 let elttype = Type::struct_([ccx.int_type, ccx.int_type], false);
2840 let maptype = Type::array(&elttype, (ccx.module_data.len() + 1) as u64);
2841 let map = do "_rust_mod_map".to_c_str().with_ref |buf| {
2843 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2846 lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2847 let mut elts: ~[ValueRef] = ~[];
2849 // This is not ideal, but the borrow checker doesn't
2850 // like the multiple borrows. At least, it doesn't
2851 // like them on the current snapshot. (2013-06-14)
2853 for (k, _) in ccx.module_data.iter() {
2854 keys.push(k.to_managed());
2857 for key in keys.iter() {
2858 let val = *ccx.module_data.find_equiv(key).unwrap();
2859 let s_const = C_cstr(ccx, *key);
2860 let s_ptr = p2i(ccx, s_const);
2861 let v_ptr = p2i(ccx, val);
2862 let elt = C_struct([s_ptr, v_ptr]);
2865 let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
2868 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2874 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2875 llmod: ModuleRef) -> ValueRef {
2876 let targ_cfg = sess.targ_cfg;
2877 let int_type = Type::int(targ_cfg.arch);
2878 let mut n_subcrates = 1;
2879 let cstore = sess.cstore;
2880 while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2881 let mapname = if *sess.building_library {
2882 fmt!("%s_%s_%s", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2886 let sym_name = ~"_rust_crate_map_" + mapname;
2887 let arrtype = Type::array(&int_type, n_subcrates as u64);
2888 let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false);
2889 let map = do sym_name.to_c_str().with_ref |buf| {
2891 llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2894 lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2898 pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) {
2899 let mut subcrates: ~[ValueRef] = ~[];
2901 let cstore = ccx.sess.cstore;
2902 while cstore::have_crate_data(cstore, i) {
2903 let cdata = cstore::get_crate_data(cstore, i);
2904 let nm = fmt!("_rust_crate_map_%s_%s_%s",
2906 cstore::get_crate_vers(cstore, i),
2907 cstore::get_crate_hash(cstore, i));
2908 let cr = do nm.to_c_str().with_ref |buf| {
2910 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2913 subcrates.push(p2i(ccx, cr));
2916 subcrates.push(C_int(ccx, 0));
2918 let llannihilatefn = match ccx.tcx.lang_items.annihilate_fn() {
2919 Some(annihilate_def_id) => {
2920 if annihilate_def_id.crate == ast::LOCAL_CRATE {
2921 get_item_val(ccx, annihilate_def_id.node)
2923 let annihilate_fn_type = csearch::get_type(ccx.tcx,
2924 annihilate_def_id).ty;
2925 trans_external_path(ccx, annihilate_def_id, annihilate_fn_type)
2928 None => { C_null(Type::i8p()) }
2932 let mod_map = create_module_map(ccx);
2933 llvm::LLVMSetInitializer(map, C_struct(
2935 lib::llvm::llvm::LLVMConstPointerCast(llannihilatefn, Type::i8p().to_ref()),
2937 C_array(ccx.int_type, subcrates)]));
2941 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
2942 -> encoder::EncodeParams<'r> {
2944 let diag = cx.sess.diagnostic();
2945 let item_symbols = &cx.item_symbols;
2946 let discrim_symbols = &cx.discrim_symbols;
2947 let link_meta = &cx.link_meta;
2948 encoder::EncodeParams {
2951 reexports2: cx.exp_map2,
2952 item_symbols: item_symbols,
2953 discrim_symbols: discrim_symbols,
2954 link_meta: link_meta,
2955 cstore: cx.sess.cstore,
2956 encode_inlined_item: ie,
2957 reachable: cx.reachable,
2961 pub fn write_metadata(cx: &mut CrateContext, crate: &ast::Crate) {
2962 if !*cx.sess.building_library { return; }
2964 let encode_inlined_item: encoder::encode_inlined_item =
2965 |ecx, ebml_w, path, ii|
2966 astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
2968 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2969 let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
2970 let llconst = C_struct([llmeta]);
2971 let mut llglobal = do "rust_metadata".to_c_str().with_ref |buf| {
2973 llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
2977 llvm::LLVMSetInitializer(llglobal, llconst);
2978 do cx.sess.targ_cfg.target_strs.meta_sect_name.to_c_str().with_ref |buf| {
2979 llvm::LLVMSetSection(llglobal, buf)
2981 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2983 let t_ptr_i8 = Type::i8p();
2984 llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
2985 let llvm_used = do "llvm.used".to_c_str().with_ref |buf| {
2986 llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
2988 lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
2989 llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
2993 fn mk_global(ccx: &CrateContext,
2999 let llglobal = do name.to_c_str().with_ref |buf| {
3000 llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval).to_ref(), buf)
3002 llvm::LLVMSetInitializer(llglobal, llval);
3003 llvm::LLVMSetGlobalConstant(llglobal, True);
3006 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
3013 // Writes the current ABI version into the crate.
3014 pub fn write_abi_version(ccx: &mut CrateContext) {
3015 mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version), false);
3018 pub fn trans_crate(sess: session::Session,
3020 analysis: &CrateAnalysis,
3021 output: &Path) -> CrateTranslation {
3022 // Before we touch LLVM, make sure that multithreading is enabled.
3023 if unsafe { !llvm::LLVMRustStartMultithreading() } {
3024 //sess.bug("couldn't enable multi-threaded LLVM");
3027 let mut symbol_hasher = hash::default_state();
3028 let link_meta = link::build_link_meta(sess, crate, output, &mut symbol_hasher);
3030 // Append ".rc" to crate name as LLVM module identifier.
3032 // LLVM code generator emits a ".file filename" directive
3033 // for ELF backends. Value of the "filename" is set as the
3034 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
3035 // crashes if the module identifer is same as other symbols
3036 // such as a function name in the module.
3037 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
3038 let llmod_id = link_meta.name.to_owned() + ".rc";
3040 let ccx = @mut CrateContext::new(sess,
3047 analysis.reachable);
3050 let _icx = push_ctxt("data");
3051 trans_constants(ccx, crate);
3055 let _icx = push_ctxt("text");
3056 trans_mod(ccx, &crate.module);
3059 decl_gc_metadata(ccx, llmod_id);
3060 fill_crate_map(ccx, ccx.crate_map);
3061 glue::emit_tydescs(ccx);
3062 write_abi_version(ccx);
3063 if ccx.sess.opts.debuginfo {
3064 debuginfo::finalize(ccx);
3067 // Translate the metadata.
3068 write_metadata(ccx, crate);
3069 if ccx.sess.trans_stats() {
3070 io::println("--- trans stats ---");
3071 printfln!("n_static_tydescs: %u", ccx.stats.n_static_tydescs);
3072 printfln!("n_glues_created: %u", ccx.stats.n_glues_created);
3073 printfln!("n_null_glues: %u", ccx.stats.n_null_glues);
3074 printfln!("n_real_glues: %u", ccx.stats.n_real_glues);
3076 printfln!("n_fns: %u", ccx.stats.n_fns);
3077 printfln!("n_monos: %u", ccx.stats.n_monos);
3078 printfln!("n_inlines: %u", ccx.stats.n_inlines);
3079 printfln!("n_closures: %u", ccx.stats.n_closures);
3080 io::println("fn stats:");
3081 do sort::quick_sort(ccx.stats.fn_stats) |&(_, _, insns_a), &(_, _, insns_b)| {
3084 for tuple in ccx.stats.fn_stats.iter() {
3086 (ref name, ms, insns) => {
3087 printfln!("%u insns, %u ms, %s", insns, ms, *name);
3092 if ccx.sess.count_llvm_insns() {
3093 for (k, v) in ccx.stats.llvm_insns.iter() {
3094 printfln!("%-7u %s", *v, *k);
3098 let llcx = ccx.llcx;
3099 let link_meta = ccx.link_meta;
3100 let llmod = ccx.llmod;
3102 return CrateTranslation {