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::config::{NoDebugInfo, FullDebugInfo};
32 use driver::driver::{CrateAnalysis, CrateTranslation, ModuleTranslation};
33 use driver::session::Session;
35 use llvm::{BasicBlockRef, ModuleRef, ValueRef, Vector, get_param};
37 use metadata::{csearch, encoder, loader};
38 use middle::astencode;
39 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::weak_lang_items;
42 use middle::subst::Subst;
43 use middle::trans::_match;
44 use middle::trans::adt;
45 use middle::trans::build::*;
46 use middle::trans::builder::{Builder, noname};
47 use middle::trans::callee;
48 use middle::trans::cleanup::{CleanupMethods, ScopeId};
49 use middle::trans::cleanup;
50 use middle::trans::common::{Block, C_bool, C_bytes_in_context, C_i32, C_integral, C_nil};
51 use middle::trans::common::{C_null, C_struct_in_context, C_u64, C_u8, C_uint, C_undef};
52 use middle::trans::common::{CrateContext, ExternMap, FunctionContext};
53 use middle::trans::common::{NodeInfo, Result, SubstP, monomorphize_type};
54 use middle::trans::common::{node_id_type, param_substs, return_type_is_void};
55 use middle::trans::common::{tydesc_info, type_is_immediate};
56 use middle::trans::common::{type_is_zero_size, val_ty};
57 use middle::trans::common;
58 use middle::trans::consts;
59 use middle::trans::context::SharedCrateContext;
60 use middle::trans::controlflow;
61 use middle::trans::datum;
62 use middle::trans::debuginfo;
63 use middle::trans::expr;
64 use middle::trans::foreign;
65 use middle::trans::glue;
66 use middle::trans::inline;
67 use middle::trans::intrinsic;
68 use middle::trans::machine;
69 use middle::trans::machine::{llsize_of, llsize_of_real, llalign_of_min};
70 use middle::trans::meth;
71 use middle::trans::monomorphize;
72 use middle::trans::tvec;
73 use middle::trans::type_::Type;
74 use middle::trans::type_of;
75 use middle::trans::type_of::*;
76 use middle::trans::value::Value;
78 use util::common::indenter;
79 use util::ppaux::{Repr, ty_to_string};
80 use util::sha2::Sha256;
81 use util::nodemap::NodeMap;
83 use arena::TypedArena;
84 use libc::{c_uint, uint64_t};
85 use std::c_str::ToCStr;
86 use std::cell::{Cell, RefCell};
87 use std::collections::HashSet;
89 use std::{i8, i16, i32, i64};
90 use syntax::abi::{X86, X86_64, Arm, Mips, Mipsel, Rust, RustCall};
91 use syntax::abi::{RustIntrinsic, Abi, OsWindows};
92 use syntax::ast_util::{local_def, is_local};
93 use syntax::attr::AttrMetaMethods;
95 use syntax::codemap::Span;
96 use syntax::parse::token::InternedString;
97 use syntax::visit::Visitor;
99 use syntax::{ast, ast_util, ast_map};
103 local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)
105 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
106 match task_local_insn_key.get() {
107 Some(ctx) => blk(ctx.borrow().as_slice()),
112 pub fn init_insn_ctxt() {
113 task_local_insn_key.replace(Some(RefCell::new(Vec::new())));
116 pub struct _InsnCtxt {
117 _cannot_construct_outside_of_this_module: ()
121 impl Drop for _InsnCtxt {
123 match task_local_insn_key.get() {
124 Some(ctx) => { ctx.borrow_mut().pop(); }
130 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
131 debug!("new InsnCtxt: {}", s);
132 match task_local_insn_key.get() {
133 Some(ctx) => ctx.borrow_mut().push(s),
136 _InsnCtxt { _cannot_construct_outside_of_this_module: () }
139 pub struct StatRecorder<'a, 'tcx: 'a> {
140 ccx: &'a CrateContext<'a, 'tcx>,
141 name: Option<String>,
146 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
147 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String)
148 -> StatRecorder<'a, 'tcx> {
149 let start = if ccx.sess().trans_stats() {
150 time::precise_time_ns()
154 let istart = ccx.stats().n_llvm_insns.get();
165 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
167 if self.ccx.sess().trans_stats() {
168 let end = time::precise_time_ns();
169 let elapsed = ((end - self.start) / 1_000_000) as uint;
170 let iend = self.ccx.stats().n_llvm_insns.get();
171 self.ccx.stats().fn_stats.borrow_mut().push((self.name.take().unwrap(),
173 iend - self.istart));
174 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
175 // Reset LLVM insn count to avoid compound costs.
176 self.ccx.stats().n_llvm_insns.set(self.istart);
181 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
182 pub fn decl_fn(ccx: &CrateContext, name: &str, cc: llvm::CallConv,
183 ty: Type, output: ty::t) -> ValueRef {
185 let llfn: ValueRef = name.with_c_str(|buf| {
187 llvm::LLVMGetOrInsertFunction(ccx.llmod(), buf, ty.to_ref())
191 match ty::get(output).sty {
192 // functions returning bottom may unwind, but can never return normally
194 llvm::SetFunctionAttribute(llfn, llvm::NoReturnAttribute)
199 if ccx.tcx().sess.opts.cg.no_redzone {
200 llvm::SetFunctionAttribute(llfn, llvm::NoRedZoneAttribute)
203 llvm::SetFunctionCallConv(llfn, cc);
204 // Function addresses in Rust are never significant, allowing functions to be merged.
205 llvm::SetUnnamedAddr(llfn, true);
207 if ccx.is_split_stack_supported() {
208 set_split_stack(llfn);
214 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
215 pub fn decl_cdecl_fn(ccx: &CrateContext,
218 output: ty::t) -> ValueRef {
219 decl_fn(ccx, name, llvm::CCallConv, ty, output)
222 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
223 pub fn get_extern_fn(ccx: &CrateContext,
224 externs: &mut ExternMap,
230 match externs.find_equiv(&name) {
231 Some(n) => return *n,
234 let f = decl_fn(ccx, name, cc, ty, output);
235 externs.insert(name.to_string(), f);
239 fn get_extern_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str, did: ast::DefId) -> ValueRef {
240 match ccx.externs().borrow().find_equiv(&name) {
241 Some(n) => return *n,
245 let f = decl_rust_fn(ccx, fn_ty, name);
247 csearch::get_item_attrs(&ccx.sess().cstore, did, |attrs| {
248 set_llvm_fn_attrs(attrs.as_slice(), f)
251 ccx.externs().borrow_mut().insert(name.to_string(), f);
255 pub fn self_type_for_unboxed_closure(ccx: &CrateContext,
256 closure_id: ast::DefId)
258 let unboxed_closure_type = ty::mk_unboxed_closure(ccx.tcx(),
261 let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
262 let unboxed_closure = unboxed_closures.get(&closure_id);
263 match unboxed_closure.kind {
264 ty::FnUnboxedClosureKind => {
265 ty::mk_imm_rptr(ccx.tcx(), ty::ReStatic, unboxed_closure_type)
267 ty::FnMutUnboxedClosureKind => {
268 ty::mk_mut_rptr(ccx.tcx(), ty::ReStatic, unboxed_closure_type)
270 ty::FnOnceUnboxedClosureKind => unboxed_closure_type,
274 pub fn kind_for_unboxed_closure(ccx: &CrateContext, closure_id: ast::DefId)
275 -> ty::UnboxedClosureKind {
276 let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
277 unboxed_closures.get(&closure_id).kind
280 pub fn decl_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
281 let (inputs, output, abi, env) = match ty::get(fn_ty).sty {
282 ty::ty_bare_fn(ref f) => {
283 (f.sig.inputs.clone(), f.sig.output, f.abi, None)
285 ty::ty_closure(ref f) => {
286 (f.sig.inputs.clone(), f.sig.output, f.abi, Some(Type::i8p(ccx)))
288 ty::ty_unboxed_closure(closure_did, _) => {
289 let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
290 let unboxed_closure = unboxed_closures.get(&closure_did);
291 let function_type = unboxed_closure.closure_type.clone();
292 let self_type = self_type_for_unboxed_closure(ccx, closure_did);
293 let llenvironment_type = type_of_explicit_arg(ccx, self_type);
294 (function_type.sig.inputs.clone(),
295 function_type.sig.output,
297 Some(llenvironment_type))
299 _ => fail!("expected closure or fn")
302 let llfty = type_of_rust_fn(ccx, env, inputs.as_slice(), output, abi);
303 debug!("decl_rust_fn(input count={},type={})",
305 ccx.tn().type_to_string(llfty));
307 let llfn = decl_fn(ccx, name, llvm::CCallConv, llfty, output);
308 let attrs = get_fn_llvm_attributes(ccx, fn_ty);
309 attrs.apply_llfn(llfn);
314 pub fn decl_internal_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
315 let llfn = decl_rust_fn(ccx, fn_ty, name);
316 llvm::SetLinkage(llfn, llvm::InternalLinkage);
320 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
321 name: &str, ty: Type) -> ValueRef {
322 match externs.find_equiv(&name) {
323 Some(n) => return *n,
327 let c = name.with_c_str(|buf| {
328 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
330 externs.insert(name.to_string(), c);
335 // Returns a pointer to the body for the box. The box may be an opaque
336 // box. The result will be casted to the type of body_t, if it is statically
338 pub fn at_box_body(bcx: Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
339 let _icx = push_ctxt("at_box_body");
341 let ty = Type::at_box(ccx, type_of(ccx, body_t));
342 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
343 GEPi(bcx, boxptr, [0u, abi::box_field_body])
346 fn require_alloc_fn(bcx: Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
347 match bcx.tcx().lang_items.require(it) {
350 bcx.sess().fatal(format!("allocation of `{}` {}",
351 bcx.ty_to_string(info_ty),
357 // The following malloc_raw_dyn* functions allocate a box to contain
358 // a given type, but with a potentially dynamic size.
360 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
365 -> Result<'blk, 'tcx> {
366 let _icx = push_ctxt("malloc_raw_exchange");
369 let r = callee::trans_lang_call(bcx,
370 require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem),
374 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
377 pub fn malloc_raw_dyn_proc<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: ty::t) -> Result<'blk, 'tcx> {
378 let _icx = push_ctxt("malloc_raw_dyn_proc");
381 // Grab the TypeRef type of ptr_ty.
382 let ptr_ty = ty::mk_uniq(bcx.tcx(), t);
383 let ptr_llty = type_of(ccx, ptr_ty);
385 let llty = type_of(bcx.ccx(), t);
386 let size = llsize_of(bcx.ccx(), llty);
387 let llalign = C_uint(ccx, llalign_of_min(bcx.ccx(), llty) as uint);
389 // Allocate space and store the destructor pointer:
390 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, ptr_llty, t, size, llalign);
391 let dtor_ptr = GEPi(bcx, llbox, [0u, abi::box_field_drop_glue]);
392 let drop_glue_field_ty = type_of(ccx, ty::mk_nil_ptr(bcx.tcx()));
393 let drop_glue = PointerCast(bcx, glue::get_drop_glue(ccx, ty::mk_uniq(bcx.tcx(), t)),
395 Store(bcx, drop_glue, dtor_ptr);
397 Result::new(bcx, llbox)
401 pub fn malloc_raw_dyn_managed<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
405 -> Result<'blk, 'tcx> {
406 let _icx = push_ctxt("malloc_raw_dyn_managed");
409 let langcall = require_alloc_fn(bcx, t, alloc_fn);
411 // Grab the TypeRef type of box_ptr_ty.
412 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
413 let llty = type_of(ccx, box_ptr_ty);
414 let llalign = C_uint(ccx, type_of::align_of(ccx, box_ptr_ty) as uint);
417 let drop_glue = glue::get_drop_glue(ccx, t);
418 let r = callee::trans_lang_call(
422 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
427 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
430 // Type descriptor and type glue stuff
432 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
433 match ccx.tydescs().borrow().find(&t) {
434 Some(inf) => return inf.clone(),
438 ccx.stats().n_static_tydescs.set(ccx.stats().n_static_tydescs.get() + 1u);
439 let inf = Rc::new(glue::declare_tydesc(ccx, t));
441 ccx.tydescs().borrow_mut().insert(t, inf.clone());
445 #[allow(dead_code)] // useful
446 pub fn set_optimize_for_size(f: ValueRef) {
447 llvm::SetFunctionAttribute(f, llvm::OptimizeForSizeAttribute)
450 pub fn set_no_inline(f: ValueRef) {
451 llvm::SetFunctionAttribute(f, llvm::NoInlineAttribute)
454 #[allow(dead_code)] // useful
455 pub fn set_no_unwind(f: ValueRef) {
456 llvm::SetFunctionAttribute(f, llvm::NoUnwindAttribute)
459 // Tell LLVM to emit the information necessary to unwind the stack for the
461 pub fn set_uwtable(f: ValueRef) {
462 llvm::SetFunctionAttribute(f, llvm::UWTableAttribute)
465 pub fn set_inline_hint(f: ValueRef) {
466 llvm::SetFunctionAttribute(f, llvm::InlineHintAttribute)
469 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
471 // Set the inline hint if there is one
472 match find_inline_attr(attrs) {
473 InlineHint => set_inline_hint(llfn),
474 InlineAlways => set_always_inline(llfn),
475 InlineNever => set_no_inline(llfn),
476 InlineNone => { /* fallthrough */ }
479 // Add the no-split-stack attribute if requested
480 if contains_name(attrs, "no_split_stack") {
481 unset_split_stack(llfn);
484 if contains_name(attrs, "cold") {
486 llvm::LLVMAddFunctionAttribute(llfn,
487 llvm::FunctionIndex as c_uint,
488 llvm::ColdAttribute as uint64_t)
493 pub fn set_always_inline(f: ValueRef) {
494 llvm::SetFunctionAttribute(f, llvm::AlwaysInlineAttribute)
497 pub fn set_split_stack(f: ValueRef) {
498 "split-stack".with_c_str(|buf| {
499 unsafe { llvm::LLVMAddFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
503 pub fn unset_split_stack(f: ValueRef) {
504 "split-stack".with_c_str(|buf| {
505 unsafe { llvm::LLVMRemoveFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
509 // Double-check that we never ask LLVM to declare the same symbol twice. It
510 // silently mangles such symbols, breaking our linkage model.
511 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) {
512 if ccx.all_llvm_symbols().borrow().contains(&sym) {
513 ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).as_slice());
515 ccx.all_llvm_symbols().borrow_mut().insert(sym);
519 pub fn get_res_dtor(ccx: &CrateContext,
522 parent_id: ast::DefId,
523 substs: &subst::Substs)
525 let _icx = push_ctxt("trans_res_dtor");
526 let did = inline::maybe_instantiate_inline(ccx, did);
528 if !substs.types.is_empty() {
529 assert_eq!(did.krate, ast::LOCAL_CRATE);
531 // Since we're in trans we don't care for any region parameters
532 let ref substs = subst::Substs::erased(substs.types.clone());
534 let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, None);
537 } else if did.krate == ast::LOCAL_CRATE {
538 get_item_val(ccx, did.node)
541 let name = csearch::get_symbol(&ccx.sess().cstore, did);
542 let class_ty = ty::lookup_item_type(tcx, parent_id).ty.subst(tcx, substs);
543 let llty = type_of_dtor(ccx, class_ty);
544 let dtor_ty = ty::mk_ctor_fn(ccx.tcx(), ast::DUMMY_NODE_ID,
545 [glue::get_drop_glue_type(ccx, t)], ty::mk_nil());
547 &mut *ccx.externs().borrow_mut(),
555 // Structural comparison: a rather involved form of glue.
556 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
557 if cx.sess().opts.cg.save_temps {
560 llvm::LLVMSetValueName(v, buf)
567 // Used only for creating scalar comparison glue.
568 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
570 pub fn compare_scalar_types<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
575 -> Result<'blk, 'tcx> {
576 let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
578 match ty::get(t).sty {
579 ty::ty_nil => f(nil_type),
580 ty::ty_bool | ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
581 ty::ty_ptr(mt) if ty::type_is_sized(cx.tcx(), mt.ty) => f(unsigned_int),
582 ty::ty_int(_) => f(signed_int),
583 ty::ty_float(_) => f(floating_point),
584 // Should never get here, because t is scalar.
585 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
590 // A helper function to do the actual comparison of scalar values.
591 pub fn compare_scalar_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
597 let _icx = push_ctxt("compare_scalar_values");
598 fn die(cx: Block) -> ! {
599 cx.sess().bug("compare_scalar_values: must be a comparison operator");
603 // We don't need to do actual comparisons for nil.
604 // () == () holds but () < () does not.
606 ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(cx.ccx(), true),
607 ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(cx.ccx(), false),
608 // refinements would be nice
614 ast::BiEq => llvm::RealOEQ,
615 ast::BiNe => llvm::RealUNE,
616 ast::BiLt => llvm::RealOLT,
617 ast::BiLe => llvm::RealOLE,
618 ast::BiGt => llvm::RealOGT,
619 ast::BiGe => llvm::RealOGE,
622 return FCmp(cx, cmp, lhs, rhs);
626 ast::BiEq => llvm::IntEQ,
627 ast::BiNe => llvm::IntNE,
628 ast::BiLt => llvm::IntSLT,
629 ast::BiLe => llvm::IntSLE,
630 ast::BiGt => llvm::IntSGT,
631 ast::BiGe => llvm::IntSGE,
634 return ICmp(cx, cmp, lhs, rhs);
638 ast::BiEq => llvm::IntEQ,
639 ast::BiNe => llvm::IntNE,
640 ast::BiLt => llvm::IntULT,
641 ast::BiLe => llvm::IntULE,
642 ast::BiGt => llvm::IntUGT,
643 ast::BiGe => llvm::IntUGE,
646 return ICmp(cx, cmp, lhs, rhs);
651 pub fn compare_simd_types(
659 match ty::get(t).sty {
661 // The comparison operators for floating point vectors are challenging.
662 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
663 // then bitcast to a floating point vector, the result will be `-NaN`
664 // for each truth value. Because of this they are unsupported.
665 cx.sess().bug("compare_simd_types: comparison operators \
666 not supported for floating point SIMD types")
668 ty::ty_uint(_) | ty::ty_int(_) => {
670 ast::BiEq => llvm::IntEQ,
671 ast::BiNe => llvm::IntNE,
672 ast::BiLt => llvm::IntSLT,
673 ast::BiLe => llvm::IntSLE,
674 ast::BiGt => llvm::IntSGT,
675 ast::BiGe => llvm::IntSGE,
676 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
678 let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
679 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
680 // to get the correctly sized type. This will compile to a single instruction
681 // once the IR is converted to assembly if the SIMD instruction is supported
682 // by the target architecture.
683 SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
685 _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
689 pub type val_and_ty_fn<'a, 'blk, 'tcx> =
690 |Block<'blk, 'tcx>, ValueRef, ty::t|: 'a -> Block<'blk, 'tcx>;
692 // Iterates through the elements of a structural type.
693 pub fn iter_structural_ty<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
696 f: val_and_ty_fn<'a, 'blk, 'tcx>)
697 -> Block<'blk, 'tcx> {
698 let _icx = push_ctxt("iter_structural_ty");
700 fn iter_variant<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
703 variant: &ty::VariantInfo,
704 substs: &subst::Substs,
705 f: val_and_ty_fn<'a, 'blk, 'tcx>)
706 -> Block<'blk, 'tcx> {
707 let _icx = push_ctxt("iter_variant");
711 for (i, &arg) in variant.args.iter().enumerate() {
713 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
714 arg.subst(tcx, substs));
719 let (data_ptr, info) = if ty::type_is_sized(cx.tcx(), t) {
722 let data = GEPi(cx, av, [0, abi::slice_elt_base]);
723 let info = GEPi(cx, av, [0, abi::slice_elt_len]);
724 (Load(cx, data), Some(Load(cx, info)))
728 match ty::get(t).sty {
729 ty::ty_struct(..) => {
730 let repr = adt::represent_type(cx.ccx(), t);
731 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
732 for (i, field_ty) in field_tys.iter().enumerate() {
733 let field_ty = field_ty.mt.ty;
734 let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, discr, i);
736 let val = if ty::type_is_sized(cx.tcx(), field_ty) {
739 let boxed_ty = ty::mk_open(cx.tcx(), field_ty);
740 let scratch = datum::rvalue_scratch_datum(cx, boxed_ty, "__fat_ptr_iter");
741 Store(cx, llfld_a, GEPi(cx, scratch.val, [0, abi::slice_elt_base]));
742 Store(cx, info.unwrap(), GEPi(cx, scratch.val, [0, abi::slice_elt_len]));
745 cx = f(cx, val, field_ty);
749 ty::ty_unboxed_closure(def_id, _) => {
750 let repr = adt::represent_type(cx.ccx(), t);
751 let upvars = ty::unboxed_closure_upvars(cx.tcx(), def_id);
752 for (i, upvar) in upvars.iter().enumerate() {
753 let llupvar = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
754 cx = f(cx, llupvar, upvar.ty);
757 ty::ty_vec(_, Some(n)) => {
758 let (base, len) = tvec::get_fixed_base_and_len(cx, data_ptr, n);
759 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
760 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
762 ty::ty_tup(ref args) => {
763 let repr = adt::represent_type(cx.ccx(), t);
764 for (i, arg) in args.iter().enumerate() {
765 let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
766 cx = f(cx, llfld_a, *arg);
769 ty::ty_enum(tid, ref substs) => {
773 let repr = adt::represent_type(ccx, t);
774 let variants = ty::enum_variants(ccx.tcx(), tid);
775 let n_variants = (*variants).len();
777 // NB: we must hit the discriminant first so that structural
778 // comparison know not to proceed when the discriminants differ.
780 match adt::trans_switch(cx, &*repr, av) {
781 (_match::Single, None) => {
782 cx = iter_variant(cx, &*repr, av, &**variants.get(0),
785 (_match::Switch, Some(lldiscrim_a)) => {
786 cx = f(cx, lldiscrim_a, ty::mk_int());
787 let unr_cx = fcx.new_temp_block("enum-iter-unr");
789 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
791 let next_cx = fcx.new_temp_block("enum-iter-next");
793 for variant in (*variants).iter() {
796 format!("enum-iter-variant-{}",
797 variant.disr_val.to_string().as_slice())
799 match adt::trans_case(cx, &*repr, variant.disr_val) {
800 _match::SingleResult(r) => {
801 AddCase(llswitch, r.val, variant_cx.llbb)
803 _ => ccx.sess().unimpl("value from adt::trans_case \
804 in iter_structural_ty")
807 iter_variant(variant_cx,
813 Br(variant_cx, next_cx.llbb);
817 _ => ccx.sess().unimpl("value from adt::trans_switch \
818 in iter_structural_ty")
821 _ => cx.sess().unimpl("type in iter_structural_ty")
826 pub fn cast_shift_expr_rhs(cx: Block,
831 cast_shift_rhs(op, lhs, rhs,
832 |a,b| Trunc(cx, a, b),
833 |a,b| ZExt(cx, a, b))
836 pub fn cast_shift_const_rhs(op: ast::BinOp,
837 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
838 cast_shift_rhs(op, lhs, rhs,
839 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
840 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
843 pub fn cast_shift_rhs(op: ast::BinOp,
846 trunc: |ValueRef, Type| -> ValueRef,
847 zext: |ValueRef, Type| -> ValueRef)
849 // Shifts may have any size int on the rhs
851 if ast_util::is_shift_binop(op) {
852 let mut rhs_llty = val_ty(rhs);
853 let mut lhs_llty = val_ty(lhs);
854 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
855 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
856 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
857 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
860 } else if lhs_sz > rhs_sz {
861 // FIXME (#1877: If shifting by negative
862 // values becomes not undefined then this is wrong.
873 pub fn fail_if_zero_or_overflows<'blk, 'tcx>(
874 cx: Block<'blk, 'tcx>,
880 -> Block<'blk, 'tcx> {
881 let (zero_text, overflow_text) = if divrem == ast::BiDiv {
882 ("attempted to divide by zero",
883 "attempted to divide with overflow")
885 ("attempted remainder with a divisor of zero",
886 "attempted remainder with overflow")
888 let (is_zero, is_signed) = match ty::get(rhs_t).sty {
890 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
891 (ICmp(cx, llvm::IntEQ, rhs, zero), true)
894 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
895 (ICmp(cx, llvm::IntEQ, rhs, zero), false)
898 cx.sess().bug(format!("fail-if-zero on unexpected type: {}",
899 ty_to_string(cx.tcx(), rhs_t)).as_slice());
902 let bcx = with_cond(cx, is_zero, |bcx| {
903 controlflow::trans_fail(bcx, span, InternedString::new(zero_text))
906 // To quote LLVM's documentation for the sdiv instruction:
908 // Division by zero leads to undefined behavior. Overflow also leads
909 // to undefined behavior; this is a rare case, but can occur, for
910 // example, by doing a 32-bit division of -2147483648 by -1.
912 // In order to avoid undefined behavior, we perform runtime checks for
913 // signed division/remainder which would trigger overflow. For unsigned
914 // integers, no action beyond checking for zero need be taken.
916 let (llty, min) = match ty::get(rhs_t).sty {
918 let llty = Type::int_from_ty(cx.ccx(), t);
920 ast::TyI if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
921 ast::TyI => i64::MIN as u64,
922 ast::TyI8 => i8::MIN as u64,
923 ast::TyI16 => i16::MIN as u64,
924 ast::TyI32 => i32::MIN as u64,
925 ast::TyI64 => i64::MIN as u64,
931 let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
932 C_integral(llty, -1, false));
933 with_cond(bcx, minus_one, |bcx| {
934 let is_min = ICmp(bcx, llvm::IntEQ, lhs,
935 C_integral(llty, min, true));
936 with_cond(bcx, is_min, |bcx| {
937 controlflow::trans_fail(bcx, span,
938 InternedString::new(overflow_text))
946 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
947 let name = csearch::get_symbol(&ccx.sess().cstore, did);
948 match ty::get(t).sty {
949 ty::ty_bare_fn(ref fn_ty) => {
950 match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
951 ccx.sess().targ_cfg.arch) {
952 Some(Rust) | Some(RustCall) => {
953 get_extern_rust_fn(ccx, t, name.as_slice(), did)
955 Some(RustIntrinsic) => {
956 ccx.sess().bug("unexpected intrinsic in trans_external_path")
959 foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
960 name.as_slice(), None)
964 ty::ty_closure(_) => {
965 get_extern_rust_fn(ccx, t, name.as_slice(), did)
968 let llty = type_of(ccx, t);
969 get_extern_const(&mut *ccx.externs().borrow_mut(),
977 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
979 llargs: Vec<ValueRef> ,
981 call_info: Option<NodeInfo>,
982 // FIXME(15064) is_lang_item is a horrible hack, please remove it
983 // at the soonest opportunity.
985 -> (ValueRef, Block<'blk, 'tcx>) {
986 let _icx = push_ctxt("invoke_");
987 if bcx.unreachable.get() {
988 return (C_null(Type::i8(bcx.ccx())), bcx);
991 // FIXME(15064) Lang item methods may (in the reflect case) not have proper
992 // types, so doing an attribute lookup will fail.
993 let attributes = if is_lang_item {
994 llvm::AttrBuilder::new()
996 get_fn_llvm_attributes(bcx.ccx(), fn_ty)
999 match bcx.opt_node_id {
1001 debug!("invoke at ???");
1004 debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
1008 if need_invoke(bcx) {
1009 debug!("invoking {} at {}", llfn, bcx.llbb);
1010 for &llarg in llargs.iter() {
1011 debug!("arg: {}", llarg);
1013 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
1014 let landing_pad = bcx.fcx.get_landing_pad();
1017 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
1018 None => debuginfo::clear_source_location(bcx.fcx)
1021 let llresult = Invoke(bcx,
1027 return (llresult, normal_bcx);
1029 debug!("calling {} at {}", llfn, bcx.llbb);
1030 for &llarg in llargs.iter() {
1031 debug!("arg: {}", llarg);
1035 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
1036 None => debuginfo::clear_source_location(bcx.fcx)
1039 let llresult = Call(bcx, llfn, llargs.as_slice(), Some(attributes));
1040 return (llresult, bcx);
1044 pub fn need_invoke(bcx: Block) -> bool {
1045 if bcx.sess().no_landing_pads() {
1049 // Avoid using invoke if we are already inside a landing pad.
1054 bcx.fcx.needs_invoke()
1057 pub fn load_if_immediate(cx: Block, v: ValueRef, t: ty::t) -> ValueRef {
1058 let _icx = push_ctxt("load_if_immediate");
1059 if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
1063 pub fn load_ty(cx: Block, ptr: ValueRef, t: ty::t) -> ValueRef {
1065 * Helper for loading values from memory. Does the necessary conversion if
1066 * the in-memory type differs from the type used for SSA values. Also
1067 * handles various special cases where the type gives us better information
1068 * about what we are loading.
1070 if type_is_zero_size(cx.ccx(), t) {
1071 C_undef(type_of::type_of(cx.ccx(), t))
1072 } else if ty::type_is_bool(t) {
1073 Trunc(cx, LoadRangeAssert(cx, ptr, 0, 2, llvm::False), Type::i1(cx.ccx()))
1074 } else if ty::type_is_char(t) {
1075 // a char is a Unicode codepoint, and so takes values from 0
1076 // to 0x10FFFF inclusive only.
1077 LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
1083 pub fn store_ty(cx: Block, v: ValueRef, dst: ValueRef, t: ty::t) {
1085 * Helper for storing values in memory. Does the necessary conversion if
1086 * the in-memory type differs from the type used for SSA values.
1088 if ty::type_is_bool(t) {
1089 Store(cx, ZExt(cx, v, Type::i8(cx.ccx())), dst);
1095 pub fn ignore_lhs(_bcx: Block, local: &ast::Local) -> bool {
1096 match local.pat.node {
1097 ast::PatWild(ast::PatWildSingle) => true, _ => false
1101 pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &ast::Local)
1102 -> Block<'blk, 'tcx> {
1103 debug!("init_local(bcx={}, local.id={:?})", bcx.to_str(), local.id);
1104 let _indenter = indenter();
1105 let _icx = push_ctxt("init_local");
1106 _match::store_local(bcx, local)
1109 pub fn raw_block<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1111 llbb: BasicBlockRef)
1112 -> Block<'blk, 'tcx> {
1113 common::BlockS::new(llbb, is_lpad, None, fcx)
1116 pub fn with_cond<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1118 f: |Block<'blk, 'tcx>| -> Block<'blk, 'tcx>)
1119 -> Block<'blk, 'tcx> {
1120 let _icx = push_ctxt("with_cond");
1122 let next_cx = fcx.new_temp_block("next");
1123 let cond_cx = fcx.new_temp_block("cond");
1124 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1125 let after_cx = f(cond_cx);
1126 if !after_cx.terminated.get() {
1127 Br(after_cx, next_cx.llbb);
1132 pub fn call_lifetime_start(cx: Block, ptr: ValueRef) {
1133 if cx.sess().opts.optimize == config::No {
1137 let _icx = push_ctxt("lifetime_start");
1140 let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
1141 let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
1142 let lifetime_start = ccx.get_intrinsic(&"llvm.lifetime.start");
1143 Call(cx, lifetime_start, [llsize, ptr], None);
1146 pub fn call_lifetime_end(cx: Block, ptr: ValueRef) {
1147 if cx.sess().opts.optimize == config::No {
1151 let _icx = push_ctxt("lifetime_end");
1154 let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
1155 let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
1156 let lifetime_end = ccx.get_intrinsic(&"llvm.lifetime.end");
1157 Call(cx, lifetime_end, [llsize, ptr], None);
1160 pub fn call_memcpy(cx: Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1161 let _icx = push_ctxt("call_memcpy");
1163 let key = match ccx.sess().targ_cfg.arch {
1164 X86 | Arm | Mips | Mipsel => "llvm.memcpy.p0i8.p0i8.i32",
1165 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1167 let memcpy = ccx.get_intrinsic(&key);
1168 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1169 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1170 let size = IntCast(cx, n_bytes, ccx.int_type());
1171 let align = C_i32(ccx, align as i32);
1172 let volatile = C_bool(ccx, false);
1173 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], None);
1176 pub fn memcpy_ty(bcx: Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1177 let _icx = push_ctxt("memcpy_ty");
1178 let ccx = bcx.ccx();
1179 if ty::type_is_structural(t) {
1180 let llty = type_of::type_of(ccx, t);
1181 let llsz = llsize_of(ccx, llty);
1182 let llalign = type_of::align_of(ccx, t);
1183 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1185 store_ty(bcx, Load(bcx, src), dst, t);
1189 pub fn zero_mem(cx: Block, llptr: ValueRef, t: ty::t) {
1190 if cx.unreachable.get() { return; }
1191 let _icx = push_ctxt("zero_mem");
1193 memzero(&B(bcx), llptr, t);
1196 // Always use this function instead of storing a zero constant to the memory
1197 // in question. If you store a zero constant, LLVM will drown in vreg
1198 // allocation for large data structures, and the generated code will be
1199 // awful. (A telltale sign of this is large quantities of
1200 // `mov [byte ptr foo],0` in the generated code.)
1201 fn memzero(b: &Builder, llptr: ValueRef, ty: ty::t) {
1202 let _icx = push_ctxt("memzero");
1205 let llty = type_of::type_of(ccx, ty);
1207 let intrinsic_key = match ccx.sess().targ_cfg.arch {
1208 X86 | Arm | Mips | Mipsel => "llvm.memset.p0i8.i32",
1209 X86_64 => "llvm.memset.p0i8.i64"
1212 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1213 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1214 let llzeroval = C_u8(ccx, 0);
1215 let size = machine::llsize_of(ccx, llty);
1216 let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
1217 let volatile = C_bool(ccx, false);
1218 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], None);
1221 pub fn alloc_ty(bcx: Block, t: ty::t, name: &str) -> ValueRef {
1222 let _icx = push_ctxt("alloc_ty");
1223 let ccx = bcx.ccx();
1224 let ty = type_of::type_of(ccx, t);
1225 assert!(!ty::type_has_params(t));
1226 let val = alloca(bcx, ty, name);
1230 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
1231 let p = alloca_no_lifetime(cx, ty, name);
1232 call_lifetime_start(cx, p);
1236 pub fn alloca_no_lifetime(cx: Block, ty: Type, name: &str) -> ValueRef {
1237 let _icx = push_ctxt("alloca");
1238 if cx.unreachable.get() {
1240 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1243 debuginfo::clear_source_location(cx.fcx);
1244 Alloca(cx, ty, name)
1247 pub fn alloca_zeroed(cx: Block, ty: ty::t, name: &str) -> ValueRef {
1248 let llty = type_of::type_of(cx.ccx(), ty);
1249 if cx.unreachable.get() {
1251 return llvm::LLVMGetUndef(llty.ptr_to().to_ref());
1254 let p = alloca_no_lifetime(cx, llty, name);
1255 let b = cx.fcx.ccx.builder();
1256 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1261 pub fn arrayalloca(cx: Block, ty: Type, v: ValueRef) -> ValueRef {
1262 let _icx = push_ctxt("arrayalloca");
1263 if cx.unreachable.get() {
1265 return llvm::LLVMGetUndef(ty.to_ref());
1268 debuginfo::clear_source_location(cx.fcx);
1269 let p = ArrayAlloca(cx, ty, v);
1270 call_lifetime_start(cx, p);
1274 // Creates the alloca slot which holds the pointer to the slot for the final return value
1275 pub fn make_return_slot_pointer(fcx: &FunctionContext, output_type: ty::t) -> ValueRef {
1276 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1278 // We create an alloca to hold a pointer of type `output_type`
1279 // which will hold the pointer to the right alloca which has the
1281 if fcx.needs_ret_allocas {
1282 // Let's create the stack slot
1283 let slot = AllocaFcx(fcx, lloutputtype.ptr_to(), "llretslotptr");
1285 // and if we're using an out pointer, then store that in our newly made slot
1286 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1287 let outptr = get_param(fcx.llfn, 0);
1289 let b = fcx.ccx.builder();
1290 b.position_before(fcx.alloca_insert_pt.get().unwrap());
1291 b.store(outptr, slot);
1296 // But if there are no nested returns, we skip the indirection and have a single
1299 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1300 get_param(fcx.llfn, 0)
1302 AllocaFcx(fcx, lloutputtype, "sret_slot")
1307 struct CheckForNestedReturnsVisitor {
1312 impl CheckForNestedReturnsVisitor {
1313 fn explicit() -> CheckForNestedReturnsVisitor {
1314 CheckForNestedReturnsVisitor { found: false, in_return: false }
1316 fn implicit() -> CheckForNestedReturnsVisitor {
1317 CheckForNestedReturnsVisitor { found: false, in_return: true }
1321 impl<'v> Visitor<'v> for CheckForNestedReturnsVisitor {
1322 fn visit_expr(&mut self, e: &ast::Expr) {
1324 ast::ExprRet(..) => {
1328 self.in_return = true;
1329 visit::walk_expr(self, e);
1330 self.in_return = false;
1333 _ => visit::walk_expr(self, e)
1338 fn has_nested_returns(tcx: &ty::ctxt, id: ast::NodeId) -> bool {
1339 match tcx.map.find(id) {
1340 Some(ast_map::NodeItem(i)) => {
1342 ast::ItemFn(_, _, _, _, ref blk) => {
1343 let mut explicit = CheckForNestedReturnsVisitor::explicit();
1344 let mut implicit = CheckForNestedReturnsVisitor::implicit();
1345 visit::walk_item(&mut explicit, &*i);
1346 visit::walk_expr_opt(&mut implicit, &blk.expr);
1347 explicit.found || implicit.found
1349 _ => tcx.sess.bug("unexpected item variant in has_nested_returns")
1352 Some(ast_map::NodeTraitItem(trait_method)) => {
1353 match *trait_method {
1354 ast::ProvidedMethod(ref m) => {
1356 ast::MethDecl(_, _, _, _, _, _, ref blk, _) => {
1357 let mut explicit = CheckForNestedReturnsVisitor::explicit();
1358 let mut implicit = CheckForNestedReturnsVisitor::implicit();
1359 visit::walk_method_helper(&mut explicit, &**m);
1360 visit::walk_expr_opt(&mut implicit, &blk.expr);
1361 explicit.found || implicit.found
1363 ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
1366 ast::RequiredMethod(_) => {
1367 tcx.sess.bug("unexpected variant: required trait method \
1368 in has_nested_returns")
1370 ast::TypeTraitItem(_) => {
1371 tcx.sess.bug("unexpected variant: type trait item in \
1372 has_nested_returns")
1376 Some(ast_map::NodeImplItem(ii)) => {
1378 ast::MethodImplItem(ref m) => {
1380 ast::MethDecl(_, _, _, _, _, _, ref blk, _) => {
1381 let mut explicit = CheckForNestedReturnsVisitor::explicit();
1382 let mut implicit = CheckForNestedReturnsVisitor::implicit();
1383 visit::walk_method_helper(&mut explicit, &**m);
1384 visit::walk_expr_opt(&mut implicit, &blk.expr);
1385 explicit.found || implicit.found
1387 ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
1390 ast::TypeImplItem(_) => {
1391 tcx.sess.bug("unexpected variant: type impl item in \
1392 has_nested_returns")
1396 Some(ast_map::NodeExpr(e)) => {
1398 ast::ExprFnBlock(_, _, ref blk) |
1399 ast::ExprProc(_, ref blk) |
1400 ast::ExprUnboxedFn(_, _, _, ref blk) => {
1401 let mut explicit = CheckForNestedReturnsVisitor::explicit();
1402 let mut implicit = CheckForNestedReturnsVisitor::implicit();
1403 visit::walk_expr(&mut explicit, e);
1404 visit::walk_expr_opt(&mut implicit, &blk.expr);
1405 explicit.found || implicit.found
1407 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns")
1411 Some(ast_map::NodeVariant(..)) | Some(ast_map::NodeStructCtor(..)) => false,
1414 None if id == ast::DUMMY_NODE_ID => false,
1416 _ => tcx.sess.bug(format!("unexpected variant in has_nested_returns: {}",
1417 tcx.map.path_to_string(id)).as_slice())
1421 // NB: must keep 4 fns in sync:
1424 // - create_datums_for_fn_args.
1428 // Be warned! You must call `init_function` before doing anything with the
1429 // returned function context.
1430 pub fn new_fn_ctxt<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
1435 param_substs: &'a param_substs,
1437 block_arena: &'a TypedArena<common::BlockS<'a, 'tcx>>)
1438 -> FunctionContext<'a, 'tcx> {
1439 param_substs.validate();
1441 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1445 ccx.tcx().map.path_to_string(id).to_string()
1447 id, param_substs.repr(ccx.tcx()));
1449 let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1450 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1451 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1452 let nested_returns = has_nested_returns(ccx.tcx(), id);
1454 let mut fcx = FunctionContext {
1457 llretslotptr: Cell::new(None),
1458 alloca_insert_pt: Cell::new(None),
1459 llreturn: Cell::new(None),
1460 needs_ret_allocas: nested_returns,
1461 personality: Cell::new(None),
1462 caller_expects_out_pointer: uses_outptr,
1463 lllocals: RefCell::new(NodeMap::new()),
1464 llupvars: RefCell::new(NodeMap::new()),
1466 param_substs: param_substs,
1468 block_arena: block_arena,
1470 debug_context: debug_context,
1471 scopes: RefCell::new(Vec::new())
1475 fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1481 /// Performs setup on a newly created function, creating the entry scope block
1482 /// and allocating space for the return pointer.
1483 pub fn init_function<'a, 'tcx>(fcx: &'a FunctionContext<'a, 'tcx>,
1485 output_type: ty::t) -> Block<'a, 'tcx> {
1486 let entry_bcx = fcx.new_temp_block("entry-block");
1488 // Use a dummy instruction as the insertion point for all allocas.
1489 // This is later removed in FunctionContext::cleanup.
1490 fcx.alloca_insert_pt.set(Some(unsafe {
1491 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1492 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1495 // This shouldn't need to recompute the return type,
1496 // as new_fn_ctxt did it already.
1497 let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1499 if !return_type_is_void(fcx.ccx, substd_output_type) {
1500 // If the function returns nil/bot, there is no real return
1501 // value, so do not set `llretslotptr`.
1502 if !skip_retptr || fcx.caller_expects_out_pointer {
1503 // Otherwise, we normally allocate the llretslotptr, unless we
1504 // have been instructed to skip it for immediate return
1506 fcx.llretslotptr.set(Some(make_return_slot_pointer(fcx, substd_output_type)));
1513 // NB: must keep 4 fns in sync:
1516 // - create_datums_for_fn_args.
1520 pub fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1521 use middle::trans::datum::{ByRef, ByValue};
1524 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1528 // work around bizarre resolve errors
1529 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1530 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1532 // create_datums_for_fn_args: creates rvalue datums for each of the
1533 // incoming function arguments. These will later be stored into
1534 // appropriate lvalue datums.
1535 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1537 -> Vec<RvalueDatum> {
1538 let _icx = push_ctxt("create_datums_for_fn_args");
1540 // Return an array wrapping the ValueRefs that we get from `get_param` for
1541 // each argument into datums.
1542 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1543 let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1544 datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1548 /// Creates rvalue datums for each of the incoming function arguments and
1549 /// tuples the arguments. These will later be stored into appropriate lvalue
1552 /// FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1553 fn create_datums_for_fn_args_under_call_abi(
1555 arg_scope: cleanup::CustomScopeIndex,
1557 -> Vec<RvalueDatum> {
1558 let mut result = Vec::new();
1559 for (i, &arg_ty) in arg_tys.iter().enumerate() {
1560 if i < arg_tys.len() - 1 {
1561 // Regular argument.
1562 let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1563 result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1568 // This is the last argument. Tuple it.
1569 match ty::get(arg_ty).sty {
1570 ty::ty_tup(ref tupled_arg_tys) => {
1571 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1574 datum::lvalue_scratch_datum(bcx,
1578 tuple_args_scope_id,
1583 for (j, &tupled_arg_ty) in
1584 tupled_arg_tys.iter().enumerate() {
1586 get_param(bcx.fcx.llfn,
1587 bcx.fcx.arg_pos(i + j) as c_uint);
1588 let lldest = GEPi(bcx, llval, [0, j]);
1589 let datum = datum::Datum::new(
1592 arg_kind(bcx.fcx, tupled_arg_ty));
1593 bcx = datum.store_to(bcx, lldest);
1597 let tuple = unpack_datum!(bcx,
1598 tuple.to_expr_datum()
1599 .to_rvalue_datum(bcx,
1604 let mode = datum::Rvalue::new(datum::ByValue);
1605 result.push(datum::Datum::new(C_nil(bcx.ccx()),
1610 bcx.tcx().sess.bug("last argument of a function with \
1611 `rust-call` ABI isn't a tuple?!")
1620 fn copy_args_to_allocas<'blk, 'tcx>(fcx: &FunctionContext<'blk, 'tcx>,
1621 arg_scope: cleanup::CustomScopeIndex,
1622 bcx: Block<'blk, 'tcx>,
1624 arg_datums: Vec<RvalueDatum> )
1625 -> Block<'blk, 'tcx> {
1626 debug!("copy_args_to_allocas");
1628 let _icx = push_ctxt("copy_args_to_allocas");
1631 let arg_scope_id = cleanup::CustomScope(arg_scope);
1633 for (i, arg_datum) in arg_datums.into_iter().enumerate() {
1634 // For certain mode/type combinations, the raw llarg values are passed
1635 // by value. However, within the fn body itself, we want to always
1636 // have all locals and arguments be by-ref so that we can cancel the
1637 // cleanup and for better interaction with LLVM's debug info. So, if
1638 // the argument would be passed by value, we store it into an alloca.
1639 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1640 // the event it's not truly needed.
1642 bcx = _match::store_arg(bcx, &*args[i].pat, arg_datum, arg_scope_id);
1644 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1645 debuginfo::create_argument_metadata(bcx, &args[i]);
1652 fn copy_unboxed_closure_args_to_allocas<'blk, 'tcx>(
1653 mut bcx: Block<'blk, 'tcx>,
1654 arg_scope: cleanup::CustomScopeIndex,
1656 arg_datums: Vec<RvalueDatum>,
1657 monomorphized_arg_types: &[ty::t])
1658 -> Block<'blk, 'tcx> {
1659 let _icx = push_ctxt("copy_unboxed_closure_args_to_allocas");
1660 let arg_scope_id = cleanup::CustomScope(arg_scope);
1662 assert_eq!(arg_datums.len(), 1);
1664 let arg_datum = arg_datums.into_iter().next().unwrap();
1666 // Untuple the rest of the arguments.
1669 arg_datum.to_lvalue_datum_in_scope(bcx,
1672 let empty = Vec::new();
1673 let untupled_arg_types = match ty::get(monomorphized_arg_types[0]).sty {
1674 ty::ty_tup(ref types) => types.as_slice(),
1675 ty::ty_nil => empty.as_slice(),
1677 bcx.tcx().sess.span_bug(args[0].pat.span,
1678 "first arg to `rust-call` ABI function \
1682 for j in range(0, args.len()) {
1683 let tuple_element_type = untupled_arg_types[j];
1684 let tuple_element_datum =
1685 tuple_datum.get_element(bcx,
1687 |llval| GEPi(bcx, llval, [0, j]));
1688 let tuple_element_datum = tuple_element_datum.to_expr_datum();
1689 let tuple_element_datum =
1691 tuple_element_datum.to_rvalue_datum(bcx,
1693 bcx = _match::store_arg(bcx,
1695 tuple_element_datum,
1698 if bcx.fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1699 debuginfo::create_argument_metadata(bcx, &args[j]);
1706 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1707 // and builds the return block.
1708 pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1709 last_bcx: Block<'blk, 'tcx>,
1711 let _icx = push_ctxt("finish_fn");
1713 // This shouldn't need to recompute the return type,
1714 // as new_fn_ctxt did it already.
1715 let substd_retty = retty.substp(fcx.ccx.tcx(), fcx.param_substs);
1717 let ret_cx = match fcx.llreturn.get() {
1719 if !last_bcx.terminated.get() {
1720 Br(last_bcx, llreturn);
1722 raw_block(fcx, false, llreturn)
1726 build_return_block(fcx, ret_cx, substd_retty);
1727 debuginfo::clear_source_location(fcx);
1731 // Builds the return block for a function.
1732 pub fn build_return_block(fcx: &FunctionContext, ret_cx: Block, retty: ty::t) {
1733 if fcx.llretslotptr.get().is_none() ||
1734 (!fcx.needs_ret_allocas && fcx.caller_expects_out_pointer) {
1735 return RetVoid(ret_cx);
1738 let retslot = if fcx.needs_ret_allocas {
1739 Load(ret_cx, fcx.llretslotptr.get().unwrap())
1741 fcx.llretslotptr.get().unwrap()
1743 let retptr = Value(retslot);
1744 match retptr.get_dominating_store(ret_cx) {
1745 // If there's only a single store to the ret slot, we can directly return
1746 // the value that was stored and omit the store and the alloca
1748 let retval = s.get_operand(0).unwrap().get();
1749 s.erase_from_parent();
1751 if retptr.has_no_uses() {
1752 retptr.erase_from_parent();
1755 let retval = if ty::type_is_bool(retty) {
1756 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1761 if fcx.caller_expects_out_pointer {
1762 store_ty(ret_cx, retval, get_param(fcx.llfn, 0), retty);
1763 return RetVoid(ret_cx);
1765 return Ret(ret_cx, retval);
1768 // Otherwise, copy the return value to the ret slot
1770 if fcx.caller_expects_out_pointer {
1771 memcpy_ty(ret_cx, get_param(fcx.llfn, 0), retslot, retty);
1772 return RetVoid(ret_cx);
1774 return Ret(ret_cx, load_ty(ret_cx, retslot, retty));
1780 #[deriving(Clone, Eq, PartialEq)]
1781 pub enum IsUnboxedClosureFlag {
1786 // trans_closure: Builds an LLVM function out of a source function.
1787 // If the function closes over its environment a closure will be
1789 pub fn trans_closure(ccx: &CrateContext,
1793 param_substs: ¶m_substs,
1795 _attributes: &[ast::Attribute],
1796 arg_types: Vec<ty::t>,
1800 is_unboxed_closure: IsUnboxedClosureFlag,
1801 maybe_load_env: <'blk, 'tcx> |Block<'blk, 'tcx>, ScopeId|
1802 -> Block<'blk, 'tcx>) {
1803 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1805 let _icx = push_ctxt("trans_closure");
1806 set_uwtable(llfndecl);
1808 debug!("trans_closure(..., param_substs={})",
1809 param_substs.repr(ccx.tcx()));
1811 let arena = TypedArena::new();
1812 let fcx = new_fn_ctxt(ccx,
1820 let mut bcx = init_function(&fcx, false, output_type);
1822 // cleanup scope for the incoming arguments
1823 let arg_scope = fcx.push_custom_cleanup_scope();
1825 let block_ty = node_id_type(bcx, body.id);
1827 // Set up arguments to the function.
1828 let monomorphized_arg_types =
1830 .map(|at| monomorphize_type(bcx, *at))
1831 .collect::<Vec<_>>();
1832 for monomorphized_arg_type in monomorphized_arg_types.iter() {
1833 debug!("trans_closure: monomorphized_arg_type: {}",
1834 ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1836 debug!("trans_closure: function lltype: {}",
1837 bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
1839 let arg_datums = if abi != RustCall {
1840 create_datums_for_fn_args(&fcx,
1841 monomorphized_arg_types.as_slice())
1843 create_datums_for_fn_args_under_call_abi(
1846 monomorphized_arg_types.as_slice())
1849 bcx = match is_unboxed_closure {
1850 NotUnboxedClosure => {
1851 copy_args_to_allocas(&fcx,
1854 decl.inputs.as_slice(),
1857 IsUnboxedClosure => {
1858 copy_unboxed_closure_args_to_allocas(
1861 decl.inputs.as_slice(),
1863 monomorphized_arg_types.as_slice())
1867 bcx = maybe_load_env(bcx, cleanup::CustomScope(arg_scope));
1869 // Up until here, IR instructions for this function have explicitly not been annotated with
1870 // source code location, so we don't step into call setup code. From here on, source location
1871 // emitting should be enabled.
1872 debuginfo::start_emitting_source_locations(&fcx);
1874 let dest = match fcx.llretslotptr.get() {
1875 Some(_) => expr::SaveIn(fcx.get_ret_slot(bcx, block_ty, "iret_slot")),
1877 assert!(type_is_zero_size(bcx.ccx(), block_ty));
1882 // This call to trans_block is the place where we bridge between
1883 // translation calls that don't have a return value (trans_crate,
1884 // trans_mod, trans_item, et cetera) and those that do
1885 // (trans_block, trans_expr, et cetera).
1886 bcx = controlflow::trans_block(bcx, body, dest);
1889 expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1890 Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1895 match fcx.llreturn.get() {
1897 Br(bcx, fcx.return_exit_block());
1898 fcx.pop_custom_cleanup_scope(arg_scope);
1901 // Microoptimization writ large: avoid creating a separate
1902 // llreturn basic block
1903 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1907 // Put return block after all other blocks.
1908 // This somewhat improves single-stepping experience in debugger.
1910 let llreturn = fcx.llreturn.get();
1911 for &llreturn in llreturn.iter() {
1912 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1916 // Insert the mandatory first few basic blocks before lltop.
1917 finish_fn(&fcx, bcx, output_type);
1920 // trans_fn: creates an LLVM function corresponding to a source language
1922 pub fn trans_fn(ccx: &CrateContext,
1926 param_substs: ¶m_substs,
1928 attrs: &[ast::Attribute]) {
1929 let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string());
1930 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1931 let _icx = push_ctxt("trans_fn");
1932 let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1933 let arg_types = ty::ty_fn_args(fn_ty);
1934 let output_type = ty::ty_fn_ret(fn_ty);
1935 let abi = ty::ty_fn_abi(fn_ty);
1951 pub fn trans_enum_variant(ccx: &CrateContext,
1952 _enum_id: ast::NodeId,
1953 variant: &ast::Variant,
1954 _args: &[ast::VariantArg],
1956 param_substs: ¶m_substs,
1957 llfndecl: ValueRef) {
1958 let _icx = push_ctxt("trans_enum_variant");
1960 trans_enum_variant_or_tuple_like_struct(
1968 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1971 args: callee::CallArgs,
1972 dest: expr::Dest) -> Result<'blk, 'tcx> {
1974 let ccx = bcx.fcx.ccx;
1975 let tcx = ccx.tcx();
1977 let result_ty = match ty::get(ctor_ty).sty {
1978 ty::ty_bare_fn(ref bft) => bft.sig.output,
1979 _ => ccx.sess().bug(
1980 format!("trans_enum_variant_constructor: \
1981 unexpected ctor return type {}",
1982 ctor_ty.repr(tcx)).as_slice())
1985 // Get location to store the result. If the user does not care about
1986 // the result, just make a stack slot
1987 let llresult = match dest {
1988 expr::SaveIn(d) => d,
1990 if !type_is_zero_size(ccx, result_ty) {
1991 alloc_ty(bcx, result_ty, "constructor_result")
1993 C_undef(type_of::type_of(ccx, result_ty))
1998 if !type_is_zero_size(ccx, result_ty) {
2000 callee::ArgExprs(exprs) => {
2001 let fields = exprs.iter().map(|x| &**x).enumerate().collect::<Vec<_>>();
2002 bcx = expr::trans_adt(bcx, result_ty, disr, fields.as_slice(),
2003 None, expr::SaveIn(llresult));
2005 _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor")
2009 // If the caller doesn't care about the result
2010 // drop the temporary we made
2011 let bcx = match dest {
2012 expr::SaveIn(_) => bcx,
2013 expr::Ignore => glue::drop_ty(bcx, llresult, result_ty)
2016 Result::new(bcx, llresult)
2019 pub fn trans_tuple_struct(ccx: &CrateContext,
2020 _fields: &[ast::StructField],
2021 ctor_id: ast::NodeId,
2022 param_substs: ¶m_substs,
2023 llfndecl: ValueRef) {
2024 let _icx = push_ctxt("trans_tuple_struct");
2026 trans_enum_variant_or_tuple_like_struct(
2034 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
2035 ctor_id: ast::NodeId,
2037 param_substs: ¶m_substs,
2038 llfndecl: ValueRef) {
2039 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2040 let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
2042 let result_ty = match ty::get(ctor_ty).sty {
2043 ty::ty_bare_fn(ref bft) => bft.sig.output,
2044 _ => ccx.sess().bug(
2045 format!("trans_enum_variant_or_tuple_like_struct: \
2046 unexpected ctor return type {}",
2047 ty_to_string(ccx.tcx(), ctor_ty)).as_slice())
2050 let arena = TypedArena::new();
2051 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
2052 param_substs, None, &arena);
2053 let bcx = init_function(&fcx, false, result_ty);
2055 assert!(!fcx.needs_ret_allocas);
2057 let arg_tys = ty::ty_fn_args(ctor_ty);
2059 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
2061 if !type_is_zero_size(fcx.ccx, result_ty) {
2062 let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot");
2063 let repr = adt::represent_type(ccx, result_ty);
2064 for (i, arg_datum) in arg_datums.into_iter().enumerate() {
2065 let lldestptr = adt::trans_field_ptr(bcx,
2070 arg_datum.store_to(bcx, lldestptr);
2072 adt::trans_set_discr(bcx, &*repr, dest, disr);
2075 finish_fn(&fcx, bcx, result_ty);
2078 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
2079 let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
2081 let levels = ccx.tcx().node_lint_levels.borrow();
2082 let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCE);
2083 let lvlsrc = match levels.find(&(id, lint_id)) {
2084 None | Some(&(lint::Allow, _)) => return,
2085 Some(&lvlsrc) => lvlsrc,
2088 let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
2090 adt::General(_, ref variants, _) => {
2091 for var in variants.iter() {
2093 for field in var.fields.iter().skip(1) {
2094 // skip the discriminant
2095 size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
2100 _ => { /* its size is either constant or unimportant */ }
2103 let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
2104 |(l, s, li), (idx, &size)|
2107 } else if size > s {
2114 // we only warn if the largest variant is at least thrice as large as
2115 // the second-largest.
2116 if largest > slargest * 3 && slargest > 0 {
2117 // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
2118 // pass for the latter already ran.
2119 lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCE,
2121 format!("enum variant is more than three times larger \
2122 ({} bytes) than the next largest (ignoring padding)",
2123 largest).as_slice());
2125 ccx.sess().span_note(enum_def.variants.get(largest_index).span,
2126 "this variant is the largest");
2130 pub struct TransItemVisitor<'a, 'tcx: 'a> {
2131 pub ccx: &'a CrateContext<'a, 'tcx>,
2134 impl<'a, 'tcx, 'v> Visitor<'v> for TransItemVisitor<'a, 'tcx> {
2135 fn visit_item(&mut self, i: &ast::Item) {
2136 trans_item(self.ccx, i);
2140 /// Enum describing the origin of an LLVM `Value`, for linkage purposes.
2141 pub enum ValueOrigin {
2142 /// The LLVM `Value` is in this context because the corresponding item was
2143 /// assigned to the current compilation unit.
2144 OriginalTranslation,
2145 /// The `Value`'s corresponding item was assigned to some other compilation
2146 /// unit, but the `Value` was translated in this context anyway because the
2147 /// item is marked `#[inline]`.
2151 /// Set the appropriate linkage for an LLVM `ValueRef` (function or global).
2152 /// If the `llval` is the direct translation of a specific Rust item, `id`
2153 /// should be set to the `NodeId` of that item. (This mapping should be
2154 /// 1-to-1, so monomorphizations and drop/visit glue should have `id` set to
2155 /// `None`.) `llval_origin` indicates whether `llval` is the translation of an
2156 /// item assigned to `ccx`'s compilation unit or an inlined copy of an item
2157 /// assigned to a different compilation unit.
2158 pub fn update_linkage(ccx: &CrateContext,
2160 id: Option<ast::NodeId>,
2161 llval_origin: ValueOrigin) {
2162 match llval_origin {
2164 // `llval` is a translation of an item defined in a separate
2165 // compilation unit. This only makes sense if there are at least
2166 // two compilation units.
2167 assert!(ccx.sess().opts.cg.codegen_units > 1);
2168 // `llval` is a copy of something defined elsewhere, so use
2169 // `AvailableExternallyLinkage` to avoid duplicating code in the
2171 llvm::SetLinkage(llval, llvm::AvailableExternallyLinkage);
2174 OriginalTranslation => {},
2178 Some(id) if ccx.reachable().contains(&id) => {
2179 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2182 // `id` does not refer to an item in `ccx.reachable`.
2183 if ccx.sess().opts.cg.codegen_units > 1 {
2184 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2186 llvm::SetLinkage(llval, llvm::InternalLinkage);
2192 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
2193 let _icx = push_ctxt("trans_item");
2195 let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
2198 ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
2199 if !generics.is_type_parameterized() {
2200 let trans_everywhere = attr::requests_inline(item.attrs.as_slice());
2201 // Ignore `trans_everywhere` for cross-crate inlined items
2202 // (`from_external`). `trans_item` will be called once for each
2203 // compilation unit that references the item, so it will still get
2204 // translated everywhere it's needed.
2205 for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2206 let llfn = get_item_val(ccx, item.id);
2208 foreign::trans_rust_fn_with_foreign_abi(ccx,
2211 item.attrs.as_slice(),
2213 ¶m_substs::empty(),
2221 ¶m_substs::empty(),
2223 item.attrs.as_slice());
2228 if is_origin { OriginalTranslation } else { InlinedCopy });
2232 // Be sure to travel more than just one layer deep to catch nested
2233 // items in blocks and such.
2234 let mut v = TransItemVisitor{ ccx: ccx };
2235 v.visit_block(&**body);
2237 ast::ItemImpl(ref generics, _, _, ref impl_items) => {
2238 meth::trans_impl(ccx,
2240 impl_items.as_slice(),
2244 ast::ItemMod(ref m) => {
2245 trans_mod(&ccx.rotate(), m);
2247 ast::ItemEnum(ref enum_definition, _) => {
2248 enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
2250 ast::ItemStatic(_, m, ref expr) => {
2251 // Recurse on the expression to catch items in blocks
2252 let mut v = TransItemVisitor{ ccx: ccx };
2253 v.visit_expr(&**expr);
2255 let trans_everywhere = attr::requests_inline(item.attrs.as_slice());
2256 for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2257 consts::trans_const(ccx, m, item.id);
2259 let g = get_item_val(ccx, item.id);
2263 if is_origin { OriginalTranslation } else { InlinedCopy });
2266 // Do static_assert checking. It can't really be done much earlier
2267 // because we need to get the value of the bool out of LLVM
2268 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
2269 if m == ast::MutMutable {
2270 ccx.sess().span_fatal(expr.span,
2271 "cannot have static_assert on a mutable \
2275 let v = ccx.const_values().borrow().get_copy(&item.id);
2277 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2278 ccx.sess().span_fatal(expr.span, "static assertion failed");
2283 ast::ItemForeignMod(ref foreign_mod) => {
2284 foreign::trans_foreign_mod(ccx, foreign_mod);
2286 ast::ItemTrait(..) => {
2287 // Inside of this trait definition, we won't be actually translating any
2288 // functions, but the trait still needs to be walked. Otherwise default
2289 // methods with items will not get translated and will cause ICE's when
2290 // metadata time comes around.
2291 let mut v = TransItemVisitor{ ccx: ccx };
2292 visit::walk_item(&mut v, item);
2294 _ => {/* fall through */ }
2298 // Translate a module. Doing this amounts to translating the items in the
2299 // module; there ends up being no artifact (aside from linkage names) of
2300 // separate modules in the compiled program. That's because modules exist
2301 // only as a convenience for humans working with the code, to organize names
2302 // and control visibility.
2303 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
2304 let _icx = push_ctxt("trans_mod");
2305 for item in m.items.iter() {
2306 trans_item(ccx, &**item);
2310 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
2312 ccx.item_symbols().borrow_mut().insert(node_id, sym);
2314 // The stack exhaustion lang item shouldn't have a split stack because
2315 // otherwise it would continue to be exhausted (bad), and both it and the
2316 // eh_personality functions need to be externally linkable.
2317 let def = ast_util::local_def(node_id);
2318 if ccx.tcx().lang_items.stack_exhausted() == Some(def) {
2319 unset_split_stack(llfn);
2320 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2322 if ccx.tcx().lang_items.eh_personality() == Some(def) {
2323 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2327 if is_entry_fn(ccx.sess(), node_id) {
2328 create_entry_wrapper(ccx, sp, llfn);
2332 fn register_fn(ccx: &CrateContext,
2335 node_id: ast::NodeId,
2338 match ty::get(node_type).sty {
2339 ty::ty_bare_fn(ref f) => {
2340 assert!(f.abi == Rust || f.abi == RustCall);
2342 _ => fail!("expected bare rust fn")
2345 let llfn = decl_rust_fn(ccx, node_type, sym.as_slice());
2346 finish_register_fn(ccx, sp, sym, node_id, llfn);
2350 pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t)
2351 -> llvm::AttrBuilder {
2352 use middle::ty::{BrAnon, ReLateBound};
2354 let (fn_sig, abi, has_env) = match ty::get(fn_ty).sty {
2355 ty::ty_closure(ref f) => (f.sig.clone(), f.abi, true),
2356 ty::ty_bare_fn(ref f) => (f.sig.clone(), f.abi, false),
2357 ty::ty_unboxed_closure(closure_did, _) => {
2358 let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
2359 let ref function_type = unboxed_closures.get(&closure_did)
2362 (function_type.sig.clone(), RustCall, true)
2364 _ => ccx.sess().bug("expected closure or function.")
2368 // Since index 0 is the return value of the llvm func, we start
2369 // at either 1 or 2 depending on whether there's an env slot or not
2370 let mut first_arg_offset = if has_env { 2 } else { 1 };
2371 let mut attrs = llvm::AttrBuilder::new();
2372 let ret_ty = fn_sig.output;
2374 // These have an odd calling convention, so we need to manually
2375 // unpack the input ty's
2376 let input_tys = match ty::get(fn_ty).sty {
2377 ty::ty_unboxed_closure(_, _) => {
2378 assert!(abi == RustCall);
2380 match ty::get(fn_sig.inputs[0]).sty {
2381 ty::ty_nil => Vec::new(),
2382 ty::ty_tup(ref inputs) => inputs.clone(),
2383 _ => ccx.sess().bug("expected tuple'd inputs")
2386 ty::ty_bare_fn(_) if abi == RustCall => {
2387 let inputs = vec![fn_sig.inputs[0]];
2389 match ty::get(fn_sig.inputs[1]).sty {
2390 ty::ty_nil => inputs,
2391 ty::ty_tup(ref t_in) => inputs.append(t_in.as_slice()),
2392 _ => ccx.sess().bug("expected tuple'd inputs")
2395 _ => fn_sig.inputs.clone()
2398 // A function pointer is called without the declaration
2399 // available, so we have to apply any attributes with ABI
2400 // implications directly to the call instruction. Right now,
2401 // the only attribute we need to worry about is `sret`.
2402 if type_of::return_uses_outptr(ccx, ret_ty) {
2403 let llret_sz = llsize_of_real(ccx, type_of::type_of(ccx, ret_ty));
2405 // The outptr can be noalias and nocapture because it's entirely
2406 // invisible to the program. We also know it's nonnull as well
2407 // as how many bytes we can dereference
2408 attrs.arg(1, llvm::StructRetAttribute)
2409 .arg(1, llvm::NoAliasAttribute)
2410 .arg(1, llvm::NoCaptureAttribute)
2411 .arg(1, llvm::DereferenceableAttribute(llret_sz));
2413 // Add one more since there's an outptr
2414 first_arg_offset += 1;
2416 // The `noalias` attribute on the return value is useful to a
2417 // function ptr caller.
2418 match ty::get(ret_ty).sty {
2419 // `~` pointer return values never alias because ownership
2421 ty::ty_uniq(it) if !ty::type_is_sized(ccx.tcx(), it) => {}
2423 attrs.ret(llvm::NoAliasAttribute);
2428 // We can also mark the return value as `dereferenceable` in certain cases
2429 match ty::get(ret_ty).sty {
2430 // These are not really pointers but pairs, (pointer, len)
2432 ty::ty_rptr(_, ty::mt { ty: it, .. }) if !ty::type_is_sized(ccx.tcx(), it) => {}
2433 ty::ty_uniq(inner) | ty::ty_rptr(_, ty::mt { ty: inner, .. }) => {
2434 let llret_sz = llsize_of_real(ccx, type_of::type_of(ccx, inner));
2435 attrs.ret(llvm::DereferenceableAttribute(llret_sz));
2440 match ty::get(ret_ty).sty {
2442 attrs.ret(llvm::ZExtAttribute);
2448 for (idx, &t) in input_tys.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
2449 match ty::get(t).sty {
2450 // this needs to be first to prevent fat pointers from falling through
2451 _ if !type_is_immediate(ccx, t) => {
2452 let llarg_sz = llsize_of_real(ccx, type_of::type_of(ccx, t));
2454 // For non-immediate arguments the callee gets its own copy of
2455 // the value on the stack, so there are no aliases. It's also
2456 // program-invisible so can't possibly capture
2457 attrs.arg(idx, llvm::NoAliasAttribute)
2458 .arg(idx, llvm::NoCaptureAttribute)
2459 .arg(idx, llvm::DereferenceableAttribute(llarg_sz));
2463 attrs.arg(idx, llvm::ZExtAttribute);
2466 // `~` pointer parameters never alias because ownership is transferred
2467 ty::ty_uniq(inner) => {
2468 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, inner));
2470 attrs.arg(idx, llvm::NoAliasAttribute)
2471 .arg(idx, llvm::DereferenceableAttribute(llsz));
2474 // The visit glue deals only with opaque pointers so we don't
2475 // actually know the concrete type of Self thus we don't know how
2476 // many bytes to mark as dereferenceable so instead we just mark
2477 // it as nonnull which still holds true
2478 ty::ty_rptr(b, ty::mt { ty: it, mutbl }) if match ty::get(it).sty {
2479 ty::ty_param(_) => true, _ => false
2480 } && mutbl == ast::MutMutable => {
2481 attrs.arg(idx, llvm::NoAliasAttribute)
2482 .arg(idx, llvm::NonNullAttribute);
2485 ReLateBound(_, BrAnon(_)) => {
2486 attrs.arg(idx, llvm::NoCaptureAttribute);
2492 // `&mut` pointer parameters never alias other parameters, or mutable global data
2494 // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as both
2495 // `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely on
2496 // memory dependencies rather than pointer equality
2497 ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable ||
2498 !ty::type_contents(ccx.tcx(), mt.ty).interior_unsafe() => {
2500 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2501 attrs.arg(idx, llvm::NoAliasAttribute)
2502 .arg(idx, llvm::DereferenceableAttribute(llsz));
2504 if mt.mutbl == ast::MutImmutable {
2505 attrs.arg(idx, llvm::ReadOnlyAttribute);
2509 ReLateBound(_, BrAnon(_)) => {
2510 attrs.arg(idx, llvm::NoCaptureAttribute);
2516 // When a reference in an argument has no named lifetime, it's impossible for that
2517 // reference to escape this function (returned or stored beyond the call by a closure).
2518 ty::ty_rptr(ReLateBound(_, BrAnon(_)), mt) => {
2519 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2520 attrs.arg(idx, llvm::NoCaptureAttribute)
2521 .arg(idx, llvm::DereferenceableAttribute(llsz));
2524 // & pointer parameters are also never null and we know exactly how
2525 // many bytes we can dereference
2526 ty::ty_rptr(_, mt) => {
2527 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2528 attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
2537 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2538 pub fn register_fn_llvmty(ccx: &CrateContext,
2541 node_id: ast::NodeId,
2543 llfty: Type) -> ValueRef {
2544 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2546 let llfn = decl_fn(ccx, sym.as_slice(), cc, llfty, ty::mk_nil());
2547 finish_register_fn(ccx, sp, sym, node_id, llfn);
2551 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2552 match *sess.entry_fn.borrow() {
2553 Some((entry_id, _)) => node_id == entry_id,
2558 // Create a _rust_main(args: ~[str]) function which will be called from the
2559 // runtime rust_start function
2560 pub fn create_entry_wrapper(ccx: &CrateContext,
2562 main_llfn: ValueRef) {
2563 let et = ccx.sess().entry_type.get().unwrap();
2565 config::EntryMain => {
2566 create_entry_fn(ccx, main_llfn, true);
2568 config::EntryStart => create_entry_fn(ccx, main_llfn, false),
2569 config::EntryNone => {} // Do nothing.
2572 fn create_entry_fn(ccx: &CrateContext,
2573 rust_main: ValueRef,
2574 use_start_lang_item: bool) {
2575 let llfty = Type::func([ccx.int_type(), Type::i8p(ccx).ptr_to()],
2578 let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil());
2580 // FIXME: #16581: Marking a symbol in the executable with `dllexport`
2581 // linkage forces MinGW's linker to output a `.reloc` section for ASLR
2582 if ccx.sess().targ_cfg.os == OsWindows {
2583 unsafe { llvm::LLVMRustSetDLLExportStorageClass(llfn) }
2586 let llbb = "top".with_c_str(|buf| {
2588 llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn, buf)
2591 let bld = ccx.raw_builder();
2593 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2595 let (start_fn, args) = if use_start_lang_item {
2596 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2598 Err(s) => { ccx.sess().fatal(s.as_slice()); }
2600 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2601 get_item_val(ccx, start_def_id.node)
2603 let start_fn_type = csearch::get_type(ccx.tcx(),
2605 trans_external_path(ccx, start_def_id, start_fn_type)
2609 let opaque_rust_main = "rust_main".with_c_str(|buf| {
2610 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
2621 debug!("using user-defined start fn");
2623 get_param(llfn, 0 as c_uint),
2624 get_param(llfn, 1 as c_uint)
2630 let result = llvm::LLVMBuildCall(bld,
2633 args.len() as c_uint,
2636 llvm::LLVMBuildRet(bld, result);
2641 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
2642 ty: ty::t, attrs: &[ast::Attribute]) -> String {
2643 match ccx.external_srcs().borrow().find(&id) {
2645 let sym = csearch::get_symbol(&ccx.sess().cstore, did);
2646 debug!("found item {} in other crate...", sym);
2652 match attr::first_attr_value_str_by_name(attrs, "export_name") {
2653 // Use provided name
2654 Some(name) => name.get().to_string(),
2656 _ => ccx.tcx().map.with_path(id, |mut path| {
2657 if attr::contains_name(attrs, "no_mangle") {
2659 path.last().unwrap().to_string()
2661 match weak_lang_items::link_name(attrs) {
2662 Some(name) => name.get().to_string(),
2664 // Usual name mangling
2665 mangle_exported_name(ccx, path, ty, id)
2673 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2674 debug!("get_item_val(id=`{:?}`)", id);
2676 match ccx.item_vals().borrow().find_copy(&id) {
2677 Some(v) => return v,
2681 let item = ccx.tcx().map.get(id);
2682 let val = match item {
2683 ast_map::NodeItem(i) => {
2684 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2685 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
2687 let v = match i.node {
2688 ast::ItemStatic(_, mutbl, ref expr) => {
2689 // If this static came from an external crate, then
2690 // we need to get the symbol from csearch instead of
2691 // using the current crate's name/version
2692 // information in the hash of the symbol
2693 debug!("making {}", sym);
2694 let is_local = !ccx.external_srcs().borrow().contains_key(&id);
2696 // We need the translated value here, because for enums the
2697 // LLVM type is not fully determined by the Rust type.
2698 let (v, inlineable, _) = consts::const_expr(ccx, &**expr, is_local);
2699 ccx.const_values().borrow_mut().insert(id, v);
2700 let mut inlineable = inlineable;
2703 let llty = llvm::LLVMTypeOf(v);
2704 let g = sym.as_slice().with_c_str(|buf| {
2705 llvm::LLVMAddGlobal(ccx.llmod(), llty, buf)
2708 // Apply the `unnamed_addr` attribute if
2710 if !ast_util::static_has_significant_address(
2712 i.attrs.as_slice()) {
2713 llvm::SetUnnamedAddr(g, true);
2715 // This is a curious case where we must make
2716 // all of these statics inlineable. If a
2717 // global is not tagged as `#[inline(never)]`,
2718 // then LLVM won't coalesce globals unless they
2719 // have an internal linkage type. This means that
2720 // external crates cannot use this global.
2721 // This is a problem for things like inner
2722 // statics in generic functions, because the
2723 // function will be inlined into another
2724 // crate and then attempt to link to the
2725 // static in the original crate, only to
2726 // find that it's not there. On the other
2727 // side of inlining, the crates knows to
2728 // not declare this static as
2729 // available_externally (because it isn't)
2733 if attr::contains_name(i.attrs.as_slice(),
2735 llvm::set_thread_local(g, true);
2739 debug!("{} not inlined", sym);
2740 ccx.non_inlineable_statics().borrow_mut()
2744 ccx.item_symbols().borrow_mut().insert(i.id, sym);
2749 ast::ItemFn(_, _, abi, _, _) => {
2750 let llfn = if abi == Rust {
2751 register_fn(ccx, i.span, sym, i.id, ty)
2753 foreign::register_rust_fn_with_foreign_abi(ccx,
2758 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2762 _ => fail!("get_item_val: weird result in table")
2765 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
2767 Some(sect) => unsafe {
2768 sect.get().with_c_str(|buf| {
2769 llvm::LLVMSetSection(v, buf);
2778 ast_map::NodeTraitItem(trait_method) => {
2779 debug!("get_item_val(): processing a NodeTraitItem");
2780 match *trait_method {
2781 ast::RequiredMethod(_) | ast::TypeTraitItem(_) => {
2782 ccx.sess().bug("unexpected variant: required trait \
2783 method in get_item_val()");
2785 ast::ProvidedMethod(ref m) => {
2786 register_method(ccx, id, &**m)
2791 ast_map::NodeImplItem(ii) => {
2793 ast::MethodImplItem(ref m) => register_method(ccx, id, &**m),
2794 ast::TypeImplItem(ref typedef) => {
2795 ccx.sess().span_bug(typedef.span,
2796 "unexpected variant: required impl \
2797 method in get_item_val()")
2802 ast_map::NodeForeignItem(ni) => {
2804 ast::ForeignItemFn(..) => {
2805 let abi = ccx.tcx().map.get_foreign_abi(id);
2806 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2807 let name = foreign::link_name(&*ni);
2808 foreign::register_foreign_item_fn(ccx, abi, ty,
2809 name.get().as_slice(),
2812 ast::ForeignItemStatic(..) => {
2813 foreign::register_static(ccx, &*ni)
2818 ast_map::NodeVariant(ref v) => {
2820 let args = match v.node.kind {
2821 ast::TupleVariantKind(ref args) => args,
2822 ast::StructVariantKind(_) => {
2823 fail!("struct variant kind unexpected in get_item_val")
2826 assert!(args.len() != 0u);
2827 let ty = ty::node_id_to_type(ccx.tcx(), id);
2828 let parent = ccx.tcx().map.get_parent(id);
2829 let enm = ccx.tcx().map.expect_item(parent);
2830 let sym = exported_name(ccx,
2833 enm.attrs.as_slice());
2835 llfn = match enm.node {
2836 ast::ItemEnum(_, _) => {
2837 register_fn(ccx, (*v).span, sym, id, ty)
2839 _ => fail!("NodeVariant, shouldn't happen")
2841 set_inline_hint(llfn);
2845 ast_map::NodeStructCtor(struct_def) => {
2846 // Only register the constructor if this is a tuple-like struct.
2847 let ctor_id = match struct_def.ctor_id {
2849 ccx.sess().bug("attempt to register a constructor of \
2850 a non-tuple-like struct")
2852 Some(ctor_id) => ctor_id,
2854 let parent = ccx.tcx().map.get_parent(id);
2855 let struct_item = ccx.tcx().map.expect_item(parent);
2856 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2857 let sym = exported_name(ccx,
2862 let llfn = register_fn(ccx, struct_item.span,
2864 set_inline_hint(llfn);
2869 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2870 variant).as_slice())
2874 // All LLVM globals and functions are initially created as external-linkage
2875 // declarations. If `trans_item`/`trans_fn` later turns the declaration
2876 // into a definition, it adjusts the linkage then (using `update_linkage`).
2878 // The exception is foreign items, which have their linkage set inside the
2879 // call to `foreign::register_*` above. We don't touch the linkage after
2880 // that (`foreign::trans_foreign_mod` doesn't adjust the linkage like the
2881 // other item translation functions do).
2883 ccx.item_vals().borrow_mut().insert(id, val);
2887 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2888 m: &ast::Method) -> ValueRef {
2889 let mty = ty::node_id_to_type(ccx.tcx(), id);
2891 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2893 let llfn = register_fn(ccx, m.span, sym, id, mty);
2894 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2898 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2900 return llvm::LLVMConstPtrToInt(v, ccx.int_type().to_ref());
2904 pub fn crate_ctxt_to_encode_parms<'a, 'tcx>(cx: &'a SharedCrateContext<'tcx>,
2905 ie: encoder::EncodeInlinedItem<'a>)
2906 -> encoder::EncodeParams<'a, 'tcx> {
2907 encoder::EncodeParams {
2908 diag: cx.sess().diagnostic(),
2910 reexports2: cx.exp_map2(),
2911 item_symbols: cx.item_symbols(),
2912 non_inlineable_statics: cx.non_inlineable_statics(),
2913 link_meta: cx.link_meta(),
2914 cstore: &cx.sess().cstore,
2915 encode_inlined_item: ie,
2916 reachable: cx.reachable(),
2920 pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
2923 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2924 *ty != config::CrateTypeExecutable
2930 let encode_inlined_item: encoder::EncodeInlinedItem =
2931 |ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii);
2933 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2934 let metadata = encoder::encode_metadata(encode_parms, krate);
2935 let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2936 .append(match flate::deflate_bytes(metadata.as_slice()) {
2937 Some(compressed) => compressed,
2939 cx.sess().fatal("failed to compress metadata")
2942 let llmeta = C_bytes_in_context(cx.metadata_llcx(), compressed.as_slice());
2943 let llconst = C_struct_in_context(cx.metadata_llcx(), [llmeta], false);
2944 let name = format!("rust_metadata_{}_{}",
2945 cx.link_meta().crate_name,
2946 cx.link_meta().crate_hash);
2947 let llglobal = name.with_c_str(|buf| {
2949 llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf)
2953 llvm::LLVMSetInitializer(llglobal, llconst);
2954 let name = loader::meta_section_name(cx.sess().targ_cfg.os);
2955 name.unwrap_or("rust_metadata").with_c_str(|buf| {
2956 llvm::LLVMSetSection(llglobal, buf)
2962 /// Find any symbols that are defined in one compilation unit, but not declared
2963 /// in any other compilation unit. Give these symbols internal linkage.
2964 fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
2965 use std::c_str::CString;
2968 let mut declared = HashSet::new();
2970 let iter_globals = |llmod| {
2972 cur: llvm::LLVMGetFirstGlobal(llmod),
2973 step: llvm::LLVMGetNextGlobal,
2977 let iter_functions = |llmod| {
2979 cur: llvm::LLVMGetFirstFunction(llmod),
2980 step: llvm::LLVMGetNextFunction,
2984 // Collect all external declarations in all compilation units.
2985 for ccx in cx.iter() {
2986 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2987 let linkage = llvm::LLVMGetLinkage(val);
2988 // We only care about external declarations (not definitions)
2989 // and available_externally definitions.
2990 if !(linkage == llvm::ExternalLinkage as c_uint &&
2991 llvm::LLVMIsDeclaration(val) != 0) &&
2992 !(linkage == llvm::AvailableExternallyLinkage as c_uint) {
2996 let name = CString::new(llvm::LLVMGetValueName(val), false);
2997 declared.insert(name);
3001 // Examine each external definition. If the definition is not used in
3002 // any other compilation unit, and is not reachable from other crates,
3003 // then give it internal linkage.
3004 for ccx in cx.iter() {
3005 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
3006 // We only care about external definitions.
3007 if !(llvm::LLVMGetLinkage(val) == llvm::ExternalLinkage as c_uint &&
3008 llvm::LLVMIsDeclaration(val) == 0) {
3012 let name = CString::new(llvm::LLVMGetValueName(val), false);
3013 if !declared.contains(&name) &&
3014 !reachable.contains_equiv(&name.as_str().unwrap()) {
3015 llvm::SetLinkage(val, llvm::InternalLinkage);
3024 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
3027 impl Iterator<ValueRef> for ValueIter {
3028 fn next(&mut self) -> Option<ValueRef> {
3031 self.cur = unsafe { (self.step)(old) };
3040 pub fn trans_crate<'tcx>(analysis: CrateAnalysis<'tcx>)
3041 -> (ty::ctxt<'tcx>, CrateTranslation) {
3042 let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, name, .. } = analysis;
3043 let krate = tcx.map.krate();
3045 // Before we touch LLVM, make sure that multithreading is enabled.
3047 use std::sync::{Once, ONCE_INIT};
3048 static mut INIT: Once = ONCE_INIT;
3049 static mut POISONED: bool = false;
3051 if llvm::LLVMStartMultithreaded() != 1 {
3052 // use an extra bool to make sure that all future usage of LLVM
3053 // cannot proceed despite the Once not running more than once.
3059 tcx.sess.bug("couldn't enable multi-threaded LLVM");
3063 let link_meta = link::build_link_meta(&tcx.sess, krate, name);
3065 let codegen_units = tcx.sess.opts.cg.codegen_units;
3066 let shared_ccx = SharedCrateContext::new(link_meta.crate_name.as_slice(),
3075 let ccx = shared_ccx.get_ccx(0);
3077 // First, verify intrinsics.
3078 intrinsic::check_intrinsics(&ccx);
3080 // Next, translate the module.
3082 let _icx = push_ctxt("text");
3083 trans_mod(&ccx, &krate.module);
3087 for ccx in shared_ccx.iter() {
3088 glue::emit_tydescs(&ccx);
3089 if ccx.sess().opts.debuginfo != NoDebugInfo {
3090 debuginfo::finalize(&ccx);
3094 // Translate the metadata.
3095 let metadata = write_metadata(&shared_ccx, krate);
3097 if shared_ccx.sess().trans_stats() {
3098 let stats = shared_ccx.stats();
3099 println!("--- trans stats ---");
3100 println!("n_static_tydescs: {}", stats.n_static_tydescs.get());
3101 println!("n_glues_created: {}", stats.n_glues_created.get());
3102 println!("n_null_glues: {}", stats.n_null_glues.get());
3103 println!("n_real_glues: {}", stats.n_real_glues.get());
3105 println!("n_fns: {}", stats.n_fns.get());
3106 println!("n_monos: {}", stats.n_monos.get());
3107 println!("n_inlines: {}", stats.n_inlines.get());
3108 println!("n_closures: {}", stats.n_closures.get());
3109 println!("fn stats:");
3110 stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
3111 insns_b.cmp(&insns_a)
3113 for tuple in stats.fn_stats.borrow().iter() {
3115 (ref name, ms, insns) => {
3116 println!("{} insns, {} ms, {}", insns, ms, *name);
3121 if shared_ccx.sess().count_llvm_insns() {
3122 for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
3123 println!("{:7u} {}", *v, *k);
3127 let modules = shared_ccx.iter()
3128 .map(|ccx| ModuleTranslation { llcx: ccx.llcx(), llmod: ccx.llmod() })
3131 let mut reachable: Vec<String> = shared_ccx.reachable().iter().filter_map(|id| {
3132 shared_ccx.item_symbols().borrow().find(id).map(|s| s.to_string())
3135 // For the purposes of LTO, we add to the reachable set all of the upstream
3136 // reachable extern fns. These functions are all part of the public ABI of
3137 // the final product, so LTO needs to preserve them.
3138 shared_ccx.sess().cstore.iter_crate_data(|cnum, _| {
3139 let syms = csearch::get_reachable_extern_fns(&shared_ccx.sess().cstore, cnum);
3140 reachable.extend(syms.into_iter().map(|did| {
3141 csearch::get_symbol(&shared_ccx.sess().cstore, did)
3145 // Make sure that some other crucial symbols are not eliminated from the
3146 // module. This includes the main function, the crate map (used for debug
3147 // log settings and I/O), and finally the curious rust_stack_exhausted
3148 // symbol. This symbol is required for use by the libmorestack library that
3149 // we link in, so we must ensure that this symbol is not internalized (if
3150 // defined in the crate).
3151 reachable.push("main".to_string());
3152 reachable.push("rust_stack_exhausted".to_string());
3154 // referenced from .eh_frame section on some platforms
3155 reachable.push("rust_eh_personality".to_string());
3156 // referenced from rt/rust_try.ll
3157 reachable.push("rust_eh_personality_catch".to_string());
3159 if codegen_units > 1 {
3160 internalize_symbols(&shared_ccx, &reachable.iter().map(|x| x.clone()).collect());
3163 let metadata_module = ModuleTranslation {
3164 llcx: shared_ccx.metadata_llcx(),
3165 llmod: shared_ccx.metadata_llmod(),
3167 let formats = shared_ccx.tcx().dependency_formats.borrow().clone();
3168 let no_builtins = attr::contains_name(krate.attrs.as_slice(), "no_builtins");
3170 let translation = CrateTranslation {
3172 metadata_module: metadata_module,
3175 reachable: reachable,
3176 crate_formats: formats,
3177 no_builtins: no_builtins,
3180 (shared_ccx.take_tcx(), translation)