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, NoDebugInfo, FullDebugInfo};
32 use driver::driver::OutputFilenames;
33 use driver::driver::{CrateAnalysis, CrateTranslation};
34 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
35 use lib::llvm::{llvm, Vector};
37 use metadata::{csearch, encoder};
38 use middle::astencode;
39 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
40 use middle::lang_items::{MallocFnLangItem, ClosureExchangeMallocFnLangItem};
41 use middle::trans::_match;
42 use middle::trans::adt;
43 use middle::trans::build::*;
44 use middle::trans::builder::{Builder, noname};
45 use middle::trans::callee;
46 use middle::trans::cleanup;
47 use middle::trans::cleanup::CleanupMethods;
48 use middle::trans::common::*;
49 use middle::trans::consts;
50 use middle::trans::controlflow;
51 use middle::trans::datum;
52 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
53 use middle::trans::debuginfo;
54 use middle::trans::expr;
55 use middle::trans::foreign;
56 use middle::trans::glue;
57 use middle::trans::inline;
58 use middle::trans::machine;
59 use middle::trans::machine::{llalign_of_min, llsize_of};
60 use middle::trans::meth;
61 use middle::trans::monomorphize;
62 use middle::trans::tvec;
63 use middle::trans::type_::Type;
64 use middle::trans::type_of;
65 use middle::trans::type_of::*;
66 use middle::trans::value::Value;
69 use util::common::indenter;
70 use util::ppaux::{Repr, ty_to_str};
71 use util::sha2::Sha256;
72 use util::nodemap::NodeMap;
74 use arena::TypedArena;
75 use std::c_str::ToCStr;
76 use std::cell::{Cell, RefCell};
77 use std::libc::c_uint;
79 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic};
80 use syntax::ast_map::PathName;
81 use syntax::ast_util::{local_def, is_local};
82 use syntax::attr::AttrMetaMethods;
84 use syntax::codemap::Span;
85 use syntax::parse::token::InternedString;
86 use syntax::parse::token;
87 use syntax::visit::Visitor;
89 use syntax::{ast, ast_util, ast_map};
93 local_data_key!(task_local_insn_key: Vec<&'static str> )
95 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
96 local_data::get(task_local_insn_key, |c| {
98 Some(ctx) => blk(ctx.as_slice()),
104 pub fn init_insn_ctxt() {
105 local_data::set(task_local_insn_key, Vec::new());
108 pub struct _InsnCtxt { _x: () }
111 impl Drop for _InsnCtxt {
113 local_data::modify(task_local_insn_key, |c| {
122 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
123 debug!("new InsnCtxt: {}", s);
124 local_data::modify(task_local_insn_key, |c| {
133 pub struct StatRecorder<'a> {
134 ccx: &'a CrateContext,
140 impl<'a> StatRecorder<'a> {
141 pub fn new(ccx: &'a CrateContext, name: ~str) -> StatRecorder<'a> {
142 let start = if ccx.sess().trans_stats() {
143 time::precise_time_ns()
147 let istart = ccx.stats.n_llvm_insns.get();
158 impl<'a> Drop for StatRecorder<'a> {
160 if self.ccx.sess().trans_stats() {
161 let end = time::precise_time_ns();
162 let elapsed = ((end - self.start) / 1_000_000) as uint;
163 let iend = self.ccx.stats.n_llvm_insns.get();
164 self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
166 iend - self.istart));
167 self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
168 // Reset LLVM insn count to avoid compound costs.
169 self.ccx.stats.n_llvm_insns.set(self.istart);
174 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
175 fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv,
176 ty: Type, output: ty::t) -> ValueRef {
177 let llfn: ValueRef = name.with_c_str(|buf| {
179 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
183 match ty::get(output).sty {
184 // functions returning bottom may unwind, but can never return normally
187 llvm::LLVMAddFunctionAttr(llfn, lib::llvm::NoReturnAttribute as c_uint)
190 // `~` pointer return values never alias because ownership is transferred
191 // FIXME #6750 ~Trait cannot be directly marked as
192 // noalias because the actual object pointer is nested.
193 ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
194 ty::ty_vec(_, ty::vstore_uniq) | ty::ty_str(ty::vstore_uniq) => {
196 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
202 lib::llvm::SetFunctionCallConv(llfn, cc);
203 // Function addresses in Rust are never significant, allowing functions to be merged.
204 lib::llvm::SetUnnamedAddr(llfn, true);
209 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
210 pub fn decl_cdecl_fn(llmod: ModuleRef,
213 output: ty::t) -> ValueRef {
214 decl_fn(llmod, name, lib::llvm::CCallConv, ty, output)
217 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
218 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef,
219 name: &str, cc: lib::llvm::CallConv,
220 ty: Type, output: ty::t) -> ValueRef {
221 match externs.find_equiv(&name) {
222 Some(n) => return *n,
225 let f = decl_fn(llmod, name, cc, ty, output);
226 externs.insert(name.to_owned(), f);
230 fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
231 name: &str, did: ast::DefId) -> ValueRef {
232 match ccx.externs.borrow().find_equiv(&name) {
233 Some(n) => return *n,
237 let f = decl_rust_fn(ccx, false, inputs, output, name);
238 csearch::get_item_attrs(&ccx.sess().cstore, did, |meta_items| {
239 set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).collect::<~[_]>(), f)
242 ccx.externs.borrow_mut().insert(name.to_owned(), f);
246 pub fn decl_rust_fn(ccx: &CrateContext, has_env: bool,
247 inputs: &[ty::t], output: ty::t,
248 name: &str) -> ValueRef {
249 use middle::ty::{BrAnon, ReLateBound};
251 let llfty = type_of_rust_fn(ccx, has_env, inputs, output);
252 let llfn = decl_cdecl_fn(ccx.llmod, name, llfty, output);
254 let uses_outptr = type_of::return_uses_outptr(ccx, output);
255 let offset = if uses_outptr { 1 } else { 0 };
256 let offset = if has_env { offset + 1 } else { offset };
258 for (i, &arg_ty) in inputs.iter().enumerate() {
259 let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
260 match ty::get(arg_ty).sty {
261 // `~` pointer parameters never alias because ownership is transferred
262 // FIXME #6750 ~Trait cannot be directly marked as
263 // noalias because the actual object pointer is nested.
264 ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
265 ty::ty_vec(_, ty::vstore_uniq) | ty::ty_str(ty::vstore_uniq) |
266 ty::ty_closure(~ty::ClosureTy {sigil: ast::OwnedSigil, ..}) => {
268 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
271 // When a reference in an argument has no named lifetime, it's
272 // impossible for that reference to escape this function(ie, be
274 ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
275 debug!("marking argument of {} as nocapture because of anonymous lifetime", name);
277 llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
281 // For non-immediate arguments the callee gets its own copy of
282 // the value on the stack, so there are no aliases
283 if !type_is_immediate(ccx, arg_ty) {
285 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
286 llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
293 // The out pointer will never alias with any other pointers, as the object only exists at a
294 // language level after the call. It can also be tagged with SRet to indicate that it is
295 // guaranteed to point to a usable block of memory for the type.
298 let outptr = llvm::LLVMGetParam(llfn, 0);
299 llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
300 llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
307 pub fn decl_internal_rust_fn(ccx: &CrateContext, has_env: bool,
308 inputs: &[ty::t], output: ty::t,
309 name: &str) -> ValueRef {
310 let llfn = decl_rust_fn(ccx, has_env, inputs, output, name);
311 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
315 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
316 name: &str, ty: Type) -> ValueRef {
317 match externs.find_equiv(&name) {
318 Some(n) => return *n,
322 let c = name.with_c_str(|buf| {
323 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
325 externs.insert(name.to_owned(), c);
330 // Returns a pointer to the body for the box. The box may be an opaque
331 // box. The result will be casted to the type of body_t, if it is statically
333 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
334 let _icx = push_ctxt("at_box_body");
336 let ty = Type::at_box(ccx, type_of(ccx, body_t));
337 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
338 GEPi(bcx, boxptr, [0u, abi::box_field_body])
341 // malloc_raw_dyn: allocates a box to contain a given type, but with a
342 // potentially dynamic size.
343 pub fn malloc_raw_dyn<'a>(
349 let _icx = push_ctxt("malloc_raw");
352 fn require_alloc_fn(bcx: &Block, t: ty::t, it: LangItem) -> ast::DefId {
353 let li = &bcx.tcx().lang_items;
354 match li.require(it) {
357 bcx.sess().fatal(format!("allocation of `{}` {}",
358 bcx.ty_to_str(t), s));
363 if heap == heap_exchange {
364 let llty_value = type_of::type_of(ccx, t);
367 let r = callee::trans_lang_call(
369 require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
372 rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
374 // we treat ~fn as @ here, which isn't ideal
375 let langcall = match heap {
377 require_alloc_fn(bcx, t, MallocFnLangItem)
379 heap_exchange_closure => {
380 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem)
382 _ => fail!("heap_exchange already handled")
385 // Grab the TypeRef type of box_ptr_ty.
386 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
387 let llty = type_of(ccx, box_ptr_ty);
388 let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
391 let drop_glue = glue::get_drop_glue(ccx, t);
392 let r = callee::trans_lang_call(
396 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
401 rslt(r.bcx, PointerCast(r.bcx, r.val, llty))
405 // malloc_raw: expects an unboxed type and returns a pointer to
406 // enough space for a box of that type. This includes a rust_opaque_box
408 pub fn malloc_raw<'a>(bcx: &'a Block<'a>, t: ty::t, heap: heap)
410 let ty = type_of(bcx.ccx(), t);
411 let size = llsize_of(bcx.ccx(), ty);
412 malloc_raw_dyn(bcx, t, heap, size)
415 pub struct MallocResult<'a> {
421 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a smart
422 // pointer, and pulls out the body
423 pub fn malloc_general_dyn<'a>(
428 -> MallocResult<'a> {
429 assert!(heap != heap_exchange);
430 let _icx = push_ctxt("malloc_general");
431 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
432 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
441 pub fn malloc_general<'a>(bcx: &'a Block<'a>, t: ty::t, heap: heap)
442 -> MallocResult<'a> {
443 let ty = type_of(bcx.ccx(), t);
444 assert!(heap != heap_exchange);
445 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
448 // Type descriptor and type glue stuff
450 pub fn get_tydesc_simple(ccx: &CrateContext, t: ty::t) -> ValueRef {
451 get_tydesc(ccx, t).tydesc
454 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> @tydesc_info {
455 match ccx.tydescs.borrow().find(&t) {
456 Some(&inf) => return inf,
460 ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
461 let inf = glue::declare_tydesc(ccx, t);
463 ccx.tydescs.borrow_mut().insert(t, inf);
467 pub fn set_optimize_for_size(f: ValueRef) {
468 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
471 pub fn set_no_inline(f: ValueRef) {
472 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
475 pub fn set_no_unwind(f: ValueRef) {
476 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
479 // Tell LLVM to emit the information necessary to unwind the stack for the
481 pub fn set_uwtable(f: ValueRef) {
482 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
485 pub fn set_inline_hint(f: ValueRef) {
486 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
489 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
491 // Set the inline hint if there is one
492 match find_inline_attr(attrs) {
493 InlineHint => set_inline_hint(llfn),
494 InlineAlways => set_always_inline(llfn),
495 InlineNever => set_no_inline(llfn),
496 InlineNone => { /* fallthrough */ }
499 // Add the no-split-stack attribute if requested
500 if contains_name(attrs, "no_split_stack") {
501 set_no_split_stack(llfn);
504 if contains_name(attrs, "cold") {
505 unsafe { llvm::LLVMAddColdAttribute(llfn) }
509 pub fn set_always_inline(f: ValueRef) {
510 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
513 pub fn set_no_split_stack(f: ValueRef) {
514 "no-split-stack".with_c_str(|buf| {
515 unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
519 // Double-check that we never ask LLVM to declare the same symbol twice. It
520 // silently mangles such symbols, breaking our linkage model.
521 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) {
522 if ccx.all_llvm_symbols.borrow().contains(&sym) {
523 ccx.sess().bug(~"duplicate LLVM symbol: " + sym);
525 ccx.all_llvm_symbols.borrow_mut().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: Vec::from_slice(substs),
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);
563 get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod, name,
564 lib::llvm::CCallConv, llty, ty::mk_nil())
568 // Structural comparison: a rather involved form of glue.
569 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
570 if cx.sess().opts.cg.save_temps {
573 llvm::LLVMSetValueName(v, buf)
580 // Used only for creating scalar comparison glue.
581 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
583 // NB: This produces an i1, not a Rust bool (i8).
584 pub fn compare_scalar_types<'a>(
591 let f = |a| rslt(cx, compare_scalar_values(cx, lhs, rhs, a, op));
593 match ty::get(t).sty {
594 ty::ty_nil => f(nil_type),
595 ty::ty_bool | ty::ty_ptr(_) |
596 ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
597 ty::ty_int(_) => f(signed_int),
598 ty::ty_float(_) => f(floating_point),
599 // Should never get here, because t is scalar.
600 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
605 // A helper function to do the actual comparison of scalar values.
606 pub fn compare_scalar_values<'a>(
613 let _icx = push_ctxt("compare_scalar_values");
614 fn die(cx: &Block) -> ! {
615 cx.sess().bug("compare_scalar_values: must be a comparison operator");
619 // We don't need to do actual comparisons for nil.
620 // () == () holds but () < () does not.
622 ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(cx.ccx(), true),
623 ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(cx.ccx(), false),
624 // refinements would be nice
630 ast::BiEq => lib::llvm::RealOEQ,
631 ast::BiNe => lib::llvm::RealUNE,
632 ast::BiLt => lib::llvm::RealOLT,
633 ast::BiLe => lib::llvm::RealOLE,
634 ast::BiGt => lib::llvm::RealOGT,
635 ast::BiGe => lib::llvm::RealOGE,
638 return FCmp(cx, cmp, lhs, rhs);
642 ast::BiEq => lib::llvm::IntEQ,
643 ast::BiNe => lib::llvm::IntNE,
644 ast::BiLt => lib::llvm::IntSLT,
645 ast::BiLe => lib::llvm::IntSLE,
646 ast::BiGt => lib::llvm::IntSGT,
647 ast::BiGe => lib::llvm::IntSGE,
650 return ICmp(cx, cmp, lhs, rhs);
654 ast::BiEq => lib::llvm::IntEQ,
655 ast::BiNe => lib::llvm::IntNE,
656 ast::BiLt => lib::llvm::IntULT,
657 ast::BiLe => lib::llvm::IntULE,
658 ast::BiGt => lib::llvm::IntUGT,
659 ast::BiGe => lib::llvm::IntUGE,
662 return ICmp(cx, cmp, lhs, rhs);
667 pub type val_and_ty_fn<'r,'b> =
668 'r |&'b Block<'b>, ValueRef, ty::t| -> &'b Block<'b>;
670 pub fn load_inbounds<'a>(cx: &'a Block<'a>, p: ValueRef, idxs: &[uint])
672 return Load(cx, GEPi(cx, p, idxs));
675 pub fn store_inbounds<'a>(
680 Store(cx, v, GEPi(cx, p, idxs));
683 // Iterates through the elements of a structural type.
684 pub fn iter_structural_ty<'r,
689 f: val_and_ty_fn<'r,'b>)
691 let _icx = push_ctxt("iter_structural_ty");
698 variant: @ty::VariantInfo,
700 f: val_and_ty_fn<'r,'b>)
702 let _icx = push_ctxt("iter_variant");
706 for (i, &arg) in variant.args.iter().enumerate() {
708 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
709 ty::subst_tps(tcx, tps, None, arg));
715 match ty::get(t).sty {
716 ty::ty_struct(..) => {
717 let repr = adt::represent_type(cx.ccx(), t);
718 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
719 for (i, field_ty) in field_tys.iter().enumerate() {
720 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
721 cx = f(cx, llfld_a, field_ty.mt.ty);
725 ty::ty_str(ty::vstore_fixed(_)) |
726 ty::ty_vec(_, ty::vstore_fixed(_)) => {
727 let (base, len) = tvec::get_base_and_byte_len(cx, av, t);
728 cx = tvec::iter_vec_raw(cx, base, t, len, f);
730 ty::ty_tup(ref args) => {
731 let repr = adt::represent_type(cx.ccx(), t);
732 for (i, arg) in args.iter().enumerate() {
733 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
734 cx = f(cx, llfld_a, *arg);
737 ty::ty_enum(tid, ref substs) => {
741 let repr = adt::represent_type(ccx, t);
742 let variants = ty::enum_variants(ccx.tcx(), tid);
743 let n_variants = (*variants).len();
745 // NB: we must hit the discriminant first so that structural
746 // comparison know not to proceed when the discriminants differ.
748 match adt::trans_switch(cx, repr, av) {
749 (_match::single, None) => {
750 cx = iter_variant(cx, repr, av, *variants.get(0),
751 substs.tps.as_slice(), f);
753 (_match::switch, Some(lldiscrim_a)) => {
754 cx = f(cx, lldiscrim_a, ty::mk_int());
755 let unr_cx = fcx.new_temp_block("enum-iter-unr");
757 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
759 let next_cx = fcx.new_temp_block("enum-iter-next");
761 for variant in (*variants).iter() {
763 fcx.new_temp_block(~"enum-iter-variant-" +
764 variant.disr_val.to_str());
765 match adt::trans_case(cx, repr, variant.disr_val) {
766 _match::single_result(r) => {
767 AddCase(llswitch, r.val, variant_cx.llbb)
769 _ => ccx.sess().unimpl("value from adt::trans_case \
770 in iter_structural_ty")
773 iter_variant(variant_cx,
777 substs.tps.as_slice(),
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.sess().bug(~"fail-if-zero on unexpected type: " +
863 ty_to_str(cx.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,
879 fn_ty.sig.inputs.as_slice(),
885 let c = foreign::llvm_calling_convention(ccx, fn_ty.abis);
886 let cconv = c.unwrap_or(lib::llvm::CCallConv);
887 let llty = type_of_fn_from_ty(ccx, t);
888 get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod,
889 name, cconv, llty, fn_ty.sig.output)
893 ty::ty_closure(ref f) => {
894 get_extern_rust_fn(ccx,
895 f.sig.inputs.as_slice(),
901 let llty = type_of(ccx, t);
902 get_extern_const(&mut *ccx.externs.borrow_mut(), ccx.llmod, name,
911 llargs: Vec<ValueRef> ,
912 attributes: &[(uint, lib::llvm::Attribute)],
913 call_info: Option<NodeInfo>)
914 -> (ValueRef, &'a Block<'a>) {
915 let _icx = push_ctxt("invoke_");
916 if bcx.unreachable.get() {
917 return (C_null(Type::i8(bcx.ccx())), bcx);
920 match bcx.opt_node_id {
922 debug!("invoke at ???");
925 debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
929 if need_invoke(bcx) {
930 debug!("invoking {} at {}", llfn, bcx.llbb);
931 for &llarg in llargs.iter() {
932 debug!("arg: {}", llarg);
934 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
935 let landing_pad = bcx.fcx.get_landing_pad();
938 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
939 None => debuginfo::clear_source_location(bcx.fcx)
942 let llresult = Invoke(bcx,
948 return (llresult, normal_bcx);
950 debug!("calling {} at {}", llfn, bcx.llbb);
951 for &llarg in llargs.iter() {
952 debug!("arg: {}", llarg);
956 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
957 None => debuginfo::clear_source_location(bcx.fcx)
960 let llresult = Call(bcx, llfn, llargs.as_slice(), attributes);
961 return (llresult, bcx);
965 pub fn need_invoke(bcx: &Block) -> bool {
966 if bcx.sess().no_landing_pads() {
970 // Avoid using invoke if we are already inside a landing pad.
975 bcx.fcx.needs_invoke()
978 pub fn do_spill(bcx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
979 if ty::type_is_bot(t) {
980 return C_null(Type::i8p(bcx.ccx()));
982 let llptr = alloc_ty(bcx, t, "");
983 Store(bcx, v, llptr);
987 // Since this function does *not* root, it is the caller's responsibility to
988 // ensure that the referent is pointed to by a root.
989 pub fn do_spill_noroot(cx: &Block, v: ValueRef) -> ValueRef {
990 let llptr = alloca(cx, val_ty(v), "");
995 pub fn spill_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
996 let _icx = push_ctxt("spill_if_immediate");
997 if type_is_immediate(cx.ccx(), t) { return do_spill(cx, v, t); }
1001 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
1002 let _icx = push_ctxt("load_if_immediate");
1003 if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
1007 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
1008 match local.pat.node {
1009 ast::PatWild => true, _ => false
1013 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
1016 debug!("init_local(bcx={}, local.id={:?})",
1017 bcx.to_str(), local.id);
1018 let _indenter = indenter();
1020 let _icx = push_ctxt("init_local");
1022 if ignore_lhs(bcx, local) {
1023 // Handle let _ = e; just like e;
1026 return expr::trans_into(bcx, init, expr::Ignore);
1028 None => { return bcx; }
1032 _match::store_local(bcx, local)
1035 pub fn raw_block<'a>(
1036 fcx: &'a FunctionContext<'a>,
1038 llbb: BasicBlockRef)
1040 Block::new(llbb, is_lpad, None, fcx)
1043 pub fn block_locals(b: &ast::Block, it: |@ast::Local|) {
1044 for s in b.stmts.iter() {
1046 ast::StmtDecl(d, _) => {
1048 ast::DeclLocal(ref local) => it(*local),
1049 _ => {} /* fall through */
1052 _ => {} /* fall through */
1057 pub fn with_cond<'a>(
1060 f: |&'a Block<'a>| -> &'a Block<'a>)
1062 let _icx = push_ctxt("with_cond");
1064 let next_cx = fcx.new_temp_block("next");
1065 let cond_cx = fcx.new_temp_block("cond");
1066 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1067 let after_cx = f(cond_cx);
1068 if !after_cx.terminated.get() {
1069 Br(after_cx, next_cx.llbb);
1074 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1075 let _icx = push_ctxt("call_memcpy");
1077 let key = match ccx.sess().targ_cfg.arch {
1078 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1079 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1081 let memcpy = ccx.intrinsics.get_copy(&key);
1082 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1083 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1084 let size = IntCast(cx, n_bytes, ccx.int_type);
1085 let align = C_i32(ccx, align as i32);
1086 let volatile = C_i1(ccx, false);
1087 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1090 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1091 let _icx = push_ctxt("memcpy_ty");
1092 let ccx = bcx.ccx();
1093 if ty::type_is_structural(t) {
1094 let llty = type_of::type_of(ccx, t);
1095 let llsz = llsize_of(ccx, llty);
1096 let llalign = llalign_of_min(ccx, llty);
1097 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1099 Store(bcx, Load(bcx, src), dst);
1103 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1104 if cx.unreachable.get() { return; }
1105 let _icx = push_ctxt("zero_mem");
1108 let llty = type_of::type_of(ccx, t);
1109 memzero(&B(bcx), llptr, llty);
1112 // Always use this function instead of storing a zero constant to the memory
1113 // in question. If you store a zero constant, LLVM will drown in vreg
1114 // allocation for large data structures, and the generated code will be
1115 // awful. (A telltale sign of this is large quantities of
1116 // `mov [byte ptr foo],0` in the generated code.)
1117 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1118 let _icx = push_ctxt("memzero");
1121 let intrinsic_key = match ccx.sess().targ_cfg.arch {
1122 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1123 X86_64 => "llvm.memset.p0i8.i64"
1126 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1127 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1128 let llzeroval = C_u8(ccx, 0);
1129 let size = machine::llsize_of(ccx, ty);
1130 let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1131 let volatile = C_i1(ccx, false);
1132 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1135 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1136 let _icx = push_ctxt("alloc_ty");
1137 let ccx = bcx.ccx();
1138 let ty = type_of::type_of(ccx, t);
1139 assert!(!ty::type_has_params(t));
1140 let val = alloca(bcx, ty, name);
1144 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1145 alloca_maybe_zeroed(cx, ty, name, false)
1148 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1149 let _icx = push_ctxt("alloca");
1150 if cx.unreachable.get() {
1152 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1155 debuginfo::clear_source_location(cx.fcx);
1156 let p = Alloca(cx, ty, name);
1158 let b = cx.fcx.ccx.builder();
1159 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1165 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1166 let _icx = push_ctxt("arrayalloca");
1167 if cx.unreachable.get() {
1169 return llvm::LLVMGetUndef(ty.to_ref());
1172 debuginfo::clear_source_location(cx.fcx);
1173 return ArrayAlloca(cx, ty, v);
1176 pub struct BasicBlocks {
1180 // Creates and returns space for, or returns the argument representing, the
1181 // slot where the return value of the function must go.
1182 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1185 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1186 llvm::LLVMGetParam(fcx.llfn, 0)
1188 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1189 let bcx = fcx.entry_bcx.get().unwrap();
1190 Alloca(bcx, lloutputtype, "__make_return_pointer")
1195 // NB: must keep 4 fns in sync:
1198 // - create_datums_for_fn_args.
1202 // Be warned! You must call `init_function` before doing anything with the
1203 // returned function context.
1204 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1209 param_substs: Option<@param_substs>,
1211 block_arena: &'a TypedArena<Block<'a>>)
1212 -> FunctionContext<'a> {
1213 for p in param_substs.iter() { p.validate(); }
1215 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1216 if id == -1 { ~"" } else { ccx.tcx.map.path_to_str(id) },
1217 id, param_substs.repr(ccx.tcx()));
1219 let substd_output_type = match param_substs {
1220 None => output_type,
1222 ty::subst_tps(ccx.tcx(),
1223 substs.tys.as_slice(),
1228 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1229 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1231 let mut fcx = FunctionContext {
1234 llretptr: Cell::new(None),
1235 entry_bcx: RefCell::new(None),
1236 alloca_insert_pt: Cell::new(None),
1237 llreturn: Cell::new(None),
1238 personality: Cell::new(None),
1239 caller_expects_out_pointer: uses_outptr,
1240 llargs: RefCell::new(NodeMap::new()),
1241 lllocals: RefCell::new(NodeMap::new()),
1242 llupvars: RefCell::new(NodeMap::new()),
1244 param_substs: param_substs,
1246 block_arena: block_arena,
1248 debug_context: debug_context,
1249 scopes: RefCell::new(Vec::new())
1253 fcx.llenv = Some(unsafe {
1254 llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1261 /// Performs setup on a newly created function, creating the entry scope block
1262 /// and allocating space for the return pointer.
1263 pub fn init_function<'a>(
1264 fcx: &'a FunctionContext<'a>,
1267 param_substs: Option<@param_substs>) {
1268 let entry_bcx = fcx.new_temp_block("entry-block");
1270 fcx.entry_bcx.set(Some(entry_bcx));
1272 // Use a dummy instruction as the insertion point for all allocas.
1273 // This is later removed in FunctionContext::cleanup.
1274 fcx.alloca_insert_pt.set(Some(unsafe {
1275 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1276 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1279 let substd_output_type = match param_substs {
1280 None => output_type,
1282 ty::subst_tps(fcx.ccx.tcx(),
1283 substs.tys.as_slice(),
1289 if !return_type_is_void(fcx.ccx, substd_output_type) {
1290 // If the function returns nil/bot, there is no real return
1291 // value, so do not set `llretptr`.
1292 if !skip_retptr || fcx.caller_expects_out_pointer {
1293 // Otherwise, we normally allocate the llretptr, unless we
1294 // have been instructed to skip it for immediate return
1296 fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1301 // NB: must keep 4 fns in sync:
1304 // - create_datums_for_fn_args.
1308 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1309 use middle::trans::datum::{ByRef, ByValue};
1312 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1316 // work around bizarre resolve errors
1317 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1318 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1320 // create_datums_for_fn_args: creates rvalue datums for each of the
1321 // incoming function arguments. These will later be stored into
1322 // appropriate lvalue datums.
1323 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1325 -> Vec<RvalueDatum> {
1326 let _icx = push_ctxt("create_datums_for_fn_args");
1328 // Return an array wrapping the ValueRefs that we get from
1329 // llvm::LLVMGetParam for each argument into datums.
1330 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1331 let llarg = unsafe {
1332 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1334 datum::Datum(llarg, arg_ty, arg_kind(fcx, arg_ty))
1338 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1339 arg_scope: cleanup::CustomScopeIndex,
1342 arg_datums: Vec<RvalueDatum> )
1344 debug!("copy_args_to_allocas");
1346 let _icx = push_ctxt("copy_args_to_allocas");
1349 let arg_scope_id = cleanup::CustomScope(arg_scope);
1351 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1352 // For certain mode/type combinations, the raw llarg values are passed
1353 // by value. However, within the fn body itself, we want to always
1354 // have all locals and arguments be by-ref so that we can cancel the
1355 // cleanup and for better interaction with LLVM's debug info. So, if
1356 // the argument would be passed by value, we store it into an alloca.
1357 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1358 // the event it's not truly needed.
1360 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1362 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1363 debuginfo::create_argument_metadata(bcx, &args[i]);
1370 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1371 // and builds the return block.
1372 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1373 last_bcx: &'a Block<'a>) {
1374 let _icx = push_ctxt("finish_fn");
1376 let ret_cx = match fcx.llreturn.get() {
1378 if !last_bcx.terminated.get() {
1379 Br(last_bcx, llreturn);
1381 raw_block(fcx, false, llreturn)
1385 build_return_block(fcx, ret_cx);
1386 debuginfo::clear_source_location(fcx);
1390 // Builds the return block for a function.
1391 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1392 // Return the value if this function immediate; otherwise, return void.
1393 if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1394 return RetVoid(ret_cx);
1397 let retptr = Value(fcx.llretptr.get().unwrap());
1398 let retval = match retptr.get_dominating_store(ret_cx) {
1399 // If there's only a single store to the ret slot, we can directly return
1400 // the value that was stored and omit the store and the alloca
1402 let retval = s.get_operand(0).unwrap().get();
1403 s.erase_from_parent();
1405 if retptr.has_no_uses() {
1406 retptr.erase_from_parent();
1411 // Otherwise, load the return value from the ret slot
1412 None => Load(ret_cx, fcx.llretptr.get().unwrap())
1416 Ret(ret_cx, retval);
1419 // trans_closure: Builds an LLVM function out of a source function.
1420 // If the function closes over its environment a closure will be
1422 pub fn trans_closure(ccx: &CrateContext,
1426 param_substs: Option<@param_substs>,
1428 _attributes: &[ast::Attribute],
1430 maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1431 ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1433 let _icx = push_ctxt("trans_closure");
1434 set_uwtable(llfndecl);
1436 debug!("trans_closure(..., param_substs={})",
1437 param_substs.repr(ccx.tcx()));
1439 let has_env = match ty::get(ty::node_id_to_type(ccx.tcx(), id)).sty {
1440 ty::ty_closure(_) => true,
1444 let arena = TypedArena::new();
1445 let fcx = new_fn_ctxt(ccx,
1453 init_function(&fcx, false, output_type, param_substs);
1455 // cleanup scope for the incoming arguments
1456 let arg_scope = fcx.push_custom_cleanup_scope();
1458 // Create the first basic block in the function and keep a handle on it to
1459 // pass to finish_fn later.
1460 let bcx_top = fcx.entry_bcx.get().unwrap();
1461 let mut bcx = bcx_top;
1462 let block_ty = node_id_type(bcx, body.id);
1464 // Set up arguments to the function.
1465 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1466 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1468 bcx = copy_args_to_allocas(&fcx,
1471 decl.inputs.as_slice(),
1474 bcx = maybe_load_env(bcx);
1476 // Up until here, IR instructions for this function have explicitly not been annotated with
1477 // source code location, so we don't step into call setup code. From here on, source location
1478 // emitting should be enabled.
1479 debuginfo::start_emitting_source_locations(&fcx);
1481 let dest = match fcx.llretptr.get() {
1482 Some(e) => {expr::SaveIn(e)}
1484 assert!(type_is_zero_size(bcx.ccx(), block_ty))
1489 // This call to trans_block is the place where we bridge between
1490 // translation calls that don't have a return value (trans_crate,
1491 // trans_mod, trans_item, et cetera) and those that do
1492 // (trans_block, trans_expr, et cetera).
1493 bcx = controlflow::trans_block(bcx, body, dest);
1495 match fcx.llreturn.get() {
1497 Br(bcx, fcx.return_exit_block());
1498 fcx.pop_custom_cleanup_scope(arg_scope);
1501 // Microoptimization writ large: avoid creating a separate
1502 // llreturn basic block
1503 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1507 // Put return block after all other blocks.
1508 // This somewhat improves single-stepping experience in debugger.
1510 let llreturn = fcx.llreturn.get();
1511 for &llreturn in llreturn.iter() {
1512 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1516 // Insert the mandatory first few basic blocks before lltop.
1517 finish_fn(&fcx, bcx);
1520 // trans_fn: creates an LLVM function corresponding to a source language
1522 pub fn trans_fn(ccx: &CrateContext,
1526 param_substs: Option<@param_substs>,
1528 attrs: &[ast::Attribute]) {
1529 let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id));
1530 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1531 let _icx = push_ctxt("trans_fn");
1532 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
1533 trans_closure(ccx, decl, body, llfndecl,
1534 param_substs, id, attrs, output_type, |bcx| bcx);
1537 pub fn trans_enum_variant(ccx: &CrateContext,
1538 _enum_id: ast::NodeId,
1539 variant: &ast::Variant,
1540 _args: &[ast::VariantArg],
1542 param_substs: Option<@param_substs>,
1543 llfndecl: ValueRef) {
1544 let _icx = push_ctxt("trans_enum_variant");
1546 trans_enum_variant_or_tuple_like_struct(
1554 pub fn trans_tuple_struct(ccx: &CrateContext,
1555 _fields: &[ast::StructField],
1556 ctor_id: ast::NodeId,
1557 param_substs: Option<@param_substs>,
1558 llfndecl: ValueRef) {
1559 let _icx = push_ctxt("trans_tuple_struct");
1561 trans_enum_variant_or_tuple_like_struct(
1569 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1570 ctor_id: ast::NodeId,
1572 param_substs: Option<@param_substs>,
1573 llfndecl: ValueRef) {
1574 let no_substs: &[ty::t] = [];
1575 let ty_param_substs = match param_substs {
1576 Some(ref substs) => {
1577 let v: &[ty::t] = substs.tys.as_slice();
1581 let v: &[ty::t] = no_substs;
1586 let ctor_ty = ty::subst_tps(ccx.tcx(),
1589 ty::node_id_to_type(ccx.tcx(), ctor_id));
1591 let result_ty = match ty::get(ctor_ty).sty {
1592 ty::ty_bare_fn(ref bft) => bft.sig.output,
1593 _ => ccx.sess().bug(
1594 format!("trans_enum_variant_or_tuple_like_struct: \
1595 unexpected ctor return type {}",
1596 ty_to_str(ccx.tcx(), ctor_ty)))
1599 let arena = TypedArena::new();
1600 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1601 param_substs, None, &arena);
1602 init_function(&fcx, false, result_ty, param_substs);
1604 let arg_tys = ty::ty_fn_args(ctor_ty);
1606 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1608 let bcx = fcx.entry_bcx.get().unwrap();
1610 if !type_is_zero_size(fcx.ccx, result_ty) {
1611 let repr = adt::represent_type(ccx, result_ty);
1612 adt::trans_start_init(bcx, repr, fcx.llretptr.get().unwrap(), disr);
1613 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1614 let lldestptr = adt::trans_field_ptr(bcx,
1616 fcx.llretptr.get().unwrap(),
1619 arg_datum.store_to(bcx, lldestptr);
1623 finish_fn(&fcx, bcx);
1626 pub fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1627 id: ast::NodeId, vi: @Vec<@ty::VariantInfo>,
1629 for &variant in enum_definition.variants.iter() {
1630 let disr_val = vi.get(*i).disr_val;
1633 match variant.node.kind {
1634 ast::TupleVariantKind(ref args) if args.len() > 0 => {
1635 let llfn = get_item_val(ccx, variant.node.id);
1636 trans_enum_variant(ccx, id, variant, args.as_slice(),
1637 disr_val, None, llfn);
1639 ast::TupleVariantKind(_) => {
1642 ast::StructVariantKind(struct_def) => {
1643 trans_struct_def(ccx, struct_def);
1649 pub struct TransItemVisitor<'a> {
1650 ccx: &'a CrateContext,
1653 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1654 fn visit_item(&mut self, i: &ast::Item, _:()) {
1655 trans_item(self.ccx, i);
1659 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1660 let _icx = push_ctxt("trans_item");
1662 ast::ItemFn(decl, purity, _abis, ref generics, body) => {
1663 if purity == ast::ExternFn {
1664 let llfndecl = get_item_val(ccx, item.id);
1665 foreign::trans_rust_fn_with_foreign_abi(
1666 ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
1667 } else if !generics.is_type_parameterized() {
1668 let llfn = get_item_val(ccx, item.id);
1675 item.attrs.as_slice());
1677 // Be sure to travel more than just one layer deep to catch nested
1678 // items in blocks and such.
1679 let mut v = TransItemVisitor{ ccx: ccx };
1680 v.visit_block(body, ());
1683 ast::ItemImpl(ref generics, _, _, ref ms) => {
1684 meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1686 ast::ItemMod(ref m) => {
1689 ast::ItemEnum(ref enum_definition, ref generics) => {
1690 if !generics.is_type_parameterized() {
1691 let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1693 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
1696 ast::ItemStatic(_, m, expr) => {
1697 consts::trans_const(ccx, m, item.id);
1698 // Do static_assert checking. It can't really be done much earlier
1699 // because we need to get the value of the bool out of LLVM
1700 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1701 if m == ast::MutMutable {
1702 ccx.sess().span_fatal(expr.span,
1703 "cannot have static_assert on a mutable \
1707 let v = ccx.const_values.borrow().get_copy(&item.id);
1709 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1710 ccx.sess().span_fatal(expr.span, "static assertion failed");
1715 ast::ItemForeignMod(ref foreign_mod) => {
1716 foreign::trans_foreign_mod(ccx, foreign_mod);
1718 ast::ItemStruct(struct_def, ref generics) => {
1719 if !generics.is_type_parameterized() {
1720 trans_struct_def(ccx, struct_def);
1723 ast::ItemTrait(..) => {
1724 // Inside of this trait definition, we won't be actually translating any
1725 // functions, but the trait still needs to be walked. Otherwise default
1726 // methods with items will not get translated and will cause ICE's when
1727 // metadata time comes around.
1728 let mut v = TransItemVisitor{ ccx: ccx };
1729 visit::walk_item(&mut v, item, ());
1731 _ => {/* fall through */ }
1735 pub fn trans_struct_def(ccx: &CrateContext, struct_def: @ast::StructDef) {
1736 // If this is a tuple-like struct, translate the constructor.
1737 match struct_def.ctor_id {
1738 // We only need to translate a constructor if there are fields;
1739 // otherwise this is a unit-like struct.
1740 Some(ctor_id) if struct_def.fields.len() > 0 => {
1741 let llfndecl = get_item_val(ccx, ctor_id);
1742 trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1743 ctor_id, None, llfndecl);
1745 Some(_) | None => {}
1749 // Translate a module. Doing this amounts to translating the items in the
1750 // module; there ends up being no artifact (aside from linkage names) of
1751 // separate modules in the compiled program. That's because modules exist
1752 // only as a convenience for humans working with the code, to organize names
1753 // and control visibility.
1754 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1755 let _icx = push_ctxt("trans_mod");
1756 for item in m.items.iter() {
1757 trans_item(ccx, *item);
1761 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: ~str, node_id: ast::NodeId,
1763 ccx.item_symbols.borrow_mut().insert(node_id, sym);
1765 if !ccx.reachable.contains(&node_id) {
1766 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1769 if is_entry_fn(ccx.sess(), node_id) && !ccx.sess().building_library.get() {
1770 create_entry_wrapper(ccx, sp, llfn);
1774 fn register_fn(ccx: &CrateContext,
1777 node_id: ast::NodeId,
1780 let f = match ty::get(node_type).sty {
1781 ty::ty_bare_fn(ref f) => {
1782 assert!(f.abis.is_rust() || f.abis.is_intrinsic());
1785 _ => fail!("expected bare rust fn or an intrinsic")
1788 let llfn = decl_rust_fn(ccx,
1790 f.sig.inputs.as_slice(),
1793 finish_register_fn(ccx, sp, sym, node_id, llfn);
1797 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1798 pub fn register_fn_llvmty(ccx: &CrateContext,
1801 node_id: ast::NodeId,
1802 cc: lib::llvm::CallConv,
1804 output: ty::t) -> ValueRef {
1805 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1807 let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty, output);
1808 finish_register_fn(ccx, sp, sym, node_id, llfn);
1812 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1813 match sess.entry_fn.get() {
1814 Some((entry_id, _)) => node_id == entry_id,
1819 // Create a _rust_main(args: ~[str]) function which will be called from the
1820 // runtime rust_start function
1821 pub fn create_entry_wrapper(ccx: &CrateContext,
1823 main_llfn: ValueRef) {
1824 let et = ccx.sess().entry_type.get().unwrap();
1826 session::EntryMain => {
1827 create_entry_fn(ccx, main_llfn, true);
1829 session::EntryStart => create_entry_fn(ccx, main_llfn, false),
1830 session::EntryNone => {} // Do nothing.
1833 fn create_entry_fn(ccx: &CrateContext,
1834 rust_main: ValueRef,
1835 use_start_lang_item: bool) {
1836 let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
1839 let llfn = decl_cdecl_fn(ccx.llmod, "main", llfty, ty::mk_nil());
1840 let llbb = "top".with_c_str(|buf| {
1842 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1845 let bld = ccx.builder.b;
1847 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1849 let (start_fn, args) = if use_start_lang_item {
1850 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1852 Err(s) => { ccx.sess().fatal(s); }
1854 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1855 get_item_val(ccx, start_def_id.node)
1857 let start_fn_type = csearch::get_type(ccx.tcx(),
1859 trans_external_path(ccx, start_def_id, start_fn_type)
1863 let opaque_rust_main = "rust_main".with_c_str(|buf| {
1864 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
1869 llvm::LLVMGetParam(llfn, 0),
1870 llvm::LLVMGetParam(llfn, 1)
1875 debug!("using user-defined start fn");
1877 llvm::LLVMGetParam(llfn, 0 as c_uint),
1878 llvm::LLVMGetParam(llfn, 1 as c_uint)
1884 let result = llvm::LLVMBuildCall(bld,
1887 args.len() as c_uint,
1890 llvm::LLVMBuildRet(bld, result);
1895 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1896 ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
1897 match attr::first_attr_value_str_by_name(attrs, "export_name") {
1898 // Use provided name
1899 Some(name) => name.get().to_owned(),
1901 _ => ccx.tcx.map.with_path(id, |mut path| {
1902 if attr::contains_name(attrs, "no_mangle") {
1904 path.last().unwrap().to_str()
1906 // Usual name mangling
1907 mangle_exported_name(ccx, path, ty, id)
1913 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
1914 debug!("get_item_val(id=`{:?}`)", id);
1916 match ccx.item_vals.borrow().find_copy(&id) {
1917 Some(v) => return v,
1921 let mut foreign = false;
1922 let item = ccx.tcx.map.get(id);
1923 let val = match item {
1924 ast_map::NodeItem(i) => {
1925 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
1926 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1928 let v = match i.node {
1929 ast::ItemStatic(_, _, expr) => {
1930 // If this static came from an external crate, then
1931 // we need to get the symbol from csearch instead of
1932 // using the current crate's name/version
1933 // information in the hash of the symbol
1934 debug!("making {}", sym);
1935 let (sym, is_local) = {
1936 match ccx.external_srcs.borrow().find(&i.id) {
1938 debug!("but found in other crate...");
1939 (csearch::get_symbol(&ccx.sess().cstore,
1946 // We need the translated value here, because for enums the
1947 // LLVM type is not fully determined by the Rust type.
1948 let (v, inlineable) = consts::const_expr(ccx, expr, is_local);
1949 ccx.const_values.borrow_mut().insert(id, v);
1950 let mut inlineable = inlineable;
1953 let llty = llvm::LLVMTypeOf(v);
1954 let g = sym.with_c_str(|buf| {
1955 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
1958 if !ccx.reachable.contains(&id) {
1959 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
1962 // Apply the `unnamed_addr` attribute if
1964 if attr::contains_name(i.attrs.as_slice(),
1965 "address_insignificant") {
1966 if ccx.reachable.contains(&id) {
1967 ccx.sess().span_bug(i.span,
1968 "insignificant static is reachable");
1970 lib::llvm::SetUnnamedAddr(g, true);
1972 // This is a curious case where we must make
1973 // all of these statics inlineable. If a
1974 // global is tagged as
1975 // address_insignificant, then LLVM won't
1976 // coalesce globals unless they have an
1977 // internal linkage type. This means that
1978 // external crates cannot use this global.
1979 // This is a problem for things like inner
1980 // statics in generic functions, because the
1981 // function will be inlined into another
1982 // crate and then attempt to link to the
1983 // static in the original crate, only to
1984 // find that it's not there. On the other
1985 // side of inlininig, the crates knows to
1986 // not declare this static as
1987 // available_externally (because it isn't)
1991 if attr::contains_name(i.attrs.as_slice(),
1993 lib::llvm::set_thread_local(g, true);
1997 debug!("{} not inlined", sym);
1998 ccx.non_inlineable_statics.borrow_mut()
2002 ccx.item_symbols.borrow_mut().insert(i.id, sym);
2007 ast::ItemFn(_, purity, _, _, _) => {
2008 let llfn = if purity != ast::ExternFn {
2009 register_fn(ccx, i.span, sym, i.id, ty)
2011 foreign::register_rust_fn_with_foreign_abi(ccx,
2016 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2020 _ => fail!("get_item_val: weird result in table")
2023 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
2025 Some(sect) => unsafe {
2026 sect.get().with_c_str(|buf| {
2027 llvm::LLVMSetSection(v, buf);
2036 ast_map::NodeTraitMethod(trait_method) => {
2037 debug!("get_item_val(): processing a NodeTraitMethod");
2038 match *trait_method {
2039 ast::Required(_) => {
2040 ccx.sess().bug("unexpected variant: required trait method in \
2043 ast::Provided(m) => {
2044 register_method(ccx, id, m)
2049 ast_map::NodeMethod(m) => {
2050 register_method(ccx, id, m)
2053 ast_map::NodeForeignItem(ni) => {
2057 ast::ForeignItemFn(..) => {
2058 let abis = ccx.tcx.map.get_foreign_abis(id);
2059 foreign::register_foreign_item_fn(ccx, abis, ni)
2061 ast::ForeignItemStatic(..) => {
2062 foreign::register_static(ccx, ni)
2067 ast_map::NodeVariant(ref v) => {
2069 let args = match v.node.kind {
2070 ast::TupleVariantKind(ref args) => args,
2071 ast::StructVariantKind(_) => {
2072 fail!("struct variant kind unexpected in get_item_val")
2075 assert!(args.len() != 0u);
2076 let ty = ty::node_id_to_type(ccx.tcx(), id);
2077 let parent = ccx.tcx.map.get_parent(id);
2078 let enm = ccx.tcx.map.expect_item(parent);
2079 let sym = exported_name(ccx,
2082 enm.attrs.as_slice());
2084 llfn = match enm.node {
2085 ast::ItemEnum(_, _) => {
2086 register_fn(ccx, (*v).span, sym, id, ty)
2088 _ => fail!("NodeVariant, shouldn't happen")
2090 set_inline_hint(llfn);
2094 ast_map::NodeStructCtor(struct_def) => {
2095 // Only register the constructor if this is a tuple-like struct.
2096 let ctor_id = match struct_def.ctor_id {
2098 ccx.sess().bug("attempt to register a constructor of \
2099 a non-tuple-like struct")
2101 Some(ctor_id) => ctor_id,
2103 let parent = ccx.tcx.map.get_parent(id);
2104 let struct_item = ccx.tcx.map.expect_item(parent);
2105 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2106 let sym = exported_name(ccx,
2111 let llfn = register_fn(ccx, struct_item.span,
2113 set_inline_hint(llfn);
2118 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2123 // foreign items (extern fns and extern statics) don't have internal
2124 // linkage b/c that doesn't quite make sense. Otherwise items can
2125 // have internal linkage if they're not reachable.
2126 if !foreign && !ccx.reachable.contains(&id) {
2127 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2130 ccx.item_vals.borrow_mut().insert(id, val);
2134 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2135 m: &ast::Method) -> ValueRef {
2136 let mty = ty::node_id_to_type(ccx.tcx(), id);
2138 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2140 let llfn = register_fn(ccx, m.span, sym, id, mty);
2141 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2145 pub fn vp2i(cx: &Block, v: ValueRef) -> ValueRef {
2147 return PtrToInt(cx, v, ccx.int_type);
2150 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2152 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2157 pub fn declare_intrinsics(ccx: &mut CrateContext) {
2159 ($name:expr fn() -> $ret:expr) => ({
2161 // HACK(eddyb) dummy output type, shouln't affect anything.
2162 let f = decl_cdecl_fn(ccx.llmod, name, Type::func([], &$ret), ty::mk_nil());
2163 ccx.intrinsics.insert(name, f);
2165 ($name:expr fn($($arg:expr),*) -> $ret:expr) => ({
2167 // HACK(eddyb) dummy output type, shouln't affect anything.
2168 let f = decl_cdecl_fn(ccx.llmod, name,
2169 Type::func([$($arg),*], &$ret), ty::mk_nil());
2170 ccx.intrinsics.insert(name, f);
2173 macro_rules! mk_struct (
2174 ($($field_ty:expr),*) => (Type::struct_(ccx, [$($field_ty),*], false))
2177 let i8p = Type::i8p(ccx);
2178 let void = Type::void(ccx);
2179 let i1 = Type::i1(ccx);
2180 let t_i8 = Type::i8(ccx);
2181 let t_i16 = Type::i16(ccx);
2182 let t_i32 = Type::i32(ccx);
2183 let t_i64 = Type::i64(ccx);
2184 let t_f32 = Type::f32(ccx);
2185 let t_f64 = Type::f64(ccx);
2187 ifn!("llvm.memcpy.p0i8.p0i8.i32" fn(i8p, i8p, t_i32, t_i32, i1) -> void);
2188 ifn!("llvm.memcpy.p0i8.p0i8.i64" fn(i8p, i8p, t_i64, t_i32, i1) -> void);
2189 ifn!("llvm.memmove.p0i8.p0i8.i32" fn(i8p, i8p, t_i32, t_i32, i1) -> void);
2190 ifn!("llvm.memmove.p0i8.p0i8.i64" fn(i8p, i8p, t_i64, t_i32, i1) -> void);
2191 ifn!("llvm.memset.p0i8.i32" fn(i8p, t_i8, t_i32, t_i32, i1) -> void);
2192 ifn!("llvm.memset.p0i8.i64" fn(i8p, t_i8, t_i64, t_i32, i1) -> void);
2194 ifn!("llvm.trap" fn() -> void);
2195 ifn!("llvm.debugtrap" fn() -> void);
2196 ifn!("llvm.frameaddress" fn(t_i32) -> i8p);
2198 ifn!("llvm.powi.f32" fn(t_f32, t_i32) -> t_f32);
2199 ifn!("llvm.powi.f64" fn(t_f64, t_i32) -> t_f64);
2200 ifn!("llvm.pow.f32" fn(t_f32, t_f32) -> t_f32);
2201 ifn!("llvm.pow.f64" fn(t_f64, t_f64) -> t_f64);
2203 ifn!("llvm.sqrt.f32" fn(t_f32) -> t_f32);
2204 ifn!("llvm.sqrt.f64" fn(t_f64) -> t_f64);
2205 ifn!("llvm.sin.f32" fn(t_f32) -> t_f32);
2206 ifn!("llvm.sin.f64" fn(t_f64) -> t_f64);
2207 ifn!("llvm.cos.f32" fn(t_f32) -> t_f32);
2208 ifn!("llvm.cos.f64" fn(t_f64) -> t_f64);
2209 ifn!("llvm.exp.f32" fn(t_f32) -> t_f32);
2210 ifn!("llvm.exp.f64" fn(t_f64) -> t_f64);
2211 ifn!("llvm.exp2.f32" fn(t_f32) -> t_f32);
2212 ifn!("llvm.exp2.f64" fn(t_f64) -> t_f64);
2213 ifn!("llvm.log.f32" fn(t_f32) -> t_f32);
2214 ifn!("llvm.log.f64" fn(t_f64) -> t_f64);
2215 ifn!("llvm.log10.f32" fn(t_f32) -> t_f32);
2216 ifn!("llvm.log10.f64" fn(t_f64) -> t_f64);
2217 ifn!("llvm.log2.f32" fn(t_f32) -> t_f32);
2218 ifn!("llvm.log2.f64" fn(t_f64) -> t_f64);
2220 ifn!("llvm.fma.f32" fn(t_f32, t_f32, t_f32) -> t_f32);
2221 ifn!("llvm.fma.f64" fn(t_f64, t_f64, t_f64) -> t_f64);
2223 ifn!("llvm.fabs.f32" fn(t_f32) -> t_f32);
2224 ifn!("llvm.fabs.f64" fn(t_f64) -> t_f64);
2226 ifn!("llvm.floor.f32" fn(t_f32) -> t_f32);
2227 ifn!("llvm.floor.f64" fn(t_f64) -> t_f64);
2228 ifn!("llvm.ceil.f32" fn(t_f32) -> t_f32);
2229 ifn!("llvm.ceil.f64" fn(t_f64) -> t_f64);
2230 ifn!("llvm.trunc.f32" fn(t_f32) -> t_f32);
2231 ifn!("llvm.trunc.f64" fn(t_f64) -> t_f64);
2233 ifn!("llvm.rint.f32" fn(t_f32) -> t_f32);
2234 ifn!("llvm.rint.f64" fn(t_f64) -> t_f64);
2235 ifn!("llvm.nearbyint.f32" fn(t_f32) -> t_f32);
2236 ifn!("llvm.nearbyint.f64" fn(t_f64) -> t_f64);
2238 ifn!("llvm.ctpop.i8" fn(t_i8) -> t_i8);
2239 ifn!("llvm.ctpop.i16" fn(t_i16) -> t_i16);
2240 ifn!("llvm.ctpop.i32" fn(t_i32) -> t_i32);
2241 ifn!("llvm.ctpop.i64" fn(t_i64) -> t_i64);
2243 ifn!("llvm.ctlz.i8" fn(t_i8 , i1) -> t_i8);
2244 ifn!("llvm.ctlz.i16" fn(t_i16, i1) -> t_i16);
2245 ifn!("llvm.ctlz.i32" fn(t_i32, i1) -> t_i32);
2246 ifn!("llvm.ctlz.i64" fn(t_i64, i1) -> t_i64);
2248 ifn!("llvm.cttz.i8" fn(t_i8 , i1) -> t_i8);
2249 ifn!("llvm.cttz.i16" fn(t_i16, i1) -> t_i16);
2250 ifn!("llvm.cttz.i32" fn(t_i32, i1) -> t_i32);
2251 ifn!("llvm.cttz.i64" fn(t_i64, i1) -> t_i64);
2253 ifn!("llvm.bswap.i16" fn(t_i16) -> t_i16);
2254 ifn!("llvm.bswap.i32" fn(t_i32) -> t_i32);
2255 ifn!("llvm.bswap.i64" fn(t_i64) -> t_i64);
2257 ifn!("llvm.sadd.with.overflow.i8" fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
2258 ifn!("llvm.sadd.with.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
2259 ifn!("llvm.sadd.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
2260 ifn!("llvm.sadd.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
2262 ifn!("llvm.uadd.with.overflow.i8" fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
2263 ifn!("llvm.uadd.with.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
2264 ifn!("llvm.uadd.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
2265 ifn!("llvm.uadd.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
2267 ifn!("llvm.ssub.with.overflow.i8" fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
2268 ifn!("llvm.ssub.with.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
2269 ifn!("llvm.ssub.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
2270 ifn!("llvm.ssub.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
2272 ifn!("llvm.usub.with.overflow.i8" fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
2273 ifn!("llvm.usub.with.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
2274 ifn!("llvm.usub.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
2275 ifn!("llvm.usub.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
2277 ifn!("llvm.smul.with.overflow.i8" fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
2278 ifn!("llvm.smul.with.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
2279 ifn!("llvm.smul.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
2280 ifn!("llvm.smul.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
2282 ifn!("llvm.umul.with.overflow.i8" fn(t_i8, t_i8) -> mk_struct!{t_i8, i1});
2283 ifn!("llvm.umul.with.overflow.i16" fn(t_i16, t_i16) -> mk_struct!{t_i16, i1});
2284 ifn!("llvm.umul.with.overflow.i32" fn(t_i32, t_i32) -> mk_struct!{t_i32, i1});
2285 ifn!("llvm.umul.with.overflow.i64" fn(t_i64, t_i64) -> mk_struct!{t_i64, i1});
2287 ifn!("llvm.expect.i1" fn(i1, i1) -> i1);
2289 // Some intrinsics were introduced in later versions of LLVM, but they have
2290 // fallbacks in libc or libm and such. Currently, all of these intrinsics
2291 // were introduced in LLVM 3.4, so we case on that.
2292 macro_rules! compatible_ifn (
2293 ($name:expr, $cname:ident ($($arg:expr),*) -> $ret:expr) => ({
2295 if unsafe { llvm::LLVMVersionMinor() >= 4 } {
2296 ifn!(name fn($($arg),*) -> $ret);
2298 let f = decl_cdecl_fn(ccx.llmod, stringify!($cname),
2299 Type::func([$($arg),*], &$ret),
2301 ccx.intrinsics.insert(name, f);
2306 compatible_ifn!("llvm.copysign.f32", copysignf(t_f32, t_f32) -> t_f32);
2307 compatible_ifn!("llvm.copysign.f64", copysign(t_f64, t_f64) -> t_f64);
2308 compatible_ifn!("llvm.round.f32", roundf(t_f32) -> t_f32);
2309 compatible_ifn!("llvm.round.f64", round(t_f64) -> t_f64);
2312 if ccx.sess().opts.debuginfo != NoDebugInfo {
2313 ifn!("llvm.dbg.declare" fn(Type::metadata(ccx), Type::metadata(ccx)) -> void);
2314 ifn!("llvm.dbg.value" fn(Type::metadata(ccx), t_i64, Type::metadata(ccx)) -> void);
2318 pub fn trap(bcx: &Block) {
2319 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2320 Some(&x) => { Call(bcx, x, [], []); },
2321 _ => bcx.sess().bug("unbound llvm.trap in trap")
2325 pub fn symname(name: &str, hash: &str, vers: &str) -> ~str {
2326 let path = [PathName(token::intern(name))];
2327 link::exported_name(ast_map::Values(path.iter()).chain(None), hash, vers)
2330 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2331 -> encoder::EncodeParams<'r> {
2333 let diag = cx.sess().diagnostic();
2334 let item_symbols = &cx.item_symbols;
2335 let link_meta = &cx.link_meta;
2336 encoder::EncodeParams {
2339 reexports2: cx.exp_map2,
2340 item_symbols: item_symbols,
2341 non_inlineable_statics: &cx.non_inlineable_statics,
2342 link_meta: link_meta,
2343 cstore: &cx.sess().cstore,
2344 encode_inlined_item: ie,
2348 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2351 if !cx.sess().building_library.get() {
2355 let encode_inlined_item: encoder::EncodeInlinedItem =
2356 |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii, &cx.maps);
2358 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2359 let metadata = encoder::encode_metadata(encode_parms, krate);
2360 let compressed = encoder::metadata_encoding_version +
2361 flate::deflate_bytes(metadata.as_slice()).as_slice();
2362 let llmeta = C_bytes(cx, compressed);
2363 let llconst = C_struct(cx, [llmeta], false);
2364 let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2365 cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2366 let llglobal = name.with_c_str(|buf| {
2368 llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2372 llvm::LLVMSetInitializer(llglobal, llconst);
2373 cx.sess().targ_cfg.target_strs.meta_sect_name.with_c_str(|buf| {
2374 llvm::LLVMSetSection(llglobal, buf)
2380 pub fn trans_crate(krate: ast::Crate,
2381 analysis: CrateAnalysis,
2382 output: &OutputFilenames) -> (ty::ctxt, CrateTranslation) {
2383 let CrateAnalysis { ty_cx: tcx, exp_map2, maps, reachable, .. } = analysis;
2385 // Before we touch LLVM, make sure that multithreading is enabled.
2387 use sync::one::{Once, ONCE_INIT};
2388 static mut INIT: Once = ONCE_INIT;
2389 static mut POISONED: bool = false;
2391 if llvm::LLVMStartMultithreaded() != 1 {
2392 // use an extra bool to make sure that all future usage of LLVM
2393 // cannot proceed despite the Once not running more than once.
2399 tcx.sess.bug("couldn't enable multi-threaded LLVM");
2403 let link_meta = link::build_link_meta(&krate, output.out_filestem);
2405 // Append ".rs" to crate name as LLVM module identifier.
2407 // LLVM code generator emits a ".file filename" directive
2408 // for ELF backends. Value of the "filename" is set as the
2409 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2410 // crashes if the module identifer is same as other symbols
2411 // such as a function name in the module.
2412 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2413 let llmod_id = link_meta.crateid.name + ".rs";
2415 let ccx = CrateContext::new(llmod_id, tcx, exp_map2, maps,
2416 Sha256::new(), link_meta, reachable);
2418 let _icx = push_ctxt("text");
2419 trans_mod(&ccx, &krate.module);
2422 glue::emit_tydescs(&ccx);
2423 if ccx.sess().opts.debuginfo != NoDebugInfo {
2424 debuginfo::finalize(&ccx);
2427 // Translate the metadata.
2428 let metadata = write_metadata(&ccx, &krate);
2429 if ccx.sess().trans_stats() {
2430 println!("--- trans stats ---");
2431 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2432 println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2433 println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2434 println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2436 println!("n_fns: {}", ccx.stats.n_fns.get());
2437 println!("n_monos: {}", ccx.stats.n_monos.get());
2438 println!("n_inlines: {}", ccx.stats.n_inlines.get());
2439 println!("n_closures: {}", ccx.stats.n_closures.get());
2440 println!("fn stats:");
2441 ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2442 insns_b.cmp(&insns_a)
2444 for tuple in ccx.stats.fn_stats.borrow().iter() {
2446 (ref name, ms, insns) => {
2447 println!("{} insns, {} ms, {}", insns, ms, *name);
2452 if ccx.sess().count_llvm_insns() {
2453 for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2454 println!("{:7u} {}", *v, *k);
2458 let llcx = ccx.llcx;
2459 let link_meta = ccx.link_meta.clone();
2460 let llmod = ccx.llmod;
2462 let mut reachable: Vec<~str> = ccx.reachable.iter().filter_map(|id| {
2463 ccx.item_symbols.borrow().find(id).map(|s| s.to_owned())
2466 // Make sure that some other crucial symbols are not eliminated from the
2467 // module. This includes the main function, the crate map (used for debug
2468 // log settings and I/O), and finally the curious rust_stack_exhausted
2469 // symbol. This symbol is required for use by the libmorestack library that
2470 // we link in, so we must ensure that this symbol is not internalized (if
2471 // defined in the crate).
2472 reachable.push(~"main");
2473 reachable.push(~"rust_stack_exhausted");
2474 reachable.push(~"rust_eh_personality"); // referenced from .eh_frame section on some platforms
2475 reachable.push(~"rust_eh_personality_catch"); // referenced from rt/rust_try.ll
2477 let metadata_module = ccx.metadata_llmod;
2479 (ccx.tcx, CrateTranslation {
2483 metadata_module: metadata_module,
2485 reachable: reachable,