1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // trans.rs: Translate the completed AST to the LLVM IR.
13 // Some functions here, such as trans_block and trans_expr, return a value --
14 // the result of the translation to LLVM -- while others, such as trans_fn,
15 // trans_impl, and trans_item, are called only for the side effect of adding a
16 // particular definition to the LLVM IR output we're producing.
18 // Hopefully useful general knowledge about trans:
20 // * There's no way to find out the ty::t type of a ValueRef. Doing so
21 // would be "trying to get the eggs out of an omelette" (credit:
22 // pcwalton). You can, instead, find out its TypeRef by calling val_ty,
23 // but one TypeRef corresponds to many `ty::t`s; for instance, tup(int, int,
24 // int) and rec(x=int, y=int, z=int) will have the same TypeRef.
26 #[allow(non_camel_case_types)];
28 use back::link::{mangle_exported_name};
29 use back::{link, abi};
31 use driver::session::Session;
32 use driver::driver::OutputFilenames;
33 use driver::driver::{CrateAnalysis, CrateTranslation};
34 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
35 use lib::llvm::{llvm, True, Vector};
37 use metadata::common::LinkMeta;
38 use metadata::{csearch, encoder};
39 use middle::astencode;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::lang_items::{MallocFnLangItem, ClosureExchangeMallocFnLangItem};
42 use middle::trans::_match;
43 use middle::trans::adt;
44 use middle::trans::build::*;
45 use middle::trans::builder::{Builder, noname};
46 use middle::trans::callee;
47 use middle::trans::cleanup;
48 use middle::trans::cleanup::CleanupMethods;
49 use middle::trans::common::*;
50 use middle::trans::consts;
51 use middle::trans::controlflow;
52 use middle::trans::datum;
53 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
54 use middle::trans::debuginfo;
55 use middle::trans::expr;
56 use middle::trans::foreign;
57 use middle::trans::glue;
58 use middle::trans::inline;
59 use middle::trans::machine;
60 use middle::trans::machine::{llalign_of_min, llsize_of};
61 use middle::trans::meth;
62 use middle::trans::monomorphize;
63 use middle::trans::tvec;
64 use middle::trans::type_::Type;
65 use middle::trans::type_of;
66 use middle::trans::type_of::*;
67 use middle::trans::value::Value;
70 use util::common::indenter;
71 use util::ppaux::{Repr, ty_to_str};
72 use util::sha2::Sha256;
74 use arena::TypedArena;
75 use std::c_str::ToCStr;
76 use std::cell::{Cell, RefCell};
77 use collections::HashMap;
78 use std::libc::c_uint;
80 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic, OsWin32};
81 use syntax::ast_map::PathName;
82 use syntax::ast_util::{local_def, is_local};
83 use syntax::attr::AttrMetaMethods;
85 use syntax::codemap::Span;
86 use syntax::parse::token::InternedString;
87 use syntax::parse::token;
88 use syntax::visit::Visitor;
90 use syntax::{ast, ast_util, ast_map};
94 pub use middle::trans::context::task_llcx;
96 local_data_key!(task_local_insn_key: ~[&'static str])
98 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
99 local_data::get(task_local_insn_key, |c| {
101 Some(ctx) => blk(*ctx),
107 pub fn init_insn_ctxt() {
108 local_data::set(task_local_insn_key, ~[]);
111 pub struct _InsnCtxt { _x: () }
114 impl Drop for _InsnCtxt {
116 local_data::modify(task_local_insn_key, |c| {
125 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
126 debug!("new InsnCtxt: {}", s);
127 local_data::modify(task_local_insn_key, |c| {
136 pub struct StatRecorder {
144 pub fn new(ccx: @CrateContext, name: ~str) -> StatRecorder {
145 let start = if ccx.sess.trans_stats() {
146 time::precise_time_ns()
150 let istart = ccx.stats.n_llvm_insns.get();
161 impl Drop for StatRecorder {
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.get();
168 let mut fn_stats = self.ccx.stats.fn_stats.borrow_mut();
169 fn_stats.get().push((self.name.take_unwrap(),
171 iend - self.istart));
173 self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
174 // Reset LLVM insn count to avoid compound costs.
175 self.ccx.stats.n_llvm_insns.set(self.istart);
180 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
181 fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv,
182 ty: Type, output: ty::t) -> ValueRef {
183 let llfn: ValueRef = name.with_c_str(|buf| {
185 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
189 match ty::get(output).sty {
190 // functions returning bottom may unwind, but can never return normally
193 llvm::LLVMAddFunctionAttr(llfn, lib::llvm::NoReturnAttribute as c_uint)
196 // `~` pointer return values never alias because ownership is transferred
197 // FIXME #6750 ~Trait cannot be directly marked as
198 // noalias because the actual object pointer is nested.
199 ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
200 ty::ty_vec(_, ty::vstore_uniq) | ty::ty_str(ty::vstore_uniq) => {
202 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
208 lib::llvm::SetFunctionCallConv(llfn, cc);
209 // Function addresses in Rust are never significant, allowing functions to be merged.
210 lib::llvm::SetUnnamedAddr(llfn, true);
215 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
216 pub fn decl_cdecl_fn(llmod: ModuleRef,
219 output: ty::t) -> ValueRef {
220 decl_fn(llmod, name, lib::llvm::CCallConv, ty, output)
223 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
224 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef,
225 name: &str, cc: lib::llvm::CallConv,
226 ty: Type, output: ty::t) -> ValueRef {
227 match externs.find_equiv(&name) {
228 Some(n) => return *n,
231 let f = decl_fn(llmod, name, cc, ty, output);
232 externs.insert(name.to_owned(), f);
236 fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
237 name: &str, did: ast::DefId) -> ValueRef {
239 let externs = ccx.externs.borrow();
240 match externs.get().find_equiv(&name) {
241 Some(n) => return *n,
246 let f = decl_rust_fn(ccx, false, inputs, output, name);
247 csearch::get_item_attrs(ccx.tcx.cstore, did, |meta_items| {
248 set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).to_owned_vec(), f)
251 let mut externs = ccx.externs.borrow_mut();
252 externs.get().insert(name.to_owned(), f);
256 pub fn decl_rust_fn(ccx: &CrateContext, has_env: bool,
257 inputs: &[ty::t], output: ty::t,
258 name: &str) -> ValueRef {
259 let llfty = type_of_rust_fn(ccx, has_env, inputs, output);
260 let llfn = decl_cdecl_fn(ccx.llmod, name, llfty, output);
262 let uses_outptr = type_of::return_uses_outptr(ccx, output);
263 let offset = if uses_outptr { 1 } else { 0 };
264 let offset = if has_env { offset + 1 } else { offset };
266 for (i, &arg_ty) in inputs.iter().enumerate() {
267 let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
268 match ty::get(arg_ty).sty {
269 // `~` pointer parameters never alias because ownership is transferred
270 // FIXME #6750 ~Trait cannot be directly marked as
271 // noalias because the actual object pointer is nested.
272 ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
273 ty::ty_vec(_, ty::vstore_uniq) | ty::ty_str(ty::vstore_uniq) |
274 ty::ty_closure(ty::ClosureTy {sigil: ast::OwnedSigil, ..}) => {
276 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
280 // For non-immediate arguments the callee gets its own copy of
281 // the value on the stack, so there are no aliases
282 if !type_is_immediate(ccx, arg_ty) {
284 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
285 llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
292 // The out pointer will never alias with any other pointers, as the object only exists at a
293 // language level after the call. It can also be tagged with SRet to indicate that it is
294 // guaranteed to point to a usable block of memory for the type.
297 let outptr = llvm::LLVMGetParam(llfn, 0);
298 llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
299 llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
306 pub fn decl_internal_rust_fn(ccx: &CrateContext, has_env: bool,
307 inputs: &[ty::t], output: ty::t,
308 name: &str) -> ValueRef {
309 let llfn = decl_rust_fn(ccx, has_env, inputs, output, name);
310 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
314 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
315 name: &str, ty: Type) -> ValueRef {
316 match externs.find_equiv(&name) {
317 Some(n) => return *n,
321 let c = name.with_c_str(|buf| {
322 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
324 externs.insert(name.to_owned(), c);
329 // Returns a pointer to the body for the box. The box may be an opaque
330 // box. The result will be casted to the type of body_t, if it is statically
332 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
333 let _icx = push_ctxt("at_box_body");
335 let ty = Type::at_box(ccx, type_of(ccx, body_t));
336 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
337 GEPi(bcx, boxptr, [0u, abi::box_field_body])
340 // malloc_raw_dyn: allocates a box to contain a given type, but with a
341 // potentially dynamic size.
342 pub fn malloc_raw_dyn<'a>(
348 let _icx = push_ctxt("malloc_raw");
351 fn require_alloc_fn(bcx: &Block, t: ty::t, it: LangItem) -> ast::DefId {
352 let li = &bcx.tcx().lang_items;
353 match li.require(it) {
356 bcx.tcx().sess.fatal(format!("allocation of `{}` {}",
357 bcx.ty_to_str(t), s));
362 if heap == heap_exchange {
363 let llty_value = type_of::type_of(ccx, t);
366 let r = callee::trans_lang_call(
368 require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
371 rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
373 // we treat ~fn as @ here, which isn't ideal
374 let langcall = match heap {
376 require_alloc_fn(bcx, t, MallocFnLangItem)
378 heap_exchange_closure => {
379 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem)
381 _ => fail!("heap_exchange already handled")
384 // Grab the TypeRef type of box_ptr_ty.
385 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
386 let llty = type_of(ccx, box_ptr_ty);
387 let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
390 let drop_glue = glue::get_drop_glue(ccx, t);
391 let r = callee::trans_lang_call(
394 [PointerCast(bcx, drop_glue, Type::glue_fn(Type::i8p()).ptr_to()), size, llalign],
396 rslt(r.bcx, PointerCast(r.bcx, r.val, llty))
400 // malloc_raw: expects an unboxed type and returns a pointer to
401 // enough space for a box of that type. This includes a rust_opaque_box
403 pub fn malloc_raw<'a>(bcx: &'a Block<'a>, t: ty::t, heap: heap)
405 let ty = type_of(bcx.ccx(), t);
406 let size = llsize_of(bcx.ccx(), ty);
407 malloc_raw_dyn(bcx, t, heap, size)
410 pub struct MallocResult<'a> {
416 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a smart
417 // pointer, and pulls out the body
418 pub fn malloc_general_dyn<'a>(
423 -> MallocResult<'a> {
424 assert!(heap != heap_exchange);
425 let _icx = push_ctxt("malloc_general");
426 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
427 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
436 pub fn malloc_general<'a>(bcx: &'a Block<'a>, t: ty::t, heap: heap)
437 -> MallocResult<'a> {
438 let ty = type_of(bcx.ccx(), t);
439 assert!(heap != heap_exchange);
440 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
443 // Type descriptor and type glue stuff
445 pub fn get_tydesc_simple(ccx: &CrateContext, t: ty::t) -> ValueRef {
446 get_tydesc(ccx, t).tydesc
449 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> @tydesc_info {
451 let tydescs = ccx.tydescs.borrow();
452 match tydescs.get().find(&t) {
453 Some(&inf) => return inf,
458 ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
459 let inf = glue::declare_tydesc(ccx, t);
461 let mut tydescs = ccx.tydescs.borrow_mut();
462 tydescs.get().insert(t, inf);
466 pub fn set_optimize_for_size(f: ValueRef) {
467 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
470 pub fn set_no_inline(f: ValueRef) {
471 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
474 pub fn set_no_unwind(f: ValueRef) {
475 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
478 // Tell LLVM to emit the information necessary to unwind the stack for the
480 pub fn set_uwtable(f: ValueRef) {
481 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
484 pub fn set_inline_hint(f: ValueRef) {
485 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
488 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
490 // Set the inline hint if there is one
491 match find_inline_attr(attrs) {
492 InlineHint => set_inline_hint(llfn),
493 InlineAlways => set_always_inline(llfn),
494 InlineNever => set_no_inline(llfn),
495 InlineNone => { /* fallthrough */ }
498 // Add the no-split-stack attribute if requested
499 if contains_name(attrs, "no_split_stack") {
500 set_no_split_stack(llfn);
503 if contains_name(attrs, "cold") {
504 unsafe { llvm::LLVMAddColdAttribute(llfn) }
508 pub fn set_always_inline(f: ValueRef) {
509 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
512 pub fn set_no_split_stack(f: ValueRef) {
513 "no-split-stack".with_c_str(|buf| {
514 unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
518 // Double-check that we never ask LLVM to declare the same symbol twice. It
519 // silently mangles such symbols, breaking our linkage model.
520 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) {
521 let mut all_llvm_symbols = ccx.all_llvm_symbols.borrow_mut();
522 if all_llvm_symbols.get().contains(&sym) {
523 ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
525 all_llvm_symbols.get().insert(sym);
529 pub fn get_res_dtor(ccx: @CrateContext,
531 parent_id: ast::DefId,
534 let _icx = push_ctxt("trans_res_dtor");
535 let did = if did.krate != ast::LOCAL_CRATE {
536 inline::maybe_instantiate_inline(ccx, did)
540 if !substs.is_empty() {
541 assert_eq!(did.krate, ast::LOCAL_CRATE);
542 let tsubsts = ty::substs {
543 regions: ty::ErasedRegions,
545 tps: substs.to_owned()
548 let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx, did.node, &tsubsts);
549 let (val, _) = monomorphize::monomorphic_fn(ccx, did, &tsubsts, vtables, None, None);
552 } else if did.krate == ast::LOCAL_CRATE {
553 get_item_val(ccx, did.node)
556 let name = csearch::get_symbol(ccx.sess.cstore, did);
557 let class_ty = ty::subst_tps(tcx,
560 ty::lookup_item_type(tcx, parent_id).ty);
561 let llty = type_of_dtor(ccx, class_ty);
564 let mut externs = ccx.externs.borrow_mut();
565 get_extern_fn(externs.get(), ccx.llmod, name,
566 lib::llvm::CCallConv, llty, ty::mk_nil())
571 // Structural comparison: a rather involved form of glue.
572 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
573 if cx.sess.opts.cg.save_temps {
576 llvm::LLVMSetValueName(v, buf)
583 // Used only for creating scalar comparison glue.
584 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
586 // NB: This produces an i1, not a Rust bool (i8).
587 pub fn compare_scalar_types<'a>(
594 let f = |a| rslt(cx, compare_scalar_values(cx, lhs, rhs, a, op));
596 match ty::get(t).sty {
597 ty::ty_nil => f(nil_type),
598 ty::ty_bool | ty::ty_ptr(_) |
599 ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
600 ty::ty_int(_) => f(signed_int),
601 ty::ty_float(_) => f(floating_point),
602 // Should never get here, because t is scalar.
603 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
608 // A helper function to do the actual comparison of scalar values.
609 pub fn compare_scalar_values<'a>(
616 let _icx = push_ctxt("compare_scalar_values");
617 fn die(cx: &Block) -> ! {
618 cx.tcx().sess.bug("compare_scalar_values: must be a\
619 comparison operator");
623 // We don't need to do actual comparisons for nil.
624 // () == () holds but () < () does not.
626 ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(true),
627 ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(false),
628 // refinements would be nice
634 ast::BiEq => lib::llvm::RealOEQ,
635 ast::BiNe => lib::llvm::RealUNE,
636 ast::BiLt => lib::llvm::RealOLT,
637 ast::BiLe => lib::llvm::RealOLE,
638 ast::BiGt => lib::llvm::RealOGT,
639 ast::BiGe => lib::llvm::RealOGE,
642 return FCmp(cx, cmp, lhs, rhs);
646 ast::BiEq => lib::llvm::IntEQ,
647 ast::BiNe => lib::llvm::IntNE,
648 ast::BiLt => lib::llvm::IntSLT,
649 ast::BiLe => lib::llvm::IntSLE,
650 ast::BiGt => lib::llvm::IntSGT,
651 ast::BiGe => lib::llvm::IntSGE,
654 return ICmp(cx, cmp, lhs, rhs);
658 ast::BiEq => lib::llvm::IntEQ,
659 ast::BiNe => lib::llvm::IntNE,
660 ast::BiLt => lib::llvm::IntULT,
661 ast::BiLe => lib::llvm::IntULE,
662 ast::BiGt => lib::llvm::IntUGT,
663 ast::BiGe => lib::llvm::IntUGE,
666 return ICmp(cx, cmp, lhs, rhs);
671 pub type val_and_ty_fn<'r,'b> =
672 'r |&'b Block<'b>, ValueRef, ty::t| -> &'b Block<'b>;
674 pub fn load_inbounds<'a>(cx: &'a Block<'a>, p: ValueRef, idxs: &[uint])
676 return Load(cx, GEPi(cx, p, idxs));
679 pub fn store_inbounds<'a>(
684 Store(cx, v, GEPi(cx, p, idxs));
687 // Iterates through the elements of a structural type.
688 pub fn iter_structural_ty<'r,
693 f: val_and_ty_fn<'r,'b>)
695 let _icx = push_ctxt("iter_structural_ty");
702 variant: @ty::VariantInfo,
704 f: val_and_ty_fn<'r,'b>)
706 let _icx = push_ctxt("iter_variant");
710 for (i, &arg) in variant.args.iter().enumerate() {
712 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
713 ty::subst_tps(tcx, tps, None, arg));
719 match ty::get(t).sty {
720 ty::ty_struct(..) => {
721 let repr = adt::represent_type(cx.ccx(), t);
722 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
723 for (i, field_ty) in field_tys.iter().enumerate() {
724 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
725 cx = f(cx, llfld_a, field_ty.mt.ty);
729 ty::ty_str(ty::vstore_fixed(_)) |
730 ty::ty_vec(_, ty::vstore_fixed(_)) => {
731 let (base, len) = tvec::get_base_and_byte_len(cx, av, t);
732 cx = tvec::iter_vec_raw(cx, base, t, len, f);
734 ty::ty_tup(ref args) => {
735 let repr = adt::represent_type(cx.ccx(), t);
736 for (i, arg) in args.iter().enumerate() {
737 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
738 cx = f(cx, llfld_a, *arg);
741 ty::ty_enum(tid, ref substs) => {
745 let repr = adt::represent_type(ccx, t);
746 let variants = ty::enum_variants(ccx.tcx, tid);
747 let n_variants = (*variants).len();
749 // NB: we must hit the discriminant first so that structural
750 // comparison know not to proceed when the discriminants differ.
752 match adt::trans_switch(cx, repr, av) {
753 (_match::single, None) => {
754 cx = iter_variant(cx, repr, av, variants[0],
757 (_match::switch, Some(lldiscrim_a)) => {
758 cx = f(cx, lldiscrim_a, ty::mk_int());
759 let unr_cx = fcx.new_temp_block("enum-iter-unr");
761 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
763 let next_cx = fcx.new_temp_block("enum-iter-next");
765 for variant in (*variants).iter() {
767 fcx.new_temp_block(~"enum-iter-variant-" +
768 variant.disr_val.to_str());
769 match adt::trans_case(cx, repr, variant.disr_val) {
770 _match::single_result(r) => {
771 AddCase(llswitch, r.val, variant_cx.llbb)
773 _ => ccx.sess.unimpl("value from adt::trans_case \
774 in iter_structural_ty")
777 iter_variant(variant_cx, repr, av, *variant,
778 substs.tps, |x,y,z| f(x,y,z));
779 Br(variant_cx, next_cx.llbb);
783 _ => ccx.sess.unimpl("value from adt::trans_switch \
784 in iter_structural_ty")
787 _ => cx.sess().unimpl("type in iter_structural_ty")
792 pub fn cast_shift_expr_rhs<'a>(
798 cast_shift_rhs(op, lhs, rhs,
799 |a,b| Trunc(cx, a, b),
800 |a,b| ZExt(cx, a, b))
803 pub fn cast_shift_const_rhs(op: ast::BinOp,
804 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
805 cast_shift_rhs(op, lhs, rhs,
806 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
807 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
810 pub fn cast_shift_rhs(op: ast::BinOp,
813 trunc: |ValueRef, Type| -> ValueRef,
814 zext: |ValueRef, Type| -> ValueRef)
816 // Shifts may have any size int on the rhs
818 if ast_util::is_shift_binop(op) {
819 let mut rhs_llty = val_ty(rhs);
820 let mut lhs_llty = val_ty(lhs);
821 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
822 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
823 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
824 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
827 } else if lhs_sz > rhs_sz {
828 // FIXME (#1877: If shifting by negative
829 // values becomes not undefined then this is wrong.
840 pub fn fail_if_zero<'a>(
847 let text = if divrem == ast::BiDiv {
848 "attempted to divide by zero"
850 "attempted remainder with a divisor of zero"
852 let is_zero = match ty::get(rhs_t).sty {
854 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
855 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
858 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
859 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
862 cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
863 ty_to_str(cx.ccx().tcx, rhs_t));
866 with_cond(cx, is_zero, |bcx| {
867 controlflow::trans_fail(bcx, span, InternedString::new(text))
871 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
872 let name = csearch::get_symbol(ccx.sess.cstore, did);
873 match ty::get(t).sty {
874 ty::ty_bare_fn(ref fn_ty) => {
875 match fn_ty.abis.for_target(ccx.sess.targ_cfg.os,
876 ccx.sess.targ_cfg.arch) {
877 Some(Rust) | Some(RustIntrinsic) => {
878 get_extern_rust_fn(ccx, fn_ty.sig.inputs, fn_ty.sig.output, name, did)
881 let c = foreign::llvm_calling_convention(ccx, fn_ty.abis);
882 let cconv = c.unwrap_or(lib::llvm::CCallConv);
883 let llty = type_of_fn_from_ty(ccx, t);
884 let mut externs = ccx.externs.borrow_mut();
885 get_extern_fn(externs.get(), ccx.llmod, name,
886 cconv, llty, fn_ty.sig.output)
890 ty::ty_closure(ref f) => {
891 get_extern_rust_fn(ccx, f.sig.inputs, f.sig.output, name, did)
894 let llty = type_of(ccx, t);
895 let mut externs = ccx.externs.borrow_mut();
896 get_extern_const(externs.get(), ccx.llmod, name, llty)
905 attributes: &[(uint, lib::llvm::Attribute)],
906 call_info: Option<NodeInfo>)
907 -> (ValueRef, &'a Block<'a>) {
908 let _icx = push_ctxt("invoke_");
909 if bcx.unreachable.get() {
910 return (C_null(Type::i8()), bcx);
913 match bcx.opt_node_id {
915 debug!("invoke at ???");
918 debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
922 if need_invoke(bcx) {
923 debug!("invoking {} at {}", llfn, bcx.llbb);
924 for &llarg in llargs.iter() {
925 debug!("arg: {}", llarg);
927 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
928 let landing_pad = bcx.fcx.get_landing_pad();
931 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
932 None => debuginfo::clear_source_location(bcx.fcx)
935 let llresult = Invoke(bcx,
941 return (llresult, normal_bcx);
943 debug!("calling {} at {}", llfn, bcx.llbb);
944 for &llarg in llargs.iter() {
945 debug!("arg: {}", llarg);
949 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
950 None => debuginfo::clear_source_location(bcx.fcx)
953 let llresult = Call(bcx, llfn, llargs, attributes);
954 return (llresult, bcx);
958 pub fn need_invoke(bcx: &Block) -> bool {
959 if bcx.ccx().sess.no_landing_pads() {
963 // Avoid using invoke if we are already inside a landing pad.
968 bcx.fcx.needs_invoke()
971 pub fn do_spill(bcx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
972 if ty::type_is_bot(t) {
973 return C_null(Type::i8p());
975 let llptr = alloc_ty(bcx, t, "");
976 Store(bcx, v, llptr);
980 // Since this function does *not* root, it is the caller's responsibility to
981 // ensure that the referent is pointed to by a root.
982 pub fn do_spill_noroot(cx: &Block, v: ValueRef) -> ValueRef {
983 let llptr = alloca(cx, val_ty(v), "");
988 pub fn spill_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
989 let _icx = push_ctxt("spill_if_immediate");
990 if type_is_immediate(cx.ccx(), t) { return do_spill(cx, v, t); }
994 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
995 let _icx = push_ctxt("load_if_immediate");
996 if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
1000 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
1001 match local.pat.node {
1002 ast::PatWild => true, _ => false
1006 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
1009 debug!("init_local(bcx={}, local.id={:?})",
1010 bcx.to_str(), local.id);
1011 let _indenter = indenter();
1013 let _icx = push_ctxt("init_local");
1015 if ignore_lhs(bcx, local) {
1016 // Handle let _ = e; just like e;
1019 return expr::trans_into(bcx, init, expr::Ignore);
1021 None => { return bcx; }
1025 _match::store_local(bcx, local)
1028 pub fn raw_block<'a>(
1029 fcx: &'a FunctionContext<'a>,
1031 llbb: BasicBlockRef)
1033 Block::new(llbb, is_lpad, None, fcx)
1036 pub fn block_locals(b: &ast::Block, it: |@ast::Local|) {
1037 for s in b.stmts.iter() {
1039 ast::StmtDecl(d, _) => {
1041 ast::DeclLocal(ref local) => it(*local),
1042 _ => {} /* fall through */
1045 _ => {} /* fall through */
1050 pub fn with_cond<'a>(
1053 f: |&'a Block<'a>| -> &'a Block<'a>)
1055 let _icx = push_ctxt("with_cond");
1057 let next_cx = fcx.new_temp_block("next");
1058 let cond_cx = fcx.new_temp_block("cond");
1059 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1060 let after_cx = f(cond_cx);
1061 if !after_cx.terminated.get() {
1062 Br(after_cx, next_cx.llbb);
1067 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1068 let _icx = push_ctxt("call_memcpy");
1070 let key = match ccx.sess.targ_cfg.arch {
1071 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1072 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1074 let memcpy = ccx.intrinsics.get_copy(&key);
1075 let src_ptr = PointerCast(cx, src, Type::i8p());
1076 let dst_ptr = PointerCast(cx, dst, Type::i8p());
1077 let size = IntCast(cx, n_bytes, ccx.int_type);
1078 let align = C_i32(align as i32);
1079 let volatile = C_i1(false);
1080 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1083 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1084 let _icx = push_ctxt("memcpy_ty");
1085 let ccx = bcx.ccx();
1086 if ty::type_is_structural(t) {
1087 let llty = type_of::type_of(ccx, t);
1088 let llsz = llsize_of(ccx, llty);
1089 let llalign = llalign_of_min(ccx, llty);
1090 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1092 Store(bcx, Load(bcx, src), dst);
1096 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1097 if cx.unreachable.get() { return; }
1098 let _icx = push_ctxt("zero_mem");
1101 let llty = type_of::type_of(ccx, t);
1102 memzero(&B(bcx), llptr, llty);
1105 // Always use this function instead of storing a zero constant to the memory
1106 // in question. If you store a zero constant, LLVM will drown in vreg
1107 // allocation for large data structures, and the generated code will be
1108 // awful. (A telltale sign of this is large quantities of
1109 // `mov [byte ptr foo],0` in the generated code.)
1110 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1111 let _icx = push_ctxt("memzero");
1114 let intrinsic_key = match ccx.sess.targ_cfg.arch {
1115 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1116 X86_64 => "llvm.memset.p0i8.i64"
1119 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1120 let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1121 let llzeroval = C_u8(0);
1122 let size = machine::llsize_of(ccx, ty);
1123 let align = C_i32(llalign_of_min(ccx, ty) as i32);
1124 let volatile = C_i1(false);
1125 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1128 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1129 let _icx = push_ctxt("alloc_ty");
1130 let ccx = bcx.ccx();
1131 let ty = type_of::type_of(ccx, t);
1132 assert!(!ty::type_has_params(t));
1133 let val = alloca(bcx, ty, name);
1137 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1138 alloca_maybe_zeroed(cx, ty, name, false)
1141 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1142 let _icx = push_ctxt("alloca");
1143 if cx.unreachable.get() {
1145 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1148 debuginfo::clear_source_location(cx.fcx);
1149 let p = Alloca(cx, ty, name);
1151 let b = cx.fcx.ccx.builder();
1152 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1158 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1159 let _icx = push_ctxt("arrayalloca");
1160 if cx.unreachable.get() {
1162 return llvm::LLVMGetUndef(ty.to_ref());
1165 debuginfo::clear_source_location(cx.fcx);
1166 return ArrayAlloca(cx, ty, v);
1169 pub struct BasicBlocks {
1173 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1175 let cx = task_llcx();
1176 "static_allocas".with_c_str(|buf| {
1177 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1182 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1184 let cx = task_llcx();
1185 "return".with_c_str(|buf| {
1186 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1191 // Creates and returns space for, or returns the argument representing, the
1192 // slot where the return value of the function must go.
1193 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1196 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1197 llvm::LLVMGetParam(fcx.llfn, 0)
1199 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1200 let bcx = fcx.entry_bcx.get().unwrap();
1201 Alloca(bcx, lloutputtype, "__make_return_pointer")
1206 // NB: must keep 4 fns in sync:
1209 // - create_datums_for_fn_args.
1213 // Be warned! You must call `init_function` before doing anything with the
1214 // returned function context.
1215 pub fn new_fn_ctxt<'a>(ccx: @CrateContext,
1220 param_substs: Option<@param_substs>,
1222 block_arena: &'a TypedArena<Block<'a>>)
1223 -> FunctionContext<'a> {
1224 for p in param_substs.iter() { p.validate(); }
1226 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1227 if id == -1 { ~"" } else { ccx.tcx.map.path_to_str(id) },
1228 id, param_substs.repr(ccx.tcx));
1230 let substd_output_type = match param_substs {
1231 None => output_type,
1233 ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1236 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1237 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1239 let mut fcx = FunctionContext {
1242 llretptr: Cell::new(None),
1243 entry_bcx: RefCell::new(None),
1244 alloca_insert_pt: Cell::new(None),
1245 llreturn: Cell::new(None),
1246 personality: Cell::new(None),
1247 caller_expects_out_pointer: uses_outptr,
1248 llargs: RefCell::new(HashMap::new()),
1249 lllocals: RefCell::new(HashMap::new()),
1250 llupvars: RefCell::new(HashMap::new()),
1252 param_substs: param_substs,
1254 block_arena: block_arena,
1256 debug_context: debug_context,
1257 scopes: RefCell::new(~[])
1261 fcx.llenv = Some(unsafe {
1262 llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1269 /// Performs setup on a newly created function, creating the entry scope block
1270 /// and allocating space for the return pointer.
1271 pub fn init_function<'a>(
1272 fcx: &'a FunctionContext<'a>,
1275 param_substs: Option<@param_substs>) {
1276 let entry_bcx = fcx.new_temp_block("entry-block");
1278 fcx.entry_bcx.set(Some(entry_bcx));
1280 // Use a dummy instruction as the insertion point for all allocas.
1281 // This is later removed in FunctionContext::cleanup.
1282 fcx.alloca_insert_pt.set(Some(unsafe {
1283 Load(entry_bcx, C_null(Type::i8p()));
1284 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1287 let substd_output_type = match param_substs {
1288 None => output_type,
1290 ty::subst_tps(fcx.ccx.tcx,
1297 if !return_type_is_void(fcx.ccx, substd_output_type) {
1298 // If the function returns nil/bot, there is no real return
1299 // value, so do not set `llretptr`.
1300 if !skip_retptr || fcx.caller_expects_out_pointer {
1301 // Otherwise, we normally allocate the llretptr, unless we
1302 // have been instructed to skip it for immediate return
1304 fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1309 // NB: must keep 4 fns in sync:
1312 // - create_datums_for_fn_args.
1316 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1317 use middle::trans::datum::{ByRef, ByValue};
1320 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1324 // work around bizarre resolve errors
1325 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1326 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1328 // create_datums_for_fn_args: creates rvalue datums for each of the
1329 // incoming function arguments. These will later be stored into
1330 // appropriate lvalue datums.
1331 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1334 let _icx = push_ctxt("create_datums_for_fn_args");
1336 // Return an array wrapping the ValueRefs that we get from
1337 // llvm::LLVMGetParam for each argument into datums.
1338 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1339 let llarg = unsafe {
1340 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1342 datum::Datum(llarg, arg_ty, arg_kind(fcx, arg_ty))
1346 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1347 arg_scope: cleanup::CustomScopeIndex,
1350 arg_datums: ~[RvalueDatum])
1352 debug!("copy_args_to_allocas");
1354 let _icx = push_ctxt("copy_args_to_allocas");
1357 let arg_scope_id = cleanup::CustomScope(arg_scope);
1359 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1360 // For certain mode/type combinations, the raw llarg values are passed
1361 // by value. However, within the fn body itself, we want to always
1362 // have all locals and arguments be by-ref so that we can cancel the
1363 // cleanup and for better interaction with LLVM's debug info. So, if
1364 // the argument would be passed by value, we store it into an alloca.
1365 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1366 // the event it's not truly needed.
1368 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1370 if fcx.ccx.sess.opts.debuginfo {
1371 debuginfo::create_argument_metadata(bcx, &args[i]);
1378 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1379 // and builds the return block.
1380 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1381 last_bcx: &'a Block<'a>) {
1382 let _icx = push_ctxt("finish_fn");
1384 let ret_cx = match fcx.llreturn.get() {
1386 if !last_bcx.terminated.get() {
1387 Br(last_bcx, llreturn);
1389 raw_block(fcx, false, llreturn)
1393 build_return_block(fcx, ret_cx);
1394 debuginfo::clear_source_location(fcx);
1398 // Builds the return block for a function.
1399 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1400 // Return the value if this function immediate; otherwise, return void.
1401 if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1402 return RetVoid(ret_cx);
1405 let retptr = Value(fcx.llretptr.get().unwrap());
1406 let retval = match retptr.get_dominating_store(ret_cx) {
1407 // If there's only a single store to the ret slot, we can directly return
1408 // the value that was stored and omit the store and the alloca
1410 let retval = s.get_operand(0).unwrap().get();
1411 s.erase_from_parent();
1413 if retptr.has_no_uses() {
1414 retptr.erase_from_parent();
1419 // Otherwise, load the return value from the ret slot
1420 None => Load(ret_cx, fcx.llretptr.get().unwrap())
1424 Ret(ret_cx, retval);
1427 // trans_closure: Builds an LLVM function out of a source function.
1428 // If the function closes over its environment a closure will be
1430 pub fn trans_closure<'a>(ccx: @CrateContext,
1434 param_substs: Option<@param_substs>,
1436 _attributes: &[ast::Attribute],
1438 maybe_load_env: <'b> |&'b Block<'b>| -> &'b Block<'b>) {
1439 ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1441 let _icx = push_ctxt("trans_closure");
1442 set_uwtable(llfndecl);
1444 debug!("trans_closure(..., param_substs={})",
1445 param_substs.repr(ccx.tcx));
1447 let has_env = match ty::get(ty::node_id_to_type(ccx.tcx, id)).sty {
1448 ty::ty_closure(_) => true,
1452 let arena = TypedArena::new();
1453 let fcx = new_fn_ctxt(ccx,
1461 init_function(&fcx, false, output_type, param_substs);
1463 // cleanup scope for the incoming arguments
1464 let arg_scope = fcx.push_custom_cleanup_scope();
1466 // Create the first basic block in the function and keep a handle on it to
1467 // pass to finish_fn later.
1468 let bcx_top = fcx.entry_bcx.get().unwrap();
1469 let mut bcx = bcx_top;
1470 let block_ty = node_id_type(bcx, body.id);
1472 // Set up arguments to the function.
1473 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1474 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys);
1476 bcx = copy_args_to_allocas(&fcx,
1479 decl.inputs.as_slice(),
1482 bcx = maybe_load_env(bcx);
1484 // Up until here, IR instructions for this function have explicitly not been annotated with
1485 // source code location, so we don't step into call setup code. From here on, source location
1486 // emitting should be enabled.
1487 debuginfo::start_emitting_source_locations(&fcx);
1489 let dest = match fcx.llretptr.get() {
1490 Some(e) => {expr::SaveIn(e)}
1492 assert!(type_is_zero_size(bcx.ccx(), block_ty))
1497 // This call to trans_block is the place where we bridge between
1498 // translation calls that don't have a return value (trans_crate,
1499 // trans_mod, trans_item, et cetera) and those that do
1500 // (trans_block, trans_expr, et cetera).
1501 bcx = controlflow::trans_block(bcx, body, dest);
1503 match fcx.llreturn.get() {
1505 Br(bcx, fcx.return_exit_block());
1506 fcx.pop_custom_cleanup_scope(arg_scope);
1509 // Microoptimization writ large: avoid creating a separate
1510 // llreturn basic block
1511 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1515 // Put return block after all other blocks.
1516 // This somewhat improves single-stepping experience in debugger.
1518 let llreturn = fcx.llreturn.get();
1519 for &llreturn in llreturn.iter() {
1520 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1524 // Insert the mandatory first few basic blocks before lltop.
1525 finish_fn(&fcx, bcx);
1528 // trans_fn: creates an LLVM function corresponding to a source language
1530 pub fn trans_fn(ccx: @CrateContext,
1534 param_substs: Option<@param_substs>,
1536 attrs: &[ast::Attribute]) {
1537 let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id));
1538 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx));
1539 let _icx = push_ctxt("trans_fn");
1540 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1541 trans_closure(ccx, decl, body, llfndecl,
1542 param_substs, id, attrs, output_type, |bcx| bcx);
1545 pub fn trans_enum_variant(ccx: @CrateContext,
1546 _enum_id: ast::NodeId,
1547 variant: &ast::Variant,
1548 _args: &[ast::VariantArg],
1550 param_substs: Option<@param_substs>,
1551 llfndecl: ValueRef) {
1552 let _icx = push_ctxt("trans_enum_variant");
1554 trans_enum_variant_or_tuple_like_struct(
1562 pub fn trans_tuple_struct(ccx: @CrateContext,
1563 _fields: &[ast::StructField],
1564 ctor_id: ast::NodeId,
1565 param_substs: Option<@param_substs>,
1566 llfndecl: ValueRef) {
1567 let _icx = push_ctxt("trans_tuple_struct");
1569 trans_enum_variant_or_tuple_like_struct(
1577 fn trans_enum_variant_or_tuple_like_struct(ccx: @CrateContext,
1578 ctor_id: ast::NodeId,
1580 param_substs: Option<@param_substs>,
1581 llfndecl: ValueRef) {
1582 let no_substs: &[ty::t] = [];
1583 let ty_param_substs = match param_substs {
1584 Some(ref substs) => {
1585 let v: &[ty::t] = substs.tys;
1589 let v: &[ty::t] = no_substs;
1594 let ctor_ty = ty::subst_tps(ccx.tcx,
1597 ty::node_id_to_type(ccx.tcx, ctor_id));
1599 let result_ty = match ty::get(ctor_ty).sty {
1600 ty::ty_bare_fn(ref bft) => bft.sig.output,
1602 format!("trans_enum_variant_or_tuple_like_struct: \
1603 unexpected ctor return type {}",
1604 ty_to_str(ccx.tcx, ctor_ty)))
1607 let arena = TypedArena::new();
1608 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1609 param_substs, None, &arena);
1610 init_function(&fcx, false, result_ty, param_substs);
1612 let arg_tys = ty::ty_fn_args(ctor_ty);
1614 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys);
1616 let bcx = fcx.entry_bcx.get().unwrap();
1618 if !type_is_zero_size(fcx.ccx, result_ty) {
1619 let repr = adt::represent_type(ccx, result_ty);
1620 adt::trans_start_init(bcx, repr, fcx.llretptr.get().unwrap(), disr);
1621 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1622 let lldestptr = adt::trans_field_ptr(bcx,
1624 fcx.llretptr.get().unwrap(),
1627 arg_datum.store_to(bcx, lldestptr);
1631 finish_fn(&fcx, bcx);
1634 pub fn trans_enum_def(ccx: @CrateContext, enum_definition: &ast::EnumDef,
1635 id: ast::NodeId, vi: @~[@ty::VariantInfo],
1637 for &variant in enum_definition.variants.iter() {
1638 let disr_val = vi[*i].disr_val;
1641 match variant.node.kind {
1642 ast::TupleVariantKind(ref args) if args.len() > 0 => {
1643 let llfn = get_item_val(ccx, variant.node.id);
1644 trans_enum_variant(ccx, id, variant, args.as_slice(),
1645 disr_val, None, llfn);
1647 ast::TupleVariantKind(_) => {
1650 ast::StructVariantKind(struct_def) => {
1651 trans_struct_def(ccx, struct_def);
1657 pub struct TransItemVisitor {
1661 impl Visitor<()> for TransItemVisitor {
1662 fn visit_item(&mut self, i: &ast::Item, _:()) {
1663 trans_item(self.ccx, i);
1667 pub fn trans_item(ccx: @CrateContext, item: &ast::Item) {
1668 let _icx = push_ctxt("trans_item");
1670 ast::ItemFn(decl, purity, _abis, ref generics, body) => {
1671 if purity == ast::ExternFn {
1672 let llfndecl = get_item_val(ccx, item.id);
1673 foreign::trans_rust_fn_with_foreign_abi(
1674 ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
1675 } else if !generics.is_type_parameterized() {
1676 let llfn = get_item_val(ccx, item.id);
1683 item.attrs.as_slice());
1685 // Be sure to travel more than just one layer deep to catch nested
1686 // items in blocks and such.
1687 let mut v = TransItemVisitor{ ccx: ccx };
1688 v.visit_block(body, ());
1691 ast::ItemImpl(ref generics, _, _, ref ms) => {
1692 meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1694 ast::ItemMod(ref m) => {
1697 ast::ItemEnum(ref enum_definition, ref generics) => {
1698 if !generics.is_type_parameterized() {
1699 let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
1701 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
1704 ast::ItemStatic(_, m, expr) => {
1705 consts::trans_const(ccx, m, item.id);
1706 // Do static_assert checking. It can't really be done much earlier
1707 // because we need to get the value of the bool out of LLVM
1708 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1709 if m == ast::MutMutable {
1710 ccx.sess.span_fatal(expr.span,
1711 "cannot have static_assert on a mutable \
1715 let const_values = ccx.const_values.borrow();
1716 let v = const_values.get().get_copy(&item.id);
1718 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1719 ccx.sess.span_fatal(expr.span, "static assertion failed");
1724 ast::ItemForeignMod(ref foreign_mod) => {
1725 foreign::trans_foreign_mod(ccx, foreign_mod);
1727 ast::ItemStruct(struct_def, ref generics) => {
1728 if !generics.is_type_parameterized() {
1729 trans_struct_def(ccx, struct_def);
1732 ast::ItemTrait(..) => {
1733 // Inside of this trait definition, we won't be actually translating any
1734 // functions, but the trait still needs to be walked. Otherwise default
1735 // methods with items will not get translated and will cause ICE's when
1736 // metadata time comes around.
1737 let mut v = TransItemVisitor{ ccx: ccx };
1738 visit::walk_item(&mut v, item, ());
1740 _ => {/* fall through */ }
1744 pub fn trans_struct_def(ccx: @CrateContext, struct_def: @ast::StructDef) {
1745 // If this is a tuple-like struct, translate the constructor.
1746 match struct_def.ctor_id {
1747 // We only need to translate a constructor if there are fields;
1748 // otherwise this is a unit-like struct.
1749 Some(ctor_id) if struct_def.fields.len() > 0 => {
1750 let llfndecl = get_item_val(ccx, ctor_id);
1751 trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1752 ctor_id, None, llfndecl);
1754 Some(_) | None => {}
1758 // Translate a module. Doing this amounts to translating the items in the
1759 // module; there ends up being no artifact (aside from linkage names) of
1760 // separate modules in the compiled program. That's because modules exist
1761 // only as a convenience for humans working with the code, to organize names
1762 // and control visibility.
1763 pub fn trans_mod(ccx: @CrateContext, m: &ast::Mod) {
1764 let _icx = push_ctxt("trans_mod");
1765 for item in m.items.iter() {
1766 trans_item(ccx, *item);
1770 fn finish_register_fn(ccx: @CrateContext, sp: Span, sym: ~str, node_id: ast::NodeId,
1773 let mut item_symbols = ccx.item_symbols.borrow_mut();
1774 item_symbols.get().insert(node_id, sym);
1778 let reachable = ccx.reachable.borrow();
1779 if !reachable.get().contains(&node_id) {
1780 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1784 if is_entry_fn(&ccx.sess, node_id) && !ccx.sess.building_library.get() {
1785 create_entry_wrapper(ccx, sp, llfn);
1789 fn register_fn(ccx: @CrateContext,
1792 node_id: ast::NodeId,
1795 let f = match ty::get(node_type).sty {
1796 ty::ty_bare_fn(ref f) => {
1797 assert!(f.abis.is_rust() || f.abis.is_intrinsic());
1800 _ => fail!("expected bare rust fn or an intrinsic")
1803 let llfn = decl_rust_fn(ccx, false, f.sig.inputs, f.sig.output, sym);
1804 finish_register_fn(ccx, sp, sym, node_id, llfn);
1808 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1809 pub fn register_fn_llvmty(ccx: @CrateContext,
1812 node_id: ast::NodeId,
1813 cc: lib::llvm::CallConv,
1815 output: ty::t) -> ValueRef {
1816 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1818 let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty, output);
1819 finish_register_fn(ccx, sp, sym, node_id, llfn);
1823 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1824 match sess.entry_fn.get() {
1825 Some((entry_id, _)) => node_id == entry_id,
1830 // Create a _rust_main(args: ~[str]) function which will be called from the
1831 // runtime rust_start function
1832 pub fn create_entry_wrapper(ccx: @CrateContext,
1834 main_llfn: ValueRef) {
1835 let et = ccx.sess.entry_type.get().unwrap();
1837 session::EntryMain => {
1838 create_entry_fn(ccx, main_llfn, true);
1840 session::EntryStart => create_entry_fn(ccx, main_llfn, false),
1841 session::EntryNone => {} // Do nothing.
1844 fn create_entry_fn(ccx: @CrateContext,
1845 rust_main: ValueRef,
1846 use_start_lang_item: bool) {
1847 let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
1850 let llfn = decl_cdecl_fn(ccx.llmod, "main", llfty, ty::mk_nil());
1851 let llbb = "top".with_c_str(|buf| {
1853 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1856 let bld = ccx.builder.b;
1858 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1860 let (start_fn, args) = if use_start_lang_item {
1861 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1863 Err(s) => { ccx.tcx.sess.fatal(s); }
1865 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1866 get_item_val(ccx, start_def_id.node)
1868 let start_fn_type = csearch::get_type(ccx.tcx,
1870 trans_external_path(ccx, start_def_id, start_fn_type)
1874 let opaque_rust_main = "rust_main".with_c_str(|buf| {
1875 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
1880 llvm::LLVMGetParam(llfn, 0),
1881 llvm::LLVMGetParam(llfn, 1)
1886 debug!("using user-defined start fn");
1888 llvm::LLVMGetParam(llfn, 0 as c_uint),
1889 llvm::LLVMGetParam(llfn, 1 as c_uint)
1895 let result = llvm::LLVMBuildCall(bld, start_fn,
1896 args.as_ptr(), args.len() as c_uint,
1899 llvm::LLVMBuildRet(bld, result);
1904 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1905 ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
1906 match attr::first_attr_value_str_by_name(attrs, "export_name") {
1907 // Use provided name
1908 Some(name) => name.get().to_owned(),
1910 _ => ccx.tcx.map.with_path(id, |mut path| {
1911 if attr::contains_name(attrs, "no_mangle") {
1913 path.last().unwrap().to_str()
1915 // Usual name mangling
1916 mangle_exported_name(ccx, path, ty, id)
1922 pub fn get_item_val(ccx: @CrateContext, id: ast::NodeId) -> ValueRef {
1923 debug!("get_item_val(id=`{:?}`)", id);
1926 let item_vals = ccx.item_vals.borrow();
1927 item_vals.get().find_copy(&id)
1933 let mut foreign = false;
1934 let item = ccx.tcx.map.get(id);
1935 let val = match item {
1936 ast_map::NodeItem(i) => {
1937 let ty = ty::node_id_to_type(ccx.tcx, i.id);
1938 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1940 let v = match i.node {
1941 ast::ItemStatic(_, _, expr) => {
1942 // If this static came from an external crate, then
1943 // we need to get the symbol from csearch instead of
1944 // using the current crate's name/version
1945 // information in the hash of the symbol
1946 debug!("making {}", sym);
1947 let (sym, is_local) = {
1948 let external_srcs = ccx.external_srcs
1950 match external_srcs.get().find(&i.id) {
1952 debug!("but found in other crate...");
1953 (csearch::get_symbol(ccx.sess.cstore,
1960 // We need the translated value here, because for enums the
1961 // LLVM type is not fully determined by the Rust type.
1962 let (v, inlineable) = consts::const_expr(ccx, expr, is_local);
1964 let mut const_values = ccx.const_values
1966 const_values.get().insert(id, v);
1968 let mut inlineable = inlineable;
1971 let llty = llvm::LLVMTypeOf(v);
1972 let g = sym.with_c_str(|buf| {
1973 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
1977 let reachable = ccx.reachable.borrow();
1978 if !reachable.get().contains(&id) {
1979 lib::llvm::SetLinkage(
1981 lib::llvm::InternalLinkage);
1985 // Apply the `unnamed_addr` attribute if
1987 if attr::contains_name(i.attrs.as_slice(),
1988 "address_insignificant"){
1991 ccx.reachable.borrow();
1992 if reachable.get().contains(&id) {
1993 ccx.sess.span_bug(i.span,
1994 "insignificant static is \
1998 lib::llvm::SetUnnamedAddr(g, true);
2000 // This is a curious case where we must make
2001 // all of these statics inlineable. If a
2002 // global is tagged as
2003 // address_insignificant, then LLVM won't
2004 // coalesce globals unless they have an
2005 // internal linkage type. This means that
2006 // external crates cannot use this global.
2007 // This is a problem for things like inner
2008 // statics in generic functions, because the
2009 // function will be inlined into another
2010 // crate and then attempt to link to the
2011 // static in the original crate, only to
2012 // find that it's not there. On the other
2013 // side of inlininig, the crates knows to
2014 // not declare this static as
2015 // available_externally (because it isn't)
2019 if attr::contains_name(i.attrs.as_slice(),
2021 lib::llvm::set_thread_local(g, true);
2025 debug!("{} not inlined", sym);
2026 let mut non_inlineable_statics =
2027 ccx.non_inlineable_statics
2029 non_inlineable_statics.get().insert(id);
2032 let mut item_symbols = ccx.item_symbols
2034 item_symbols.get().insert(i.id, sym);
2039 ast::ItemFn(_, purity, _, _, _) => {
2040 let llfn = if purity != ast::ExternFn {
2041 register_fn(ccx, i.span, sym, i.id, ty)
2043 foreign::register_rust_fn_with_foreign_abi(ccx,
2048 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2052 _ => fail!("get_item_val: weird result in table")
2055 match attr::first_attr_value_str_by_name(i.attrs
2058 Some(sect) => unsafe {
2059 sect.get().with_c_str(|buf| {
2060 llvm::LLVMSetSection(v, buf);
2069 ast_map::NodeTraitMethod(trait_method) => {
2070 debug!("get_item_val(): processing a NodeTraitMethod");
2071 match *trait_method {
2072 ast::Required(_) => {
2073 ccx.sess.bug("unexpected variant: required trait method in \
2076 ast::Provided(m) => {
2077 register_method(ccx, id, m)
2082 ast_map::NodeMethod(m) => {
2083 register_method(ccx, id, m)
2086 ast_map::NodeForeignItem(ni) => {
2087 let ty = ty::node_id_to_type(ccx.tcx, ni.id);
2091 ast::ForeignItemFn(..) => {
2092 let abis = ccx.tcx.map.get_foreign_abis(id);
2093 foreign::register_foreign_item_fn(ccx, abis, ni)
2095 ast::ForeignItemStatic(..) => {
2096 // Treat the crate map static specially in order to
2097 // a weak-linkage-like functionality where it's
2098 // dynamically resolved at runtime. If we're
2099 // building a library, then we declare the static
2100 // with weak linkage, but if we're building a
2101 // library then we've already declared the crate map
2102 // so use that instead.
2103 if attr::contains_name(ni.attrs.as_slice(),
2105 if ccx.sess.building_library.get() {
2106 let s = "_rust_crate_map_toplevel";
2108 s.with_c_str(|buf| {
2109 let ty = type_of(ccx, ty);
2110 llvm::LLVMAddGlobal(ccx.llmod,
2115 lib::llvm::SetLinkage(g,
2116 lib::llvm::ExternalWeakLinkage);
2122 let ident = foreign::link_name(ni);
2124 ident.get().with_c_str(|buf| {
2125 let ty = type_of(ccx, ty);
2126 llvm::LLVMAddGlobal(ccx.llmod,
2135 ast_map::NodeVariant(ref v) => {
2138 ast::TupleVariantKind(ref args) => {
2139 assert!(args.len() != 0u);
2140 let ty = ty::node_id_to_type(ccx.tcx, id);
2141 let parent = ccx.tcx.map.get_parent(id);
2142 let enm = ccx.tcx.map.expect_item(parent);
2143 let sym = exported_name(ccx,
2146 enm.attrs.as_slice());
2148 llfn = match enm.node {
2149 ast::ItemEnum(_, _) => {
2150 register_fn(ccx, (*v).span, sym, id, ty)
2152 _ => fail!("NodeVariant, shouldn't happen")
2155 ast::StructVariantKind(_) => {
2156 fail!("struct variant kind unexpected in get_item_val")
2159 set_inline_hint(llfn);
2163 ast_map::NodeStructCtor(struct_def) => {
2164 // Only register the constructor if this is a tuple-like struct.
2165 match struct_def.ctor_id {
2167 ccx.tcx.sess.bug("attempt to register a constructor of \
2168 a non-tuple-like struct")
2171 let parent = ccx.tcx.map.get_parent(id);
2172 let struct_item = ccx.tcx.map.expect_item(parent);
2173 let ty = ty::node_id_to_type(ccx.tcx, ctor_id);
2174 let sym = exported_name(ccx,
2179 let llfn = register_fn(ccx, struct_item.span,
2181 set_inline_hint(llfn);
2188 ccx.sess.bug(format!("get_item_val(): unexpected variant: {:?}",
2193 // foreign items (extern fns and extern statics) don't have internal
2194 // linkage b/c that doesn't quite make sense. Otherwise items can
2195 // have internal linkage if they're not reachable.
2197 let reachable = ccx.reachable.borrow();
2198 if !foreign && !reachable.get().contains(&id) {
2199 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2203 let mut item_vals = ccx.item_vals.borrow_mut();
2204 item_vals.get().insert(id, val);
2210 fn register_method(ccx: @CrateContext, id: ast::NodeId,
2211 m: &ast::Method) -> ValueRef {
2212 let mty = ty::node_id_to_type(ccx.tcx, id);
2214 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2216 let llfn = register_fn(ccx, m.span, sym, id, mty);
2217 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2221 pub fn vp2i(cx: &Block, v: ValueRef) -> ValueRef {
2223 return PtrToInt(cx, v, ccx.int_type);
2226 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2228 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2233 ($intrinsics:ident, $name:expr, $args:expr, $ret:expr) => ({
2235 // HACK(eddyb) dummy output type, shouln't affect anything.
2236 let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret), ty::mk_nil());
2237 $intrinsics.insert(name, f);
2241 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2242 let i8p = Type::i8p();
2243 let mut intrinsics = HashMap::new();
2245 ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i32",
2246 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2247 ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i64",
2248 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2249 ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i32",
2250 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2251 ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i64",
2252 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2253 ifn!(intrinsics, "llvm.memset.p0i8.i32",
2254 [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2255 ifn!(intrinsics, "llvm.memset.p0i8.i64",
2256 [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2258 ifn!(intrinsics, "llvm.trap", [], Type::void());
2259 ifn!(intrinsics, "llvm.debugtrap", [], Type::void());
2260 ifn!(intrinsics, "llvm.frameaddress", [Type::i32()], i8p);
2262 ifn!(intrinsics, "llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2263 ifn!(intrinsics, "llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2264 ifn!(intrinsics, "llvm.pow.f32", [Type::f32(), Type::f32()], Type::f32());
2265 ifn!(intrinsics, "llvm.pow.f64", [Type::f64(), Type::f64()], Type::f64());
2267 ifn!(intrinsics, "llvm.sqrt.f32", [Type::f32()], Type::f32());
2268 ifn!(intrinsics, "llvm.sqrt.f64", [Type::f64()], Type::f64());
2269 ifn!(intrinsics, "llvm.sin.f32", [Type::f32()], Type::f32());
2270 ifn!(intrinsics, "llvm.sin.f64", [Type::f64()], Type::f64());
2271 ifn!(intrinsics, "llvm.cos.f32", [Type::f32()], Type::f32());
2272 ifn!(intrinsics, "llvm.cos.f64", [Type::f64()], Type::f64());
2273 ifn!(intrinsics, "llvm.exp.f32", [Type::f32()], Type::f32());
2274 ifn!(intrinsics, "llvm.exp.f64", [Type::f64()], Type::f64());
2275 ifn!(intrinsics, "llvm.exp2.f32", [Type::f32()], Type::f32());
2276 ifn!(intrinsics, "llvm.exp2.f64", [Type::f64()], Type::f64());
2277 ifn!(intrinsics, "llvm.log.f32", [Type::f32()], Type::f32());
2278 ifn!(intrinsics, "llvm.log.f64", [Type::f64()], Type::f64());
2279 ifn!(intrinsics, "llvm.log10.f32",[Type::f32()], Type::f32());
2280 ifn!(intrinsics, "llvm.log10.f64",[Type::f64()], Type::f64());
2281 ifn!(intrinsics, "llvm.log2.f32", [Type::f32()], Type::f32());
2282 ifn!(intrinsics, "llvm.log2.f64", [Type::f64()], Type::f64());
2284 ifn!(intrinsics, "llvm.fma.f32", [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2285 ifn!(intrinsics, "llvm.fma.f64", [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2287 ifn!(intrinsics, "llvm.fabs.f32", [Type::f32()], Type::f32());
2288 ifn!(intrinsics, "llvm.fabs.f64", [Type::f64()], Type::f64());
2289 ifn!(intrinsics, "llvm.copysign.f32", [Type::f32(), Type::f32()], Type::f32());
2290 ifn!(intrinsics, "llvm.copysign.f64", [Type::f64(), Type::f64()], Type::f64());
2292 ifn!(intrinsics, "llvm.floor.f32",[Type::f32()], Type::f32());
2293 ifn!(intrinsics, "llvm.floor.f64",[Type::f64()], Type::f64());
2294 ifn!(intrinsics, "llvm.ceil.f32", [Type::f32()], Type::f32());
2295 ifn!(intrinsics, "llvm.ceil.f64", [Type::f64()], Type::f64());
2296 ifn!(intrinsics, "llvm.trunc.f32",[Type::f32()], Type::f32());
2297 ifn!(intrinsics, "llvm.trunc.f64",[Type::f64()], Type::f64());
2299 ifn!(intrinsics, "llvm.rint.f32", [Type::f32()], Type::f32());
2300 ifn!(intrinsics, "llvm.rint.f64", [Type::f64()], Type::f64());
2301 ifn!(intrinsics, "llvm.nearbyint.f32", [Type::f32()], Type::f32());
2302 ifn!(intrinsics, "llvm.nearbyint.f64", [Type::f64()], Type::f64());
2303 ifn!(intrinsics, "llvm.round.f32", [Type::f32()], Type::f32());
2304 ifn!(intrinsics, "llvm.round.f64", [Type::f64()], Type::f64());
2306 ifn!(intrinsics, "llvm.ctpop.i8", [Type::i8()], Type::i8());
2307 ifn!(intrinsics, "llvm.ctpop.i16",[Type::i16()], Type::i16());
2308 ifn!(intrinsics, "llvm.ctpop.i32",[Type::i32()], Type::i32());
2309 ifn!(intrinsics, "llvm.ctpop.i64",[Type::i64()], Type::i64());
2311 ifn!(intrinsics, "llvm.ctlz.i8", [Type::i8() , Type::i1()], Type::i8());
2312 ifn!(intrinsics, "llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2313 ifn!(intrinsics, "llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2314 ifn!(intrinsics, "llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2316 ifn!(intrinsics, "llvm.cttz.i8", [Type::i8() , Type::i1()], Type::i8());
2317 ifn!(intrinsics, "llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2318 ifn!(intrinsics, "llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2319 ifn!(intrinsics, "llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2321 ifn!(intrinsics, "llvm.bswap.i16",[Type::i16()], Type::i16());
2322 ifn!(intrinsics, "llvm.bswap.i32",[Type::i32()], Type::i32());
2323 ifn!(intrinsics, "llvm.bswap.i64",[Type::i64()], Type::i64());
2325 ifn!(intrinsics, "llvm.sadd.with.overflow.i8",
2326 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2327 ifn!(intrinsics, "llvm.sadd.with.overflow.i16",
2328 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2329 ifn!(intrinsics, "llvm.sadd.with.overflow.i32",
2330 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2331 ifn!(intrinsics, "llvm.sadd.with.overflow.i64",
2332 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2334 ifn!(intrinsics, "llvm.uadd.with.overflow.i8",
2335 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2336 ifn!(intrinsics, "llvm.uadd.with.overflow.i16",
2337 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2338 ifn!(intrinsics, "llvm.uadd.with.overflow.i32",
2339 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2340 ifn!(intrinsics, "llvm.uadd.with.overflow.i64",
2341 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2343 ifn!(intrinsics, "llvm.ssub.with.overflow.i8",
2344 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2345 ifn!(intrinsics, "llvm.ssub.with.overflow.i16",
2346 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2347 ifn!(intrinsics, "llvm.ssub.with.overflow.i32",
2348 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2349 ifn!(intrinsics, "llvm.ssub.with.overflow.i64",
2350 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2352 ifn!(intrinsics, "llvm.usub.with.overflow.i8",
2353 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2354 ifn!(intrinsics, "llvm.usub.with.overflow.i16",
2355 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2356 ifn!(intrinsics, "llvm.usub.with.overflow.i32",
2357 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2358 ifn!(intrinsics, "llvm.usub.with.overflow.i64",
2359 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2361 ifn!(intrinsics, "llvm.smul.with.overflow.i8",
2362 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2363 ifn!(intrinsics, "llvm.smul.with.overflow.i16",
2364 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2365 ifn!(intrinsics, "llvm.smul.with.overflow.i32",
2366 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2367 ifn!(intrinsics, "llvm.smul.with.overflow.i64",
2368 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2370 ifn!(intrinsics, "llvm.umul.with.overflow.i8",
2371 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2372 ifn!(intrinsics, "llvm.umul.with.overflow.i16",
2373 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2374 ifn!(intrinsics, "llvm.umul.with.overflow.i32",
2375 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2376 ifn!(intrinsics, "llvm.umul.with.overflow.i64",
2377 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2379 ifn!(intrinsics, "llvm.expect.i1", [Type::i1(), Type::i1()], Type::i1());
2384 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2385 ifn!(intrinsics, "llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2387 "llvm.dbg.value", [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2390 pub fn trap(bcx: &Block) {
2391 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2392 Some(&x) => { Call(bcx, x, [], []); },
2393 _ => bcx.sess().bug("unbound llvm.trap in trap")
2397 pub fn decl_gc_metadata(ccx: &CrateContext, llmod_id: &str) {
2398 if !ccx.sess.opts.gc || !ccx.uses_gc {
2402 let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2403 let gc_metadata = gc_metadata_name.with_c_str(|buf| {
2405 llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2409 llvm::LLVMSetGlobalConstant(gc_metadata, True);
2410 lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2412 let mut module_data = ccx.module_data.borrow_mut();
2413 module_data.get().insert(~"_gc_module_metadata", gc_metadata);
2417 pub fn create_module_map(ccx: &CrateContext) -> (ValueRef, uint) {
2418 let str_slice_type = Type::struct_([Type::i8p(), ccx.int_type], false);
2419 let elttype = Type::struct_([str_slice_type, ccx.int_type], false);
2421 let module_data = ccx.module_data.borrow();
2422 Type::array(&elttype, module_data.get().len() as u64)
2424 let map = "_rust_mod_map".with_c_str(|buf| {
2426 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2429 lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2430 let mut elts: ~[ValueRef] = ~[];
2432 // This is not ideal, but the borrow checker doesn't
2433 // like the multiple borrows. At least, it doesn't
2434 // like them on the current snapshot. (2013-06-14)
2437 let module_data = ccx.module_data.borrow();
2438 for (k, _) in module_data.get().iter() {
2439 keys.push(k.clone());
2444 for key in keys.iter() {
2445 let llstrval = C_str_slice(ccx, token::intern_and_get_ident(*key));
2446 let module_data = ccx.module_data.borrow();
2447 let val = *module_data.get().find_equiv(key).unwrap();
2448 let v_ptr = p2i(ccx, val);
2449 let elt = C_struct([
2456 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2458 return (map, keys.len())
2461 pub fn symname(name: &str, hash: &str, vers: &str) -> ~str {
2462 let path = [PathName(token::intern(name))];
2463 link::exported_name(ast_map::Values(path.iter()).chain(None), hash, vers)
2466 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2467 llmod: ModuleRef) -> (~str, ValueRef) {
2468 let targ_cfg = sess.targ_cfg;
2469 let int_type = Type::int(targ_cfg.arch);
2470 let mut n_subcrates = 1;
2471 let cstore = sess.cstore;
2472 while cstore.have_crate_data(n_subcrates) { n_subcrates += 1; }
2473 let is_top = !sess.building_library.get() || sess.opts.cg.gen_crate_map;
2474 let sym_name = if is_top {
2475 ~"_rust_crate_map_toplevel"
2477 symname("_rust_crate_map_" + mapmeta.crateid.name,
2478 mapmeta.crate_hash.as_str(),
2479 mapmeta.crateid.version_or_default())
2482 let slicetype = Type::struct_([int_type, int_type], false);
2483 let maptype = Type::struct_([
2484 Type::i32(), // version
2485 slicetype, // child modules
2486 slicetype, // sub crate-maps
2487 int_type.ptr_to(), // event loop factory
2489 let map = sym_name.with_c_str(|buf| {
2491 llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2494 lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2496 // On windows we'd like to export the toplevel cratemap
2497 // such that we can find it from libstd.
2498 if targ_cfg.os == OsWin32 && is_top {
2499 unsafe { llvm::LLVMRustSetDLLExportStorageClass(map) }
2502 return (sym_name, map);
2505 pub fn fill_crate_map(ccx: @CrateContext, map: ValueRef) {
2506 let mut subcrates: ~[ValueRef] = ~[];
2508 let cstore = ccx.sess.cstore;
2509 while cstore.have_crate_data(i) {
2510 let cdata = cstore.get_crate_data(i);
2511 let nm = symname(format!("_rust_crate_map_{}", cdata.name),
2512 cstore.get_crate_hash(i).as_str(),
2513 cstore.get_crate_id(i).version_or_default());
2514 let cr = nm.with_c_str(|buf| {
2516 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2519 subcrates.push(p2i(ccx, cr));
2522 let event_loop_factory = match ccx.tcx.lang_items.event_loop_factory() {
2523 Some(did) => unsafe {
2525 llvm::LLVMConstPointerCast(get_item_val(ccx, did.node),
2526 ccx.int_type.ptr_to().to_ref())
2528 let name = csearch::get_symbol(ccx.sess.cstore, did);
2529 let global = name.with_c_str(|buf| {
2530 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2535 None => C_null(ccx.int_type.ptr_to())
2538 let maptype = Type::array(&ccx.int_type, subcrates.len() as u64);
2539 let vec_elements = "_crate_map_child_vectors".with_c_str(|buf| {
2540 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2542 lib::llvm::SetLinkage(vec_elements, lib::llvm::InternalLinkage);
2544 llvm::LLVMSetInitializer(vec_elements, C_array(ccx.int_type, subcrates));
2545 let (mod_map, mod_count) = create_module_map(ccx);
2547 llvm::LLVMSetInitializer(map, C_struct(
2551 C_uint(ccx, mod_count)
2554 p2i(ccx, vec_elements),
2555 C_uint(ccx, subcrates.len())
2562 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2563 -> encoder::EncodeParams<'r> {
2565 let diag = cx.sess.diagnostic();
2566 let item_symbols = &cx.item_symbols;
2567 let link_meta = &cx.link_meta;
2568 encoder::EncodeParams {
2571 reexports2: cx.exp_map2,
2572 item_symbols: item_symbols,
2573 non_inlineable_statics: &cx.non_inlineable_statics,
2574 link_meta: link_meta,
2575 cstore: cx.sess.cstore,
2576 encode_inlined_item: ie,
2580 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> ~[u8] {
2583 if !cx.sess.building_library.get() {
2587 let encode_inlined_item: encoder::EncodeInlinedItem =
2588 |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii, cx.maps);
2590 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2591 let metadata = encoder::encode_metadata(encode_parms, krate);
2592 let compressed = encoder::metadata_encoding_version +
2593 flate::deflate_bytes(metadata).as_slice();
2594 let llmeta = C_bytes(compressed);
2595 let llconst = C_struct([llmeta], false);
2596 let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2597 cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2598 let llglobal = name.with_c_str(|buf| {
2600 llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2604 llvm::LLVMSetInitializer(llglobal, llconst);
2605 cx.sess.targ_cfg.target_strs.meta_sect_name.with_c_str(|buf| {
2606 llvm::LLVMSetSection(llglobal, buf)
2612 pub fn trans_crate(sess: session::Session,
2614 analysis: &CrateAnalysis,
2615 output: &OutputFilenames) -> CrateTranslation {
2616 // Before we touch LLVM, make sure that multithreading is enabled.
2618 use sync::one::{Once, ONCE_INIT};
2619 static mut INIT: Once = ONCE_INIT;
2620 static mut POISONED: bool = false;
2622 if llvm::LLVMStartMultithreaded() != 1 {
2623 // use an extra bool to make sure that all future usage of LLVM
2624 // cannot proceed despite the Once not running more than once.
2630 sess.bug("couldn't enable multi-threaded LLVM");
2634 let link_meta = link::build_link_meta(&krate, output);
2636 // Append ".rs" to crate name as LLVM module identifier.
2638 // LLVM code generator emits a ".file filename" directive
2639 // for ELF backends. Value of the "filename" is set as the
2640 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2641 // crashes if the module identifer is same as other symbols
2642 // such as a function name in the module.
2643 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2644 let llmod_id = link_meta.crateid.name + ".rs";
2646 let ccx = @CrateContext::new(sess,
2653 analysis.reachable);
2655 let _icx = push_ctxt("text");
2656 trans_mod(ccx, &krate.module);
2659 decl_gc_metadata(ccx, llmod_id);
2660 fill_crate_map(ccx, ccx.crate_map);
2662 // win32: wart with exporting crate_map symbol
2663 // We set the crate map (_rust_crate_map_toplevel) to use dll_export
2664 // linkage but that ends up causing the linker to look for a
2665 // __rust_crate_map_toplevel symbol (extra underscore) which it will
2666 // subsequently fail to find. So to mitigate that we just introduce
2667 // an alias from the symbol it expects to the one that actually exists.
2668 if ccx.sess.targ_cfg.os == OsWin32 && !ccx.sess.building_library.get() {
2670 let maptype = val_ty(ccx.crate_map).to_ref();
2672 "__rust_crate_map_toplevel".with_c_str(|buf| {
2674 llvm::LLVMAddAlias(ccx.llmod, maptype,
2675 ccx.crate_map, buf);
2680 glue::emit_tydescs(ccx);
2681 if ccx.sess.opts.debuginfo {
2682 debuginfo::finalize(ccx);
2685 // Translate the metadata.
2686 let metadata = write_metadata(ccx, &krate);
2687 if ccx.sess.trans_stats() {
2688 println!("--- trans stats ---");
2689 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2690 println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2691 println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2692 println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2694 println!("n_fns: {}", ccx.stats.n_fns.get());
2695 println!("n_monos: {}", ccx.stats.n_monos.get());
2696 println!("n_inlines: {}", ccx.stats.n_inlines.get());
2697 println!("n_closures: {}", ccx.stats.n_closures.get());
2698 println!("fn stats:");
2700 let mut fn_stats = ccx.stats.fn_stats.borrow_mut();
2701 fn_stats.get().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2702 insns_b.cmp(&insns_a)
2704 for tuple in fn_stats.get().iter() {
2706 (ref name, ms, insns) => {
2707 println!("{} insns, {} ms, {}", insns, ms, *name);
2713 if ccx.sess.count_llvm_insns() {
2714 let llvm_insns = ccx.stats.llvm_insns.borrow();
2715 for (k, v) in llvm_insns.get().iter() {
2716 println!("{:7u} {}", *v, *k);
2720 let llcx = ccx.llcx;
2721 let link_meta = ccx.link_meta.clone();
2722 let llmod = ccx.llmod;
2724 let mut reachable = {
2725 let reachable_map = ccx.reachable.borrow();
2726 reachable_map.get().iter().filter_map(|id| {
2727 let item_symbols = ccx.item_symbols.borrow();
2728 item_symbols.get().find(id).map(|s| s.to_owned())
2732 // Make sure that some other crucial symbols are not eliminated from the
2733 // module. This includes the main function, the crate map (used for debug
2734 // log settings and I/O), and finally the curious rust_stack_exhausted
2735 // symbol. This symbol is required for use by the libmorestack library that
2736 // we link in, so we must ensure that this symbol is not internalized (if
2737 // defined in the crate).
2738 reachable.push(ccx.crate_map_name.to_owned());
2739 reachable.push(~"main");
2740 reachable.push(~"rust_stack_exhausted");
2741 reachable.push(~"rust_eh_personality"); // referenced from .eh_frame section on some platforms
2742 reachable.push(~"rust_eh_personality_catch"); // referenced from rt/rust_try.ll
2744 return CrateTranslation {
2748 metadata_module: ccx.metadata_llmod,
2750 reachable: reachable,