]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/base.rs
4c936ddbcef00224338af15e1e1b59810db382f8
[rust.git] / src / librustc_trans / trans / base.rs
1 // Copyright 2012-2015 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.
4 //
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.
10 //! Translate the completed AST to the LLVM IR.
11 //!
12 //! Some functions here, such as trans_block and trans_expr, return a value --
13 //! the result of the translation to LLVM -- while others, such as trans_fn,
14 //! trans_impl, and trans_item, are called only for the side effect of adding a
15 //! particular definition to the LLVM IR output we're producing.
16 //!
17 //! Hopefully useful general knowledge about trans:
18 //!
19 //!   * There's no way to find out the Ty type of a ValueRef.  Doing so
20 //!     would be "trying to get the eggs out of an omelette" (credit:
21 //!     pcwalton).  You can, instead, find out its TypeRef by calling val_ty,
22 //!     but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
23 //!     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
24
25 #![allow(non_camel_case_types)]
26
27 pub use self::ValueOrigin::*;
28
29 use super::CrateTranslation;
30 use super::ModuleTranslation;
31
32 use back::link::mangle_exported_name;
33 use back::{link, abi};
34 use lint;
35 use llvm::{BasicBlockRef, Linkage, ValueRef, Vector, get_param};
36 use llvm;
37 use metadata::{csearch, encoder, loader};
38 use middle::astencode;
39 use middle::cfg;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::weak_lang_items;
42 use middle::subst::Substs;
43 use middle::ty::{self, Ty, ClosureTyper, type_is_simd, simd_size};
44 use session::config::{self, NoDebugInfo};
45 use session::Session;
46 use trans::_match;
47 use trans::adt;
48 use trans::attributes;
49 use trans::build::*;
50 use trans::builder::{Builder, noname};
51 use trans::callee;
52 use trans::cleanup::CleanupMethods;
53 use trans::cleanup;
54 use trans::closure;
55 use trans::common::{Block, C_bool, C_bytes_in_context, C_i32, C_int, C_integral};
56 use trans::common::{C_null, C_struct_in_context, C_u64, C_u8, C_undef};
57 use trans::common::{CrateContext, FunctionContext};
58 use trans::common::{Result, NodeIdAndSpan};
59 use trans::common::{node_id_type, return_type_is_void};
60 use trans::common::{type_is_immediate, type_is_zero_size, val_ty};
61 use trans::common;
62 use trans::consts;
63 use trans::context::SharedCrateContext;
64 use trans::controlflow;
65 use trans::datum;
66 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
67 use trans::declare;
68 use trans::expr;
69 use trans::foreign;
70 use trans::glue;
71 use trans::intrinsic;
72 use trans::machine;
73 use trans::machine::{llsize_of, llsize_of_real};
74 use trans::meth;
75 use trans::monomorphize;
76 use trans::tvec;
77 use trans::type_::Type;
78 use trans::type_of;
79 use trans::type_of::*;
80 use trans::value::Value;
81 use util::common::indenter;
82 use util::ppaux::{Repr, ty_to_string};
83 use util::sha2::Sha256;
84 use util::nodemap::NodeMap;
85
86 use arena::TypedArena;
87 use libc::c_uint;
88 use std::ffi::{CStr, CString};
89 use std::cell::{Cell, RefCell};
90 use std::collections::HashSet;
91 use std::mem;
92 use std::str;
93 use std::{i8, i16, i32, i64};
94 use syntax::abi::{Rust, RustCall, RustIntrinsic, Abi};
95 use syntax::ast_util::local_def;
96 use syntax::attr::AttrMetaMethods;
97 use syntax::attr;
98 use syntax::codemap::Span;
99 use syntax::parse::token::InternedString;
100 use syntax::visit::Visitor;
101 use syntax::visit;
102 use syntax::{ast, ast_util, ast_map};
103
104 thread_local! {
105     static TASK_LOCAL_INSN_KEY: RefCell<Option<Vec<&'static str>>> = {
106         RefCell::new(None)
107     }
108 }
109
110 pub fn with_insn_ctxt<F>(blk: F) where
111     F: FnOnce(&[&'static str]),
112 {
113     TASK_LOCAL_INSN_KEY.with(move |slot| {
114         slot.borrow().as_ref().map(move |s| blk(s));
115     })
116 }
117
118 pub fn init_insn_ctxt() {
119     TASK_LOCAL_INSN_KEY.with(|slot| {
120         *slot.borrow_mut() = Some(Vec::new());
121     });
122 }
123
124 pub struct _InsnCtxt {
125     _cannot_construct_outside_of_this_module: ()
126 }
127
128 impl Drop for _InsnCtxt {
129     fn drop(&mut self) {
130         TASK_LOCAL_INSN_KEY.with(|slot| {
131             match slot.borrow_mut().as_mut() {
132                 Some(ctx) => { ctx.pop(); }
133                 None => {}
134             }
135         })
136     }
137 }
138
139 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
140     debug!("new InsnCtxt: {}", s);
141     TASK_LOCAL_INSN_KEY.with(|slot| {
142         match slot.borrow_mut().as_mut() {
143             Some(ctx) => ctx.push(s),
144             None => {}
145         }
146     });
147     _InsnCtxt { _cannot_construct_outside_of_this_module: () }
148 }
149
150 pub struct StatRecorder<'a, 'tcx: 'a> {
151     ccx: &'a CrateContext<'a, 'tcx>,
152     name: Option<String>,
153     istart: usize,
154 }
155
156 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
157     pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String)
158                -> StatRecorder<'a, 'tcx> {
159         let istart = ccx.stats().n_llvm_insns.get();
160         StatRecorder {
161             ccx: ccx,
162             name: Some(name),
163             istart: istart,
164         }
165     }
166 }
167
168 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
169     fn drop(&mut self) {
170         if self.ccx.sess().trans_stats() {
171             let iend = self.ccx.stats().n_llvm_insns.get();
172             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);
177         }
178     }
179 }
180
181 fn get_extern_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty: Ty<'tcx>,
182                                 name: &str, did: ast::DefId) -> ValueRef {
183     match ccx.externs().borrow().get(name) {
184         Some(n) => return *n,
185         None => ()
186     }
187
188     let f = declare::declare_rust_fn(ccx, name, fn_ty);
189
190     let attrs = csearch::get_item_attrs(&ccx.sess().cstore, did);
191     attributes::from_fn_attrs(ccx, &attrs[..], f);
192
193     ccx.externs().borrow_mut().insert(name.to_string(), f);
194     f
195 }
196
197 pub fn self_type_for_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
198                                        closure_id: ast::DefId,
199                                        fn_ty: Ty<'tcx>)
200                                        -> Ty<'tcx>
201 {
202     let closure_kind = ccx.tcx().closure_kind(closure_id);
203     match closure_kind {
204         ty::FnClosureKind => {
205             ty::mk_imm_rptr(ccx.tcx(), ccx.tcx().mk_region(ty::ReStatic), fn_ty)
206         }
207         ty::FnMutClosureKind => {
208             ty::mk_mut_rptr(ccx.tcx(), ccx.tcx().mk_region(ty::ReStatic), fn_ty)
209         }
210         ty::FnOnceClosureKind => fn_ty
211     }
212 }
213
214 pub fn kind_for_closure(ccx: &CrateContext, closure_id: ast::DefId) -> ty::ClosureKind {
215     *ccx.tcx().closure_kinds.borrow().get(&closure_id).unwrap()
216 }
217
218 pub fn get_extern_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId,
219                                   t: Ty<'tcx>) -> ValueRef {
220     let name = csearch::get_symbol(&ccx.sess().cstore, did);
221     let ty = type_of(ccx, t);
222     match ccx.externs().borrow_mut().get(&name) {
223         Some(n) => return *n,
224         None => ()
225     }
226     // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
227     // FIXME(nagisa): investigate whether it can be changed into define_global
228     let c = declare::declare_global(ccx, &name[..], ty);
229     // Thread-local statics in some other crate need to *always* be linked
230     // against in a thread-local fashion, so we need to be sure to apply the
231     // thread-local attribute locally if it was present remotely. If we
232     // don't do this then linker errors can be generated where the linker
233     // complains that one object files has a thread local version of the
234     // symbol and another one doesn't.
235     for attr in &*ty::get_attrs(ccx.tcx(), did) {
236         if attr.check_name("thread_local") {
237             llvm::set_thread_local(c, true);
238         }
239     }
240     ccx.externs().borrow_mut().insert(name.to_string(), c);
241     return c;
242 }
243
244 fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
245                                 info_ty: Ty<'tcx>, it: LangItem) -> ast::DefId {
246     match bcx.tcx().lang_items.require(it) {
247         Ok(id) => id,
248         Err(s) => {
249             bcx.sess().fatal(&format!("allocation of `{}` {}",
250                                      bcx.ty_to_string(info_ty),
251                                      s));
252         }
253     }
254 }
255
256 // The following malloc_raw_dyn* functions allocate a box to contain
257 // a given type, but with a potentially dynamic size.
258
259 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
260                                   llty_ptr: Type,
261                                   info_ty: Ty<'tcx>,
262                                   size: ValueRef,
263                                   align: ValueRef,
264                                   debug_loc: DebugLoc)
265                                   -> Result<'blk, 'tcx> {
266     let _icx = push_ctxt("malloc_raw_exchange");
267
268     // Allocate space:
269     let r = callee::trans_lang_call(bcx,
270         require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem),
271         &[size, align],
272         None,
273         debug_loc);
274
275     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
276 }
277
278
279 pub fn bin_op_to_icmp_predicate(ccx: &CrateContext, op: ast::BinOp_, signed: bool)
280                                 -> llvm::IntPredicate {
281     match op {
282         ast::BiEq => llvm::IntEQ,
283         ast::BiNe => llvm::IntNE,
284         ast::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
285         ast::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
286         ast::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
287         ast::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
288         op => {
289             ccx.sess().bug(&format!("comparison_op_to_icmp_predicate: expected \
290                                      comparison operator, found {:?}", op));
291         }
292     }
293 }
294
295 pub fn bin_op_to_fcmp_predicate(ccx: &CrateContext, op: ast::BinOp_)
296                                 -> llvm::RealPredicate {
297     match op {
298         ast::BiEq => llvm::RealOEQ,
299         ast::BiNe => llvm::RealUNE,
300         ast::BiLt => llvm::RealOLT,
301         ast::BiLe => llvm::RealOLE,
302         ast::BiGt => llvm::RealOGT,
303         ast::BiGe => llvm::RealOGE,
304         op => {
305             ccx.sess().bug(&format!("comparison_op_to_fcmp_predicate: expected \
306                                      comparison operator, found {:?}", op));
307         }
308     }
309 }
310
311 pub fn compare_scalar_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
312                                         lhs: ValueRef,
313                                         rhs: ValueRef,
314                                         t: Ty<'tcx>,
315                                         op: ast::BinOp_,
316                                         debug_loc: DebugLoc)
317                                         -> ValueRef {
318     match t.sty {
319         ty::ty_tup(ref tys) if tys.is_empty() => {
320             // We don't need to do actual comparisons for nil.
321             // () == () holds but () < () does not.
322             match op {
323                 ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(bcx.ccx(), true),
324                 ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(bcx.ccx(), false),
325                 // refinements would be nice
326                 _ => bcx.sess().bug("compare_scalar_types: must be a comparison operator")
327             }
328         }
329         ty::ty_bare_fn(..) | ty::ty_bool | ty::ty_uint(_) | ty::ty_char => {
330             ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, false), lhs, rhs, debug_loc)
331         }
332         ty::ty_ptr(mt) if common::type_is_sized(bcx.tcx(), mt.ty) => {
333             ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, false), lhs, rhs, debug_loc)
334         }
335         ty::ty_int(_) => {
336             ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, true), lhs, rhs, debug_loc)
337         }
338         ty::ty_float(_) => {
339             FCmp(bcx, bin_op_to_fcmp_predicate(bcx.ccx(), op), lhs, rhs, debug_loc)
340         }
341         // Should never get here, because t is scalar.
342         _ => bcx.sess().bug("non-scalar type passed to compare_scalar_types")
343     }
344 }
345
346 pub fn compare_simd_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
347                                       lhs: ValueRef,
348                                       rhs: ValueRef,
349                                       t: Ty<'tcx>,
350                                       op: ast::BinOp_,
351                                       debug_loc: DebugLoc)
352                                       -> ValueRef {
353     let signed = match t.sty {
354         ty::ty_float(_) => {
355             // The comparison operators for floating point vectors are challenging.
356             // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
357             // then bitcast to a floating point vector, the result will be `-NaN`
358             // for each truth value. Because of this they are unsupported.
359             bcx.sess().bug("compare_simd_types: comparison operators \
360                             not supported for floating point SIMD types")
361         },
362         ty::ty_uint(_) => false,
363         ty::ty_int(_) => true,
364         _ => bcx.sess().bug("compare_simd_types: invalid SIMD type"),
365     };
366
367     let cmp = bin_op_to_icmp_predicate(bcx.ccx(), op, signed);
368     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
369     // to get the correctly sized type. This will compile to a single instruction
370     // once the IR is converted to assembly if the SIMD instruction is supported
371     // by the target architecture.
372     SExt(bcx, ICmp(bcx, cmp, lhs, rhs, debug_loc), val_ty(lhs))
373 }
374
375 // Iterates through the elements of a structural type.
376 pub fn iter_structural_ty<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
377                                          av: ValueRef,
378                                          t: Ty<'tcx>,
379                                          mut f: F)
380                                          -> Block<'blk, 'tcx> where
381     F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
382 {
383     let _icx = push_ctxt("iter_structural_ty");
384
385     fn iter_variant<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
386                                    repr: &adt::Repr<'tcx>,
387                                    av: ValueRef,
388                                    variant: &ty::VariantInfo<'tcx>,
389                                    substs: &Substs<'tcx>,
390                                    f: &mut F)
391                                    -> Block<'blk, 'tcx> where
392         F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
393     {
394         let _icx = push_ctxt("iter_variant");
395         let tcx = cx.tcx();
396         let mut cx = cx;
397
398         for (i, &arg) in variant.args.iter().enumerate() {
399             let arg = monomorphize::apply_param_substs(tcx, substs, &arg);
400             cx = f(cx, adt::trans_field_ptr(cx, repr, av, variant.disr_val, i), arg);
401         }
402         return cx;
403     }
404
405     let (data_ptr, info) = if common::type_is_sized(cx.tcx(), t) {
406         (av, None)
407     } else {
408         let data = GEPi(cx, av, &[0, abi::FAT_PTR_ADDR]);
409         let info = GEPi(cx, av, &[0, abi::FAT_PTR_EXTRA]);
410         (Load(cx, data), Some(Load(cx, info)))
411     };
412
413     let mut cx = cx;
414     match t.sty {
415       ty::ty_struct(..) => {
416           let repr = adt::represent_type(cx.ccx(), t);
417           expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
418               for (i, field_ty) in field_tys.iter().enumerate() {
419                   let field_ty = field_ty.mt.ty;
420                   let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, discr, i);
421
422                   let val = if common::type_is_sized(cx.tcx(), field_ty) {
423                       llfld_a
424                   } else {
425                       let scratch = datum::rvalue_scratch_datum(cx, field_ty, "__fat_ptr_iter");
426                       Store(cx, llfld_a, GEPi(cx, scratch.val, &[0, abi::FAT_PTR_ADDR]));
427                       Store(cx, info.unwrap(), GEPi(cx, scratch.val, &[0, abi::FAT_PTR_EXTRA]));
428                       scratch.val
429                   };
430                   cx = f(cx, val, field_ty);
431               }
432           })
433       }
434       ty::ty_closure(def_id, substs) => {
435           let repr = adt::represent_type(cx.ccx(), t);
436           let typer = common::NormalizingClosureTyper::new(cx.tcx());
437           let upvars = typer.closure_upvars(def_id, substs).unwrap();
438           for (i, upvar) in upvars.iter().enumerate() {
439               let llupvar = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
440               cx = f(cx, llupvar, upvar.ty);
441           }
442       }
443       ty::ty_vec(_, Some(n)) => {
444         let (base, len) = tvec::get_fixed_base_and_len(cx, data_ptr, n);
445         let unit_ty = ty::sequence_element_type(cx.tcx(), t);
446         cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
447       }
448       ty::ty_vec(_, None) | ty::ty_str => {
449         let unit_ty = ty::sequence_element_type(cx.tcx(), t);
450         cx = tvec::iter_vec_raw(cx, data_ptr, unit_ty, info.unwrap(), f);
451       }
452       ty::ty_tup(ref args) => {
453           let repr = adt::represent_type(cx.ccx(), t);
454           for (i, arg) in args.iter().enumerate() {
455               let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
456               cx = f(cx, llfld_a, *arg);
457           }
458       }
459       ty::ty_enum(tid, substs) => {
460           let fcx = cx.fcx;
461           let ccx = fcx.ccx;
462
463           let repr = adt::represent_type(ccx, t);
464           let variants = ty::enum_variants(ccx.tcx(), tid);
465           let n_variants = (*variants).len();
466
467           // NB: we must hit the discriminant first so that structural
468           // comparison know not to proceed when the discriminants differ.
469
470           match adt::trans_switch(cx, &*repr, av) {
471               (_match::Single, None) => {
472                   if n_variants != 0 {
473                       assert!(n_variants == 1);
474                       cx = iter_variant(cx, &*repr, av, &*(*variants)[0],
475                                         substs, &mut f);
476                   }
477               }
478               (_match::Switch, Some(lldiscrim_a)) => {
479                   cx = f(cx, lldiscrim_a, cx.tcx().types.isize);
480                   let unr_cx = fcx.new_temp_block("enum-iter-unr");
481                   Unreachable(unr_cx);
482                   let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
483                                         n_variants);
484                   let next_cx = fcx.new_temp_block("enum-iter-next");
485
486                   for variant in &(*variants) {
487                       let variant_cx =
488                           fcx.new_temp_block(
489                               &format!("enum-iter-variant-{}",
490                                       &variant.disr_val.to_string())
491                               );
492                       match adt::trans_case(cx, &*repr, variant.disr_val) {
493                           _match::SingleResult(r) => {
494                               AddCase(llswitch, r.val, variant_cx.llbb)
495                           }
496                           _ => ccx.sess().unimpl("value from adt::trans_case \
497                                                   in iter_structural_ty")
498                       }
499                       let variant_cx =
500                           iter_variant(variant_cx,
501                                        &*repr,
502                                        data_ptr,
503                                        &**variant,
504                                        substs,
505                                        &mut f);
506                       Br(variant_cx, next_cx.llbb, DebugLoc::None);
507                   }
508                   cx = next_cx;
509               }
510               _ => ccx.sess().unimpl("value from adt::trans_switch \
511                                       in iter_structural_ty")
512           }
513       }
514       _ => {
515           cx.sess().unimpl(&format!("type in iter_structural_ty: {}",
516                                    ty_to_string(cx.tcx(), t)))
517       }
518     }
519     return cx;
520 }
521
522 pub fn cast_shift_expr_rhs(cx: Block,
523                            op: ast::BinOp_,
524                            lhs: ValueRef,
525                            rhs: ValueRef)
526                            -> ValueRef {
527     cast_shift_rhs(op, lhs, rhs,
528                    |a,b| Trunc(cx, a, b),
529                    |a,b| ZExt(cx, a, b))
530 }
531
532 pub fn cast_shift_const_rhs(op: ast::BinOp_,
533                             lhs: ValueRef, rhs: ValueRef) -> ValueRef {
534     cast_shift_rhs(op, lhs, rhs,
535                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
536                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
537 }
538
539 fn cast_shift_rhs<F, G>(op: ast::BinOp_,
540                         lhs: ValueRef,
541                         rhs: ValueRef,
542                         trunc: F,
543                         zext: G)
544                         -> ValueRef where
545     F: FnOnce(ValueRef, Type) -> ValueRef,
546     G: FnOnce(ValueRef, Type) -> ValueRef,
547 {
548     // Shifts may have any size int on the rhs
549     if ast_util::is_shift_binop(op) {
550         let mut rhs_llty = val_ty(rhs);
551         let mut lhs_llty = val_ty(lhs);
552         if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
553         if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
554         let rhs_sz = rhs_llty.int_width();
555         let lhs_sz = lhs_llty.int_width();
556         if lhs_sz < rhs_sz {
557             trunc(rhs, lhs_llty)
558         } else if lhs_sz > rhs_sz {
559             // FIXME (#1877: If shifting by negative
560             // values becomes not undefined then this is wrong.
561             zext(rhs, lhs_llty)
562         } else {
563             rhs
564         }
565     } else {
566         rhs
567     }
568 }
569
570 pub fn llty_and_min_for_signed_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
571                                               val_t: Ty<'tcx>) -> (Type, u64) {
572     match val_t.sty {
573         ty::ty_int(t) => {
574             let llty = Type::int_from_ty(cx.ccx(), t);
575             let min = match t {
576                 ast::TyIs if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
577                 ast::TyIs => i64::MIN as u64,
578                 ast::TyI8 => i8::MIN as u64,
579                 ast::TyI16 => i16::MIN as u64,
580                 ast::TyI32 => i32::MIN as u64,
581                 ast::TyI64 => i64::MIN as u64,
582             };
583             (llty, min)
584         }
585         _ => unreachable!(),
586     }
587 }
588
589 pub fn fail_if_zero_or_overflows<'blk, 'tcx>(
590                                 cx: Block<'blk, 'tcx>,
591                                 call_info: NodeIdAndSpan,
592                                 divrem: ast::BinOp,
593                                 lhs: ValueRef,
594                                 rhs: ValueRef,
595                                 rhs_t: Ty<'tcx>)
596                                 -> Block<'blk, 'tcx> {
597     let (zero_text, overflow_text) = if divrem.node == ast::BiDiv {
598         ("attempted to divide by zero",
599          "attempted to divide with overflow")
600     } else {
601         ("attempted remainder with a divisor of zero",
602          "attempted remainder with overflow")
603     };
604     let debug_loc = call_info.debug_loc();
605
606     let (is_zero, is_signed) = match rhs_t.sty {
607         ty::ty_int(t) => {
608             let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0, false);
609             (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), true)
610         }
611         ty::ty_uint(t) => {
612             let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0, false);
613             (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), false)
614         }
615         ty::ty_struct(_, _) if type_is_simd(cx.tcx(), rhs_t) => {
616             let mut res = C_bool(cx.ccx(), false);
617             for i in 0 .. simd_size(cx.tcx(), rhs_t) {
618                 res = Or(cx, res,
619                          IsNull(cx,
620                                 ExtractElement(cx, rhs, C_int(cx.ccx(), i as i64))), debug_loc);
621             }
622             (res, false)
623         }
624         _ => {
625             cx.sess().bug(&format!("fail-if-zero on unexpected type: {}",
626                                   ty_to_string(cx.tcx(), rhs_t)));
627         }
628     };
629     let bcx = with_cond(cx, is_zero, |bcx| {
630         controlflow::trans_fail(bcx, call_info, InternedString::new(zero_text))
631     });
632
633     // To quote LLVM's documentation for the sdiv instruction:
634     //
635     //      Division by zero leads to undefined behavior. Overflow also leads
636     //      to undefined behavior; this is a rare case, but can occur, for
637     //      example, by doing a 32-bit division of -2147483648 by -1.
638     //
639     // In order to avoid undefined behavior, we perform runtime checks for
640     // signed division/remainder which would trigger overflow. For unsigned
641     // integers, no action beyond checking for zero need be taken.
642     if is_signed {
643         let (llty, min) = llty_and_min_for_signed_ty(cx, rhs_t);
644         let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
645                              C_integral(llty, !0, false), debug_loc);
646         with_cond(bcx, minus_one, |bcx| {
647             let is_min = ICmp(bcx, llvm::IntEQ, lhs,
648                               C_integral(llty, min, true), debug_loc);
649             with_cond(bcx, is_min, |bcx| {
650                 controlflow::trans_fail(bcx,
651                                         call_info,
652                                         InternedString::new(overflow_text))
653             })
654         })
655     } else {
656         bcx
657     }
658 }
659
660 pub fn trans_external_path<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
661                                      did: ast::DefId, t: Ty<'tcx>) -> ValueRef {
662     let name = csearch::get_symbol(&ccx.sess().cstore, did);
663     match t.sty {
664         ty::ty_bare_fn(_, ref fn_ty) => {
665             match ccx.sess().target.target.adjust_abi(fn_ty.abi) {
666                 Rust | RustCall => {
667                     get_extern_rust_fn(ccx, t, &name[..], did)
668                 }
669                 RustIntrinsic => {
670                     ccx.sess().bug("unexpected intrinsic in trans_external_path")
671                 }
672                 _ => {
673                     let llfn = foreign::register_foreign_item_fn(ccx, fn_ty.abi,
674                                                                  t, &name);
675                     let attrs = csearch::get_item_attrs(&ccx.sess().cstore, did);
676                     attributes::from_fn_attrs(ccx, &attrs, llfn);
677                     llfn
678                 }
679             }
680         }
681         _ => {
682             get_extern_const(ccx, did, t)
683         }
684     }
685 }
686
687 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
688                           llfn: ValueRef,
689                           llargs: &[ValueRef],
690                           fn_ty: Ty<'tcx>,
691                           debug_loc: DebugLoc)
692                           -> (ValueRef, Block<'blk, 'tcx>) {
693     let _icx = push_ctxt("invoke_");
694     if bcx.unreachable.get() {
695         return (C_null(Type::i8(bcx.ccx())), bcx);
696     }
697
698     let attributes = attributes::from_fn_type(bcx.ccx(), fn_ty);
699
700     match bcx.opt_node_id {
701         None => {
702             debug!("invoke at ???");
703         }
704         Some(id) => {
705             debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
706         }
707     }
708
709     if need_invoke(bcx) {
710         debug!("invoking {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
711         for &llarg in llargs {
712             debug!("arg: {}", bcx.val_to_string(llarg));
713         }
714         let normal_bcx = bcx.fcx.new_temp_block("normal-return");
715         let landing_pad = bcx.fcx.get_landing_pad();
716
717         let llresult = Invoke(bcx,
718                               llfn,
719                               &llargs[..],
720                               normal_bcx.llbb,
721                               landing_pad,
722                               Some(attributes),
723                               debug_loc);
724         return (llresult, normal_bcx);
725     } else {
726         debug!("calling {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
727         for &llarg in llargs {
728             debug!("arg: {}", bcx.val_to_string(llarg));
729         }
730
731         let llresult = Call(bcx,
732                             llfn,
733                             &llargs[..],
734                             Some(attributes),
735                             debug_loc);
736         return (llresult, bcx);
737     }
738 }
739
740 pub fn need_invoke(bcx: Block) -> bool {
741     if bcx.sess().no_landing_pads() {
742         return false;
743     }
744
745     // Avoid using invoke if we are already inside a landing pad.
746     if bcx.is_lpad {
747         return false;
748     }
749
750     bcx.fcx.needs_invoke()
751 }
752
753 pub fn load_if_immediate<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
754                                      v: ValueRef, t: Ty<'tcx>) -> ValueRef {
755     let _icx = push_ctxt("load_if_immediate");
756     if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
757     return v;
758 }
759
760 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
761 /// differs from the type used for SSA values. Also handles various special cases where the type
762 /// gives us better information about what we are loading.
763 pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
764                            ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
765     if cx.unreachable.get() || type_is_zero_size(cx.ccx(), t) {
766         return C_undef(type_of::type_of(cx.ccx(), t));
767     }
768
769     let ptr = to_arg_ty_ptr(cx, ptr, t);
770     let align = type_of::align_of(cx.ccx(), t);
771
772     if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
773         let load = Load(cx, ptr);
774         unsafe {
775             llvm::LLVMSetAlignment(load, align);
776         }
777         return load;
778     }
779
780     unsafe {
781         let global = llvm::LLVMIsAGlobalVariable(ptr);
782         if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
783             let val = llvm::LLVMGetInitializer(global);
784             if !val.is_null() {
785                 return from_arg_ty(cx, val, t);
786             }
787         }
788     }
789
790     let val =  if ty::type_is_bool(t) {
791         LoadRangeAssert(cx, ptr, 0, 2, llvm::False)
792     } else if ty::type_is_char(t) {
793         // a char is a Unicode codepoint, and so takes values from 0
794         // to 0x10FFFF inclusive only.
795         LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
796     } else if (ty::type_is_region_ptr(t) || ty::type_is_unique(t))
797         && !common::type_is_fat_ptr(cx.tcx(), t) {
798             LoadNonNull(cx, ptr)
799     } else {
800         Load(cx, ptr)
801     };
802
803     unsafe {
804         llvm::LLVMSetAlignment(val, align);
805     }
806
807     from_arg_ty(cx, val, t)
808 }
809
810 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
811 /// differs from the type used for SSA values.
812 pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
813     if cx.unreachable.get() {
814         return;
815     }
816
817     let store = Store(cx, to_arg_ty(cx, v, t), to_arg_ty_ptr(cx, dst, t));
818     unsafe {
819         llvm::LLVMSetAlignment(store, type_of::align_of(cx.ccx(), t));
820     }
821 }
822
823 pub fn to_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
824     if ty::type_is_bool(ty) {
825         ZExt(bcx, val, Type::i8(bcx.ccx()))
826     } else {
827         val
828     }
829 }
830
831 pub fn from_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
832     if ty::type_is_bool(ty) {
833         Trunc(bcx, val, Type::i1(bcx.ccx()))
834     } else {
835         val
836     }
837 }
838
839 pub fn to_arg_ty_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef, ty: Ty<'tcx>) -> ValueRef {
840     if type_is_immediate(bcx.ccx(), ty) && type_of::type_of(bcx.ccx(), ty).is_aggregate() {
841         // We want to pass small aggregates as immediate values, but using an aggregate LLVM type
842         // for this leads to bad optimizations, so its arg type is an appropriately sized integer
843         // and we have to convert it
844         BitCast(bcx, ptr, type_of::arg_type_of(bcx.ccx(), ty).ptr_to())
845     } else {
846         ptr
847     }
848 }
849
850 pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &ast::Local)
851                               -> Block<'blk, 'tcx> {
852     debug!("init_local(bcx={}, local.id={})", bcx.to_str(), local.id);
853     let _indenter = indenter();
854     let _icx = push_ctxt("init_local");
855     _match::store_local(bcx, local)
856 }
857
858 pub fn raw_block<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
859                              is_lpad: bool,
860                              llbb: BasicBlockRef)
861                              -> Block<'blk, 'tcx> {
862     common::BlockS::new(llbb, is_lpad, None, fcx)
863 }
864
865 pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
866                                 val: ValueRef,
867                                 f: F)
868                                 -> Block<'blk, 'tcx> where
869     F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>,
870 {
871     let _icx = push_ctxt("with_cond");
872
873     if bcx.unreachable.get() ||
874             (common::is_const(val) && common::const_to_uint(val) == 0) {
875         return bcx;
876     }
877
878     let fcx = bcx.fcx;
879     let next_cx = fcx.new_temp_block("next");
880     let cond_cx = fcx.new_temp_block("cond");
881     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb, DebugLoc::None);
882     let after_cx = f(cond_cx);
883     if !after_cx.terminated.get() {
884         Br(after_cx, next_cx.llbb, DebugLoc::None);
885     }
886     next_cx
887 }
888
889 pub fn call_lifetime_start(cx: Block, ptr: ValueRef) {
890     if cx.sess().opts.optimize == config::No {
891         return;
892     }
893
894     let _icx = push_ctxt("lifetime_start");
895     let ccx = cx.ccx();
896
897     let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
898     let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
899     let lifetime_start = ccx.get_intrinsic(&"llvm.lifetime.start");
900     Call(cx, lifetime_start, &[llsize, ptr], None, DebugLoc::None);
901 }
902
903 pub fn call_lifetime_end(cx: Block, ptr: ValueRef) {
904     if cx.sess().opts.optimize == config::No {
905         return;
906     }
907
908     let _icx = push_ctxt("lifetime_end");
909     let ccx = cx.ccx();
910
911     let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
912     let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
913     let lifetime_end = ccx.get_intrinsic(&"llvm.lifetime.end");
914     Call(cx, lifetime_end, &[llsize, ptr], None, DebugLoc::None);
915 }
916
917 pub fn call_memcpy(cx: Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
918     let _icx = push_ctxt("call_memcpy");
919     let ccx = cx.ccx();
920     let key = match &ccx.sess().target.target.target_pointer_width[..] {
921         "32" => "llvm.memcpy.p0i8.p0i8.i32",
922         "64" => "llvm.memcpy.p0i8.p0i8.i64",
923         tws => panic!("Unsupported target word size for memcpy: {}", tws),
924     };
925     let memcpy = ccx.get_intrinsic(&key);
926     let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
927     let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
928     let size = IntCast(cx, n_bytes, ccx.int_type());
929     let align = C_i32(ccx, align as i32);
930     let volatile = C_bool(ccx, false);
931     Call(cx, memcpy, &[dst_ptr, src_ptr, size, align, volatile], None, DebugLoc::None);
932 }
933
934 pub fn memcpy_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
935                              dst: ValueRef, src: ValueRef,
936                              t: Ty<'tcx>) {
937     let _icx = push_ctxt("memcpy_ty");
938     let ccx = bcx.ccx();
939     if ty::type_is_structural(t) {
940         let llty = type_of::type_of(ccx, t);
941         let llsz = llsize_of(ccx, llty);
942         let llalign = type_of::align_of(ccx, t);
943         call_memcpy(bcx, dst, src, llsz, llalign as u32);
944     } else {
945         store_ty(bcx, load_ty(bcx, src, t), dst, t);
946     }
947 }
948
949 pub fn drop_done_fill_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
950     if cx.unreachable.get() { return; }
951     let _icx = push_ctxt("drop_done_fill_mem");
952     let bcx = cx;
953     memfill(&B(bcx), llptr, t, adt::DTOR_DONE);
954 }
955
956 pub fn init_zero_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
957     if cx.unreachable.get() { return; }
958     let _icx = push_ctxt("init_zero_mem");
959     let bcx = cx;
960     memfill(&B(bcx), llptr, t, 0);
961 }
962
963 // Always use this function instead of storing a constant byte to the memory
964 // in question. e.g. if you store a zero constant, LLVM will drown in vreg
965 // allocation for large data structures, and the generated code will be
966 // awful. (A telltale sign of this is large quantities of
967 // `mov [byte ptr foo],0` in the generated code.)
968 fn memfill<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>, byte: u8) {
969     let _icx = push_ctxt("memfill");
970     let ccx = b.ccx;
971
972     let llty = type_of::type_of(ccx, ty);
973
974     let intrinsic_key = match &ccx.sess().target.target.target_pointer_width[..] {
975         "32" => "llvm.memset.p0i8.i32",
976         "64" => "llvm.memset.p0i8.i64",
977         tws => panic!("Unsupported target word size for memset: {}", tws),
978     };
979
980     let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
981     let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
982     let llzeroval = C_u8(ccx, byte as usize);
983     let size = machine::llsize_of(ccx, llty);
984     let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
985     let volatile = C_bool(ccx, false);
986     b.call(llintrinsicfn, &[llptr, llzeroval, size, align, volatile], None);
987 }
988
989 pub fn alloc_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, name: &str) -> ValueRef {
990     let _icx = push_ctxt("alloc_ty");
991     let ccx = bcx.ccx();
992     let ty = type_of::type_of(ccx, t);
993     assert!(!ty::type_has_params(t));
994     let val = alloca(bcx, ty, name);
995     return val;
996 }
997
998 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
999     let p = alloca_no_lifetime(cx, ty, name);
1000     call_lifetime_start(cx, p);
1001     p
1002 }
1003
1004 pub fn alloca_no_lifetime(cx: Block, ty: Type, name: &str) -> ValueRef {
1005     let _icx = push_ctxt("alloca");
1006     if cx.unreachable.get() {
1007         unsafe {
1008             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1009         }
1010     }
1011     debuginfo::clear_source_location(cx.fcx);
1012     Alloca(cx, ty, name)
1013 }
1014
1015 // Creates the alloca slot which holds the pointer to the slot for the final return value
1016 pub fn make_return_slot_pointer<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1017                                           output_type: Ty<'tcx>) -> ValueRef {
1018     let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1019
1020     // We create an alloca to hold a pointer of type `output_type`
1021     // which will hold the pointer to the right alloca which has the
1022     // final ret value
1023     if fcx.needs_ret_allocas {
1024         // Let's create the stack slot
1025         let slot = AllocaFcx(fcx, lloutputtype.ptr_to(), "llretslotptr");
1026
1027         // and if we're using an out pointer, then store that in our newly made slot
1028         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1029             let outptr = get_param(fcx.llfn, 0);
1030
1031             let b = fcx.ccx.builder();
1032             b.position_before(fcx.alloca_insert_pt.get().unwrap());
1033             b.store(outptr, slot);
1034         }
1035
1036         slot
1037
1038     // But if there are no nested returns, we skip the indirection and have a single
1039     // retslot
1040     } else {
1041         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1042             get_param(fcx.llfn, 0)
1043         } else {
1044             AllocaFcx(fcx, lloutputtype, "sret_slot")
1045         }
1046     }
1047 }
1048
1049 struct FindNestedReturn {
1050     found: bool,
1051 }
1052
1053 impl FindNestedReturn {
1054     fn new() -> FindNestedReturn {
1055         FindNestedReturn { found: false }
1056     }
1057 }
1058
1059 impl<'v> Visitor<'v> for FindNestedReturn {
1060     fn visit_expr(&mut self, e: &ast::Expr) {
1061         match e.node {
1062             ast::ExprRet(..) => {
1063                 self.found = true;
1064             }
1065             _ => visit::walk_expr(self, e)
1066         }
1067     }
1068 }
1069
1070 fn build_cfg(tcx: &ty::ctxt, id: ast::NodeId) -> (ast::NodeId, Option<cfg::CFG>) {
1071     let blk = match tcx.map.find(id) {
1072         Some(ast_map::NodeItem(i)) => {
1073             match i.node {
1074                 ast::ItemFn(_, _, _, _, ref blk) => {
1075                     blk
1076                 }
1077                 _ => tcx.sess.bug("unexpected item variant in has_nested_returns")
1078             }
1079         }
1080         Some(ast_map::NodeTraitItem(trait_item)) => {
1081             match trait_item.node {
1082                 ast::MethodTraitItem(_, Some(ref body)) => body,
1083                 _ => {
1084                     tcx.sess.bug("unexpected variant: trait item other than a \
1085                                   provided method in has_nested_returns")
1086                 }
1087             }
1088         }
1089         Some(ast_map::NodeImplItem(impl_item)) => {
1090             match impl_item.node {
1091                 ast::MethodImplItem(_, ref body) => body,
1092                 _ => {
1093                     tcx.sess.bug("unexpected variant: non-method impl item in \
1094                                   has_nested_returns")
1095                 }
1096             }
1097         }
1098         Some(ast_map::NodeExpr(e)) => {
1099             match e.node {
1100                 ast::ExprClosure(_, _, ref blk) => blk,
1101                 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns")
1102             }
1103         }
1104         Some(ast_map::NodeVariant(..)) |
1105         Some(ast_map::NodeStructCtor(..)) => return (ast::DUMMY_NODE_ID, None),
1106
1107         // glue, shims, etc
1108         None if id == ast::DUMMY_NODE_ID => return (ast::DUMMY_NODE_ID, None),
1109
1110         _ => tcx.sess.bug(&format!("unexpected variant in has_nested_returns: {}",
1111                                    tcx.map.path_to_string(id)))
1112     };
1113
1114     (blk.id, Some(cfg::CFG::new(tcx, blk)))
1115 }
1116
1117 // Checks for the presence of "nested returns" in a function.
1118 // Nested returns are when the inner expression of a return expression
1119 // (the 'expr' in 'return expr') contains a return expression. Only cases
1120 // where the outer return is actually reachable are considered. Implicit
1121 // returns from the end of blocks are considered as well.
1122 //
1123 // This check is needed to handle the case where the inner expression is
1124 // part of a larger expression that may have already partially-filled the
1125 // return slot alloca. This can cause errors related to clean-up due to
1126 // the clobbering of the existing value in the return slot.
1127 fn has_nested_returns(tcx: &ty::ctxt, cfg: &cfg::CFG, blk_id: ast::NodeId) -> bool {
1128     for n in cfg.graph.depth_traverse(cfg.entry) {
1129         match tcx.map.find(n.id()) {
1130             Some(ast_map::NodeExpr(ex)) => {
1131                 if let ast::ExprRet(Some(ref ret_expr)) = ex.node {
1132                     let mut visitor = FindNestedReturn::new();
1133                     visit::walk_expr(&mut visitor, &**ret_expr);
1134                     if visitor.found {
1135                         return true;
1136                     }
1137                 }
1138             }
1139             Some(ast_map::NodeBlock(blk)) if blk.id == blk_id => {
1140                 let mut visitor = FindNestedReturn::new();
1141                 visit::walk_expr_opt(&mut visitor, &blk.expr);
1142                 if visitor.found {
1143                     return true;
1144                 }
1145             }
1146             _ => {}
1147         }
1148     }
1149
1150     return false;
1151 }
1152
1153 // NB: must keep 4 fns in sync:
1154 //
1155 //  - type_of_fn
1156 //  - create_datums_for_fn_args.
1157 //  - new_fn_ctxt
1158 //  - trans_args
1159 //
1160 // Be warned! You must call `init_function` before doing anything with the
1161 // returned function context.
1162 pub fn new_fn_ctxt<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
1163                              llfndecl: ValueRef,
1164                              id: ast::NodeId,
1165                              has_env: bool,
1166                              output_type: ty::FnOutput<'tcx>,
1167                              param_substs: &'tcx Substs<'tcx>,
1168                              sp: Option<Span>,
1169                              block_arena: &'a TypedArena<common::BlockS<'a, 'tcx>>)
1170                              -> FunctionContext<'a, 'tcx> {
1171     common::validate_substs(param_substs);
1172
1173     debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1174            if id == !0 {
1175                "".to_string()
1176            } else {
1177                ccx.tcx().map.path_to_string(id).to_string()
1178            },
1179            id, param_substs.repr(ccx.tcx()));
1180
1181     let uses_outptr = match output_type {
1182         ty::FnConverging(output_type) => {
1183             let substd_output_type =
1184                 monomorphize::apply_param_substs(ccx.tcx(), param_substs, &output_type);
1185             type_of::return_uses_outptr(ccx, substd_output_type)
1186         }
1187         ty::FnDiverging => false
1188     };
1189     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1190     let (blk_id, cfg) = build_cfg(ccx.tcx(), id);
1191     let nested_returns = if let Some(ref cfg) = cfg {
1192         has_nested_returns(ccx.tcx(), cfg, blk_id)
1193     } else {
1194         false
1195     };
1196
1197     let mut fcx = FunctionContext {
1198           llfn: llfndecl,
1199           llenv: None,
1200           llretslotptr: Cell::new(None),
1201           param_env: ty::empty_parameter_environment(ccx.tcx()),
1202           alloca_insert_pt: Cell::new(None),
1203           llreturn: Cell::new(None),
1204           needs_ret_allocas: nested_returns,
1205           personality: Cell::new(None),
1206           caller_expects_out_pointer: uses_outptr,
1207           lllocals: RefCell::new(NodeMap()),
1208           llupvars: RefCell::new(NodeMap()),
1209           id: id,
1210           param_substs: param_substs,
1211           span: sp,
1212           block_arena: block_arena,
1213           ccx: ccx,
1214           debug_context: debug_context,
1215           scopes: RefCell::new(Vec::new()),
1216           cfg: cfg
1217     };
1218
1219     if has_env {
1220         fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1221     }
1222
1223     fcx
1224 }
1225
1226 /// Performs setup on a newly created function, creating the entry scope block
1227 /// and allocating space for the return pointer.
1228 pub fn init_function<'a, 'tcx>(fcx: &'a FunctionContext<'a, 'tcx>,
1229                                skip_retptr: bool,
1230                                output: ty::FnOutput<'tcx>)
1231                                -> Block<'a, 'tcx> {
1232     let entry_bcx = fcx.new_temp_block("entry-block");
1233
1234     // Use a dummy instruction as the insertion point for all allocas.
1235     // This is later removed in FunctionContext::cleanup.
1236     fcx.alloca_insert_pt.set(Some(unsafe {
1237         Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1238         llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1239     }));
1240
1241     if let ty::FnConverging(output_type) = output {
1242         // This shouldn't need to recompute the return type,
1243         // as new_fn_ctxt did it already.
1244         let substd_output_type = fcx.monomorphize(&output_type);
1245         if !return_type_is_void(fcx.ccx, substd_output_type) {
1246             // If the function returns nil/bot, there is no real return
1247             // value, so do not set `llretslotptr`.
1248             if !skip_retptr || fcx.caller_expects_out_pointer {
1249                 // Otherwise, we normally allocate the llretslotptr, unless we
1250                 // have been instructed to skip it for immediate return
1251                 // values.
1252                 fcx.llretslotptr.set(Some(make_return_slot_pointer(fcx, substd_output_type)));
1253             }
1254         }
1255     }
1256
1257     entry_bcx
1258 }
1259
1260 // NB: must keep 4 fns in sync:
1261 //
1262 //  - type_of_fn
1263 //  - create_datums_for_fn_args.
1264 //  - new_fn_ctxt
1265 //  - trans_args
1266
1267 pub fn arg_kind<'a, 'tcx>(cx: &FunctionContext<'a, 'tcx>, t: Ty<'tcx>)
1268                           -> datum::Rvalue {
1269     use trans::datum::{ByRef, ByValue};
1270
1271     datum::Rvalue {
1272         mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1273     }
1274 }
1275
1276 // work around bizarre resolve errors
1277 pub type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
1278
1279 // create_datums_for_fn_args: creates rvalue datums for each of the
1280 // incoming function arguments. These will later be stored into
1281 // appropriate lvalue datums.
1282 pub fn create_datums_for_fn_args<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1283                                            arg_tys: &[Ty<'tcx>])
1284                                            -> Vec<RvalueDatum<'tcx>> {
1285     let _icx = push_ctxt("create_datums_for_fn_args");
1286
1287     // Return an array wrapping the ValueRefs that we get from `get_param` for
1288     // each argument into datums.
1289     arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1290         let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1291         datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1292     }).collect()
1293 }
1294
1295 /// Creates rvalue datums for each of the incoming function arguments and
1296 /// tuples the arguments. These will later be stored into appropriate lvalue
1297 /// datums.
1298 ///
1299 /// FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1300 fn create_datums_for_fn_args_under_call_abi<'blk, 'tcx>(
1301         mut bcx: Block<'blk, 'tcx>,
1302         arg_scope: cleanup::CustomScopeIndex,
1303         arg_tys: &[Ty<'tcx>])
1304         -> Vec<RvalueDatum<'tcx>> {
1305     let mut result = Vec::new();
1306     for (i, &arg_ty) in arg_tys.iter().enumerate() {
1307         if i < arg_tys.len() - 1 {
1308             // Regular argument.
1309             let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1310             result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1311                                                                   arg_ty)));
1312             continue
1313         }
1314
1315         // This is the last argument. Tuple it.
1316         match arg_ty.sty {
1317             ty::ty_tup(ref tupled_arg_tys) => {
1318                 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1319                 let tuple =
1320                     unpack_datum!(bcx,
1321                                   datum::lvalue_scratch_datum(bcx,
1322                                                               arg_ty,
1323                                                               "tupled_args",
1324                                                               tuple_args_scope_id,
1325                                                               (),
1326                                                               |(),
1327                                                                mut bcx,
1328                                                                llval| {
1329                         for (j, &tupled_arg_ty) in
1330                                     tupled_arg_tys.iter().enumerate() {
1331                             let llarg =
1332                                 get_param(bcx.fcx.llfn,
1333                                           bcx.fcx.arg_pos(i + j) as c_uint);
1334                             let lldest = GEPi(bcx, llval, &[0, j]);
1335                             let datum = datum::Datum::new(
1336                                 llarg,
1337                                 tupled_arg_ty,
1338                                 arg_kind(bcx.fcx, tupled_arg_ty));
1339                             bcx = datum.store_to(bcx, lldest);
1340                         }
1341                         bcx
1342                     }));
1343                 let tuple = unpack_datum!(bcx,
1344                                           tuple.to_expr_datum()
1345                                                .to_rvalue_datum(bcx,
1346                                                                 "argtuple"));
1347                 result.push(tuple);
1348             }
1349             _ => {
1350                 bcx.tcx().sess.bug("last argument of a function with \
1351                                     `rust-call` ABI isn't a tuple?!")
1352             }
1353         };
1354
1355     }
1356
1357     result
1358 }
1359
1360 fn copy_args_to_allocas<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1361                                     arg_scope: cleanup::CustomScopeIndex,
1362                                     args: &[ast::Arg],
1363                                     arg_datums: Vec<RvalueDatum<'tcx>>)
1364                                     -> Block<'blk, 'tcx> {
1365     debug!("copy_args_to_allocas");
1366
1367     let _icx = push_ctxt("copy_args_to_allocas");
1368     let mut bcx = bcx;
1369
1370     let arg_scope_id = cleanup::CustomScope(arg_scope);
1371
1372     for (i, arg_datum) in arg_datums.into_iter().enumerate() {
1373         // For certain mode/type combinations, the raw llarg values are passed
1374         // by value.  However, within the fn body itself, we want to always
1375         // have all locals and arguments be by-ref so that we can cancel the
1376         // cleanup and for better interaction with LLVM's debug info.  So, if
1377         // the argument would be passed by value, we store it into an alloca.
1378         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1379         // the event it's not truly needed.
1380
1381         bcx = _match::store_arg(bcx, &*args[i].pat, arg_datum, arg_scope_id);
1382         debuginfo::create_argument_metadata(bcx, &args[i]);
1383     }
1384
1385     bcx
1386 }
1387
1388 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1389 // and builds the return block.
1390 pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1391                              last_bcx: Block<'blk, 'tcx>,
1392                              retty: ty::FnOutput<'tcx>,
1393                              ret_debug_loc: DebugLoc) {
1394     let _icx = push_ctxt("finish_fn");
1395
1396     let ret_cx = match fcx.llreturn.get() {
1397         Some(llreturn) => {
1398             if !last_bcx.terminated.get() {
1399                 Br(last_bcx, llreturn, DebugLoc::None);
1400             }
1401             raw_block(fcx, false, llreturn)
1402         }
1403         None => last_bcx
1404     };
1405
1406     // This shouldn't need to recompute the return type,
1407     // as new_fn_ctxt did it already.
1408     let substd_retty = fcx.monomorphize(&retty);
1409     build_return_block(fcx, ret_cx, substd_retty, ret_debug_loc);
1410
1411     debuginfo::clear_source_location(fcx);
1412     fcx.cleanup();
1413 }
1414
1415 // Builds the return block for a function.
1416 pub fn build_return_block<'blk, 'tcx>(fcx: &FunctionContext<'blk, 'tcx>,
1417                                       ret_cx: Block<'blk, 'tcx>,
1418                                       retty: ty::FnOutput<'tcx>,
1419                                       ret_debug_location: DebugLoc) {
1420     if fcx.llretslotptr.get().is_none() ||
1421        (!fcx.needs_ret_allocas && fcx.caller_expects_out_pointer) {
1422         return RetVoid(ret_cx, ret_debug_location);
1423     }
1424
1425     let retslot = if fcx.needs_ret_allocas {
1426         Load(ret_cx, fcx.llretslotptr.get().unwrap())
1427     } else {
1428         fcx.llretslotptr.get().unwrap()
1429     };
1430     let retptr = Value(retslot);
1431     match retptr.get_dominating_store(ret_cx) {
1432         // If there's only a single store to the ret slot, we can directly return
1433         // the value that was stored and omit the store and the alloca
1434         Some(s) => {
1435             let retval = s.get_operand(0).unwrap().get();
1436             s.erase_from_parent();
1437
1438             if retptr.has_no_uses() {
1439                 retptr.erase_from_parent();
1440             }
1441
1442             let retval = if retty == ty::FnConverging(fcx.ccx.tcx().types.bool) {
1443                 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1444             } else {
1445                 retval
1446             };
1447
1448             if fcx.caller_expects_out_pointer {
1449                 if let ty::FnConverging(retty) = retty {
1450                     store_ty(ret_cx, retval, get_param(fcx.llfn, 0), retty);
1451                 }
1452                 RetVoid(ret_cx, ret_debug_location)
1453             } else {
1454                 Ret(ret_cx, retval, ret_debug_location)
1455             }
1456         }
1457         // Otherwise, copy the return value to the ret slot
1458         None => match retty {
1459             ty::FnConverging(retty) => {
1460                 if fcx.caller_expects_out_pointer {
1461                     memcpy_ty(ret_cx, get_param(fcx.llfn, 0), retslot, retty);
1462                     RetVoid(ret_cx, ret_debug_location)
1463                 } else {
1464                     Ret(ret_cx, load_ty(ret_cx, retslot, retty), ret_debug_location)
1465                 }
1466             }
1467             ty::FnDiverging => {
1468                 if fcx.caller_expects_out_pointer {
1469                     RetVoid(ret_cx, ret_debug_location)
1470                 } else {
1471                     Ret(ret_cx, C_undef(Type::nil(fcx.ccx)), ret_debug_location)
1472                 }
1473             }
1474         }
1475     }
1476 }
1477
1478 /// Builds an LLVM function out of a source function.
1479 ///
1480 /// If the function closes over its environment a closure will be returned.
1481 pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1482                                    decl: &ast::FnDecl,
1483                                    body: &ast::Block,
1484                                    llfndecl: ValueRef,
1485                                    param_substs: &'tcx Substs<'tcx>,
1486                                    fn_ast_id: ast::NodeId,
1487                                    _attributes: &[ast::Attribute],
1488                                    output_type: ty::FnOutput<'tcx>,
1489                                    abi: Abi,
1490                                    closure_env: closure::ClosureEnv<'b>) {
1491     ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1492
1493     let _icx = push_ctxt("trans_closure");
1494     attributes::emit_uwtable(llfndecl, true);
1495
1496     debug!("trans_closure(..., param_substs={})",
1497            param_substs.repr(ccx.tcx()));
1498
1499     let has_env = match closure_env {
1500         closure::ClosureEnv::Closure(_) => true,
1501         closure::ClosureEnv::NotClosure => false,
1502     };
1503
1504     let (arena, fcx): (TypedArena<_>, FunctionContext);
1505     arena = TypedArena::new();
1506     fcx = new_fn_ctxt(ccx,
1507                       llfndecl,
1508                       fn_ast_id,
1509                       has_env,
1510                       output_type,
1511                       param_substs,
1512                       Some(body.span),
1513                       &arena);
1514     let mut bcx = init_function(&fcx, false, output_type);
1515
1516     // cleanup scope for the incoming arguments
1517     let fn_cleanup_debug_loc =
1518         debuginfo::get_cleanup_debug_loc_for_ast_node(ccx, fn_ast_id, body.span, true);
1519     let arg_scope = fcx.push_custom_cleanup_scope_with_debug_loc(fn_cleanup_debug_loc);
1520
1521     let block_ty = node_id_type(bcx, body.id);
1522
1523     // Set up arguments to the function.
1524     let monomorphized_arg_types =
1525         decl.inputs.iter()
1526                    .map(|arg| node_id_type(bcx, arg.id))
1527                    .collect::<Vec<_>>();
1528     let monomorphized_arg_types = match closure_env {
1529         closure::ClosureEnv::NotClosure => {
1530             monomorphized_arg_types
1531         }
1532
1533         // Tuple up closure argument types for the "rust-call" ABI.
1534         closure::ClosureEnv::Closure(_) => {
1535             vec![ty::mk_tup(ccx.tcx(), monomorphized_arg_types)]
1536         }
1537     };
1538     for monomorphized_arg_type in &monomorphized_arg_types {
1539         debug!("trans_closure: monomorphized_arg_type: {}",
1540                ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1541     }
1542     debug!("trans_closure: function lltype: {}",
1543            bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
1544
1545     let arg_datums = match closure_env {
1546         closure::ClosureEnv::NotClosure if abi == RustCall => {
1547             create_datums_for_fn_args_under_call_abi(bcx, arg_scope, &monomorphized_arg_types[..])
1548         }
1549         _ => {
1550             let arg_tys = untuple_arguments_if_necessary(ccx, &monomorphized_arg_types, abi);
1551             create_datums_for_fn_args(&fcx, &arg_tys)
1552         }
1553     };
1554
1555     bcx = copy_args_to_allocas(bcx, arg_scope, &decl.inputs, arg_datums);
1556
1557     bcx = closure_env.load(bcx, cleanup::CustomScope(arg_scope));
1558
1559     // Up until here, IR instructions for this function have explicitly not been annotated with
1560     // source code location, so we don't step into call setup code. From here on, source location
1561     // emitting should be enabled.
1562     debuginfo::start_emitting_source_locations(&fcx);
1563
1564     let dest = match fcx.llretslotptr.get() {
1565         Some(_) => expr::SaveIn(fcx.get_ret_slot(bcx, ty::FnConverging(block_ty), "iret_slot")),
1566         None => {
1567             assert!(type_is_zero_size(bcx.ccx(), block_ty));
1568             expr::Ignore
1569         }
1570     };
1571
1572     // This call to trans_block is the place where we bridge between
1573     // translation calls that don't have a return value (trans_crate,
1574     // trans_mod, trans_item, et cetera) and those that do
1575     // (trans_block, trans_expr, et cetera).
1576     bcx = controlflow::trans_block(bcx, body, dest);
1577
1578     match dest {
1579         expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1580             Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1581         }
1582         _ => {}
1583     }
1584
1585     match fcx.llreturn.get() {
1586         Some(_) => {
1587             Br(bcx, fcx.return_exit_block(), DebugLoc::None);
1588             fcx.pop_custom_cleanup_scope(arg_scope);
1589         }
1590         None => {
1591             // Microoptimization writ large: avoid creating a separate
1592             // llreturn basic block
1593             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1594         }
1595     };
1596
1597     // Put return block after all other blocks.
1598     // This somewhat improves single-stepping experience in debugger.
1599     unsafe {
1600         let llreturn = fcx.llreturn.get();
1601         if let Some(llreturn) = llreturn {
1602             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1603         }
1604     }
1605
1606     let ret_debug_loc = DebugLoc::At(fn_cleanup_debug_loc.id,
1607                                      fn_cleanup_debug_loc.span);
1608
1609     // Insert the mandatory first few basic blocks before lltop.
1610     finish_fn(&fcx, bcx, output_type, ret_debug_loc);
1611 }
1612
1613 /// Creates an LLVM function corresponding to a source language function.
1614 pub fn trans_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1615                           decl: &ast::FnDecl,
1616                           body: &ast::Block,
1617                           llfndecl: ValueRef,
1618                           param_substs: &'tcx Substs<'tcx>,
1619                           id: ast::NodeId,
1620                           attrs: &[ast::Attribute]) {
1621     let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string());
1622     debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1623     let _icx = push_ctxt("trans_fn");
1624     let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1625     let output_type = ty::erase_late_bound_regions(ccx.tcx(), &ty::ty_fn_ret(fn_ty));
1626     let abi = ty::ty_fn_abi(fn_ty);
1627     trans_closure(ccx, decl, body, llfndecl, param_substs, id, attrs, output_type, abi,
1628                   closure::ClosureEnv::NotClosure);
1629 }
1630
1631 pub fn trans_enum_variant<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1632                                     _enum_id: ast::NodeId,
1633                                     variant: &ast::Variant,
1634                                     _args: &[ast::VariantArg],
1635                                     disr: ty::Disr,
1636                                     param_substs: &'tcx Substs<'tcx>,
1637                                     llfndecl: ValueRef) {
1638     let _icx = push_ctxt("trans_enum_variant");
1639
1640     trans_enum_variant_or_tuple_like_struct(
1641         ccx,
1642         variant.node.id,
1643         disr,
1644         param_substs,
1645         llfndecl);
1646 }
1647
1648 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1649                                                  ctor_ty: Ty<'tcx>,
1650                                                  disr: ty::Disr,
1651                                                  args: callee::CallArgs,
1652                                                  dest: expr::Dest,
1653                                                  debug_loc: DebugLoc)
1654                                                  -> Result<'blk, 'tcx> {
1655
1656     let ccx = bcx.fcx.ccx;
1657     let tcx = ccx.tcx();
1658
1659     let result_ty = match ctor_ty.sty {
1660         ty::ty_bare_fn(_, ref bft) => {
1661             ty::erase_late_bound_regions(bcx.tcx(), &bft.sig.output()).unwrap()
1662         }
1663         _ => ccx.sess().bug(
1664             &format!("trans_enum_variant_constructor: \
1665                      unexpected ctor return type {}",
1666                      ctor_ty.repr(tcx)))
1667     };
1668
1669     // Get location to store the result. If the user does not care about
1670     // the result, just make a stack slot
1671     let llresult = match dest {
1672         expr::SaveIn(d) => d,
1673         expr::Ignore => {
1674             if !type_is_zero_size(ccx, result_ty) {
1675                 alloc_ty(bcx, result_ty, "constructor_result")
1676             } else {
1677                 C_undef(type_of::type_of(ccx, result_ty))
1678             }
1679         }
1680     };
1681
1682     if !type_is_zero_size(ccx, result_ty) {
1683         match args {
1684             callee::ArgExprs(exprs) => {
1685                 let fields = exprs.iter().map(|x| &**x).enumerate().collect::<Vec<_>>();
1686                 bcx = expr::trans_adt(bcx,
1687                                       result_ty,
1688                                       disr,
1689                                       &fields[..],
1690                                       None,
1691                                       expr::SaveIn(llresult),
1692                                       debug_loc);
1693             }
1694             _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor")
1695         }
1696     }
1697
1698     // If the caller doesn't care about the result
1699     // drop the temporary we made
1700     let bcx = match dest {
1701         expr::SaveIn(_) => bcx,
1702         expr::Ignore => {
1703             let bcx = glue::drop_ty(bcx, llresult, result_ty, debug_loc);
1704             if !type_is_zero_size(ccx, result_ty) {
1705                 call_lifetime_end(bcx, llresult);
1706             }
1707             bcx
1708         }
1709     };
1710
1711     Result::new(bcx, llresult)
1712 }
1713
1714 pub fn trans_tuple_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1715                                     _fields: &[ast::StructField],
1716                                     ctor_id: ast::NodeId,
1717                                     param_substs: &'tcx Substs<'tcx>,
1718                                     llfndecl: ValueRef) {
1719     let _icx = push_ctxt("trans_tuple_struct");
1720
1721     trans_enum_variant_or_tuple_like_struct(
1722         ccx,
1723         ctor_id,
1724         0,
1725         param_substs,
1726         llfndecl);
1727 }
1728
1729 fn trans_enum_variant_or_tuple_like_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1730                                                      ctor_id: ast::NodeId,
1731                                                      disr: ty::Disr,
1732                                                      param_substs: &'tcx Substs<'tcx>,
1733                                                      llfndecl: ValueRef) {
1734     let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1735     let ctor_ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &ctor_ty);
1736
1737     let result_ty = match ctor_ty.sty {
1738         ty::ty_bare_fn(_, ref bft) => {
1739             ty::erase_late_bound_regions(ccx.tcx(), &bft.sig.output())
1740         }
1741         _ => ccx.sess().bug(
1742             &format!("trans_enum_variant_or_tuple_like_struct: \
1743                      unexpected ctor return type {}",
1744                     ty_to_string(ccx.tcx(), ctor_ty)))
1745     };
1746
1747     let (arena, fcx): (TypedArena<_>, FunctionContext);
1748     arena = TypedArena::new();
1749     fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1750                       param_substs, None, &arena);
1751     let bcx = init_function(&fcx, false, result_ty);
1752
1753     assert!(!fcx.needs_ret_allocas);
1754
1755     let arg_tys =
1756         ty::erase_late_bound_regions(
1757             ccx.tcx(), &ty::ty_fn_args(ctor_ty));
1758
1759     let arg_datums = create_datums_for_fn_args(&fcx, &arg_tys[..]);
1760
1761     if !type_is_zero_size(fcx.ccx, result_ty.unwrap()) {
1762         let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot");
1763         let repr = adt::represent_type(ccx, result_ty.unwrap());
1764         for (i, arg_datum) in arg_datums.into_iter().enumerate() {
1765             let lldestptr = adt::trans_field_ptr(bcx,
1766                                                  &*repr,
1767                                                  dest,
1768                                                  disr,
1769                                                  i);
1770             arg_datum.store_to(bcx, lldestptr);
1771         }
1772         adt::trans_set_discr(bcx, &*repr, dest, disr);
1773     }
1774
1775     finish_fn(&fcx, bcx, result_ty, DebugLoc::None);
1776 }
1777
1778 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
1779     let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
1780
1781     let print_info = ccx.sess().print_enum_sizes();
1782
1783     let levels = ccx.tcx().node_lint_levels.borrow();
1784     let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCES);
1785     let lvlsrc = levels.get(&(id, lint_id));
1786     let is_allow = lvlsrc.map_or(true, |&(lvl, _)| lvl == lint::Allow);
1787
1788     if is_allow && !print_info {
1789         // we're not interested in anything here
1790         return
1791     }
1792
1793     let ty = ty::node_id_to_type(ccx.tcx(), id);
1794     let avar = adt::represent_type(ccx, ty);
1795     match *avar {
1796         adt::General(_, ref variants, _) => {
1797             for var in variants {
1798                 let mut size = 0;
1799                 for field in var.fields.iter().skip(1) {
1800                     // skip the discriminant
1801                     size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
1802                 }
1803                 sizes.push(size);
1804             }
1805         },
1806         _ => { /* its size is either constant or unimportant */ }
1807     }
1808
1809     let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
1810         |(l, s, li), (idx, &size)|
1811             if size > l {
1812                 (size, l, idx)
1813             } else if size > s {
1814                 (l, size, li)
1815             } else {
1816                 (l, s, li)
1817             }
1818     );
1819
1820     if print_info {
1821         let llty = type_of::sizing_type_of(ccx, ty);
1822
1823         let sess = &ccx.tcx().sess;
1824         sess.span_note(sp, &*format!("total size: {} bytes", llsize_of_real(ccx, llty)));
1825         match *avar {
1826             adt::General(..) => {
1827                 for (i, var) in enum_def.variants.iter().enumerate() {
1828                     ccx.tcx().sess.span_note(var.span,
1829                                              &*format!("variant data: {} bytes", sizes[i]));
1830                 }
1831             }
1832             _ => {}
1833         }
1834     }
1835
1836     // we only warn if the largest variant is at least thrice as large as
1837     // the second-largest.
1838     if !is_allow && largest > slargest * 3 && slargest > 0 {
1839         // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
1840         // pass for the latter already ran.
1841         lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCES,
1842                             *lvlsrc.unwrap(), Some(sp),
1843                             &format!("enum variant is more than three times larger \
1844                                      ({} bytes) than the next largest (ignoring padding)",
1845                                     largest));
1846
1847         ccx.sess().span_note(enum_def.variants[largest_index].span,
1848                              "this variant is the largest");
1849     }
1850 }
1851
1852 pub struct TransItemVisitor<'a, 'tcx: 'a> {
1853     pub ccx: &'a CrateContext<'a, 'tcx>,
1854 }
1855
1856 impl<'a, 'tcx, 'v> Visitor<'v> for TransItemVisitor<'a, 'tcx> {
1857     fn visit_item(&mut self, i: &ast::Item) {
1858         trans_item(self.ccx, i);
1859     }
1860 }
1861
1862 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
1863     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
1864     // applicable to variable declarations and may not really make sense for
1865     // Rust code in the first place but whitelist them anyway and trust that
1866     // the user knows what s/he's doing. Who knows, unanticipated use cases
1867     // may pop up in the future.
1868     //
1869     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
1870     // and don't have to be, LLVM treats them as no-ops.
1871     match name {
1872         "appending" => Some(llvm::AppendingLinkage),
1873         "available_externally" => Some(llvm::AvailableExternallyLinkage),
1874         "common" => Some(llvm::CommonLinkage),
1875         "extern_weak" => Some(llvm::ExternalWeakLinkage),
1876         "external" => Some(llvm::ExternalLinkage),
1877         "internal" => Some(llvm::InternalLinkage),
1878         "linkonce" => Some(llvm::LinkOnceAnyLinkage),
1879         "linkonce_odr" => Some(llvm::LinkOnceODRLinkage),
1880         "private" => Some(llvm::PrivateLinkage),
1881         "weak" => Some(llvm::WeakAnyLinkage),
1882         "weak_odr" => Some(llvm::WeakODRLinkage),
1883         _ => None,
1884     }
1885 }
1886
1887
1888 /// Enum describing the origin of an LLVM `Value`, for linkage purposes.
1889 #[derive(Copy, Clone)]
1890 pub enum ValueOrigin {
1891     /// The LLVM `Value` is in this context because the corresponding item was
1892     /// assigned to the current compilation unit.
1893     OriginalTranslation,
1894     /// The `Value`'s corresponding item was assigned to some other compilation
1895     /// unit, but the `Value` was translated in this context anyway because the
1896     /// item is marked `#[inline]`.
1897     InlinedCopy,
1898 }
1899
1900 /// Set the appropriate linkage for an LLVM `ValueRef` (function or global).
1901 /// If the `llval` is the direct translation of a specific Rust item, `id`
1902 /// should be set to the `NodeId` of that item.  (This mapping should be
1903 /// 1-to-1, so monomorphizations and drop/visit glue should have `id` set to
1904 /// `None`.)  `llval_origin` indicates whether `llval` is the translation of an
1905 /// item assigned to `ccx`'s compilation unit or an inlined copy of an item
1906 /// assigned to a different compilation unit.
1907 pub fn update_linkage(ccx: &CrateContext,
1908                       llval: ValueRef,
1909                       id: Option<ast::NodeId>,
1910                       llval_origin: ValueOrigin) {
1911     match llval_origin {
1912         InlinedCopy => {
1913             // `llval` is a translation of an item defined in a separate
1914             // compilation unit.  This only makes sense if there are at least
1915             // two compilation units.
1916             assert!(ccx.sess().opts.cg.codegen_units > 1);
1917             // `llval` is a copy of something defined elsewhere, so use
1918             // `AvailableExternallyLinkage` to avoid duplicating code in the
1919             // output.
1920             llvm::SetLinkage(llval, llvm::AvailableExternallyLinkage);
1921             return;
1922         },
1923         OriginalTranslation => {},
1924     }
1925
1926     if let Some(id) = id {
1927         let item = ccx.tcx().map.get(id);
1928         if let ast_map::NodeItem(i) = item {
1929             if let Some(name) = attr::first_attr_value_str_by_name(&i.attrs, "linkage") {
1930                 if let Some(linkage) = llvm_linkage_by_name(&name) {
1931                     llvm::SetLinkage(llval, linkage);
1932                 } else {
1933                     ccx.sess().span_fatal(i.span, "invalid linkage specified");
1934                 }
1935                 return;
1936             }
1937         }
1938     }
1939
1940     match id {
1941         Some(id) if ccx.reachable().contains(&id) => {
1942             llvm::SetLinkage(llval, llvm::ExternalLinkage);
1943         },
1944         _ => {
1945             // `id` does not refer to an item in `ccx.reachable`.
1946             if ccx.sess().opts.cg.codegen_units > 1 {
1947                 llvm::SetLinkage(llval, llvm::ExternalLinkage);
1948             } else {
1949                 llvm::SetLinkage(llval, llvm::InternalLinkage);
1950             }
1951         },
1952     }
1953 }
1954
1955 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1956     let _icx = push_ctxt("trans_item");
1957
1958     let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
1959
1960     match item.node {
1961       ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
1962         if !generics.is_type_parameterized() {
1963             let trans_everywhere = attr::requests_inline(&item.attrs);
1964             // Ignore `trans_everywhere` for cross-crate inlined items
1965             // (`from_external`).  `trans_item` will be called once for each
1966             // compilation unit that references the item, so it will still get
1967             // translated everywhere it's needed.
1968             for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
1969                 let llfn = get_item_val(ccx, item.id);
1970                 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
1971                 if abi != Rust {
1972                     foreign::trans_rust_fn_with_foreign_abi(ccx, &**decl, &**body, &item.attrs,
1973                                                             llfn, empty_substs, item.id, None);
1974                 } else {
1975                     trans_fn(ccx, &**decl, &**body, llfn, empty_substs, item.id, &item.attrs);
1976                 }
1977                 update_linkage(ccx, llfn, Some(item.id),
1978                                if is_origin { OriginalTranslation } else { InlinedCopy });
1979
1980                 if is_entry_fn(ccx.sess(), item.id) {
1981                     create_entry_wrapper(ccx, item.span, llfn);
1982                     // check for the #[rustc_error] annotation, which forces an
1983                     // error in trans. This is used to write compile-fail tests
1984                     // that actually test that compilation succeeds without
1985                     // reporting an error.
1986                     if ty::has_attr(ccx.tcx(), local_def(item.id), "rustc_error") {
1987                         ccx.tcx().sess.span_fatal(item.span, "compilation successful");
1988                     }
1989                 }
1990             }
1991         }
1992
1993         // Be sure to travel more than just one layer deep to catch nested
1994         // items in blocks and such.
1995         let mut v = TransItemVisitor{ ccx: ccx };
1996         v.visit_block(&**body);
1997       }
1998       ast::ItemImpl(_, _, ref generics, _, _, ref impl_items) => {
1999         meth::trans_impl(ccx,
2000                          item.ident,
2001                          &impl_items[..],
2002                          generics,
2003                          item.id);
2004       }
2005       ast::ItemMod(ref m) => {
2006         trans_mod(&ccx.rotate(), m);
2007       }
2008       ast::ItemEnum(ref enum_definition, ref gens) => {
2009         if gens.ty_params.is_empty() {
2010             // sizes only make sense for non-generic types
2011
2012             enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
2013         }
2014       }
2015       ast::ItemConst(_, ref expr) => {
2016           // Recurse on the expression to catch items in blocks
2017           let mut v = TransItemVisitor{ ccx: ccx };
2018           v.visit_expr(&**expr);
2019       }
2020       ast::ItemStatic(_, m, ref expr) => {
2021           // Recurse on the expression to catch items in blocks
2022           let mut v = TransItemVisitor{ ccx: ccx };
2023           v.visit_expr(&**expr);
2024
2025           let g = consts::trans_static(ccx, m, item.id);
2026           update_linkage(ccx, g, Some(item.id), OriginalTranslation);
2027
2028           // Do static_assert checking. It can't really be done much earlier
2029           // because we need to get the value of the bool out of LLVM
2030           if attr::contains_name(&item.attrs, "static_assert") {
2031               if !ty::type_is_bool(ty::expr_ty(ccx.tcx(), expr)) {
2032                   ccx.sess().span_fatal(expr.span,
2033                                         "can only have static_assert on a static \
2034                                          with type `bool`");
2035               }
2036               if m == ast::MutMutable {
2037                   ccx.sess().span_fatal(expr.span,
2038                                         "cannot have static_assert on a mutable \
2039                                          static");
2040               }
2041
2042               let v = ccx.static_values().borrow().get(&item.id).unwrap().clone();
2043               unsafe {
2044                   if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2045                       ccx.sess().span_fatal(expr.span, "static assertion failed");
2046                   }
2047               }
2048           }
2049       },
2050       ast::ItemForeignMod(ref foreign_mod) => {
2051         foreign::trans_foreign_mod(ccx, foreign_mod);
2052       }
2053       ast::ItemTrait(..) => {
2054         // Inside of this trait definition, we won't be actually translating any
2055         // functions, but the trait still needs to be walked. Otherwise default
2056         // methods with items will not get translated and will cause ICE's when
2057         // metadata time comes around.
2058         let mut v = TransItemVisitor{ ccx: ccx };
2059         visit::walk_item(&mut v, item);
2060       }
2061       _ => {/* fall through */ }
2062     }
2063 }
2064
2065 // Translate a module. Doing this amounts to translating the items in the
2066 // module; there ends up being no artifact (aside from linkage names) of
2067 // separate modules in the compiled program.  That's because modules exist
2068 // only as a convenience for humans working with the code, to organize names
2069 // and control visibility.
2070 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
2071     let _icx = push_ctxt("trans_mod");
2072     for item in &m.items {
2073         trans_item(ccx, &**item);
2074     }
2075 }
2076
2077
2078 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2079 pub fn register_fn_llvmty(ccx: &CrateContext,
2080                           sp: Span,
2081                           sym: String,
2082                           node_id: ast::NodeId,
2083                       cc: llvm::CallConv,
2084                           llfty: Type) -> ValueRef {
2085     debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2086
2087     let llfn = declare::define_fn(ccx, &sym[..], cc, llfty,
2088                                    ty::FnConverging(ty::mk_nil(ccx.tcx()))).unwrap_or_else(||{
2089         ccx.sess().span_fatal(sp, &format!("symbol `{}` is already defined", sym));
2090     });
2091     finish_register_fn(ccx, sym, node_id, llfn);
2092     llfn
2093 }
2094
2095 fn finish_register_fn(ccx: &CrateContext, sym: String, node_id: ast::NodeId,
2096                       llfn: ValueRef) {
2097     ccx.item_symbols().borrow_mut().insert(node_id, sym);
2098
2099     // The stack exhaustion lang item shouldn't have a split stack because
2100     // otherwise it would continue to be exhausted (bad), and both it and the
2101     // eh_personality functions need to be externally linkable.
2102     let def = ast_util::local_def(node_id);
2103     if ccx.tcx().lang_items.stack_exhausted() == Some(def) {
2104         attributes::split_stack(llfn, false);
2105         llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2106     }
2107     if ccx.tcx().lang_items.eh_personality() == Some(def) {
2108         llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2109     }
2110 }
2111
2112 fn register_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2113                          sp: Span,
2114                          sym: String,
2115                          node_id: ast::NodeId,
2116                          node_type: Ty<'tcx>)
2117                          -> ValueRef {
2118     if let ty::ty_bare_fn(_, ref f) = node_type.sty {
2119         if f.abi != Rust && f.abi != RustCall {
2120             ccx.sess().span_bug(sp, &format!("only the `{}` or `{}` calling conventions are valid \
2121                                               for this function; `{}` was specified",
2122                                               Rust.name(), RustCall.name(), f.abi.name()));
2123         }
2124     } else {
2125         ccx.sess().span_bug(sp, "expected bare rust function")
2126     }
2127
2128     let llfn = declare::define_rust_fn(ccx, &sym[..], node_type).unwrap_or_else(||{
2129         ccx.sess().span_fatal(sp, &format!("symbol `{}` is already defined", sym));
2130     });
2131     finish_register_fn(ccx, sym, node_id, llfn);
2132     llfn
2133 }
2134
2135 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2136     match *sess.entry_fn.borrow() {
2137         Some((entry_id, _)) => node_id == entry_id,
2138         None => false
2139     }
2140 }
2141
2142 /// Create the `main` function which will initialise the rust runtime and call users’ main
2143 /// function.
2144 pub fn create_entry_wrapper(ccx: &CrateContext,
2145                            sp: Span,
2146                            main_llfn: ValueRef) {
2147     let et = ccx.sess().entry_type.get().unwrap();
2148     match et {
2149         config::EntryMain => {
2150             create_entry_fn(ccx, sp, main_llfn, true);
2151         }
2152         config::EntryStart => create_entry_fn(ccx, sp, main_llfn, false),
2153         config::EntryNone => {}    // Do nothing.
2154     }
2155
2156     fn create_entry_fn(ccx: &CrateContext,
2157                        sp: Span,
2158                        rust_main: ValueRef,
2159                        use_start_lang_item: bool) {
2160         let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()],
2161                                &ccx.int_type());
2162
2163         let llfn = declare::define_cfn(ccx, "main", llfty,
2164                                        ty::mk_nil(ccx.tcx())).unwrap_or_else(||{
2165             ccx.sess().span_err(sp, "entry symbol `main` defined multiple times");
2166             // FIXME: We should be smart and show a better diagnostic here.
2167             ccx.sess().help("did you use #[no_mangle] on `fn main`? Use #[start] instead");
2168             ccx.sess().abort_if_errors();
2169             panic!();
2170         });
2171
2172         // FIXME: #16581: Marking a symbol in the executable with `dllexport`
2173         // linkage forces MinGW's linker to output a `.reloc` section for ASLR
2174         if ccx.sess().target.target.options.is_like_windows {
2175             unsafe { llvm::LLVMRustSetDLLExportStorageClass(llfn) }
2176         }
2177
2178         let llbb = unsafe {
2179             llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn,
2180                                                 "top\0".as_ptr() as *const _)
2181         };
2182         let bld = ccx.raw_builder();
2183         unsafe {
2184             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2185
2186             debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx);
2187
2188             let (start_fn, args) = if use_start_lang_item {
2189                 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2190                     Ok(id) => id,
2191                     Err(s) => { ccx.sess().fatal(&s[..]); }
2192                 };
2193                 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2194                     get_item_val(ccx, start_def_id.node)
2195                 } else {
2196                     let start_fn_type = csearch::get_type(ccx.tcx(),
2197                                                           start_def_id).ty;
2198                     trans_external_path(ccx, start_def_id, start_fn_type)
2199                 };
2200
2201                 let args = {
2202                     let opaque_rust_main = llvm::LLVMBuildPointerCast(bld,
2203                         rust_main, Type::i8p(ccx).to_ref(),
2204                         "rust_main\0".as_ptr() as *const _);
2205
2206                     vec!(
2207                         opaque_rust_main,
2208                         get_param(llfn, 0),
2209                         get_param(llfn, 1)
2210                      )
2211                 };
2212                 (start_fn, args)
2213             } else {
2214                 debug!("using user-defined start fn");
2215                 let args = vec!(
2216                     get_param(llfn, 0 as c_uint),
2217                     get_param(llfn, 1 as c_uint)
2218                 );
2219
2220                 (rust_main, args)
2221             };
2222
2223             let result = llvm::LLVMBuildCall(bld,
2224                                              start_fn,
2225                                              args.as_ptr(),
2226                                              args.len() as c_uint,
2227                                              noname());
2228
2229             llvm::LLVMBuildRet(bld, result);
2230         }
2231     }
2232 }
2233
2234 fn exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, id: ast::NodeId,
2235                            ty: Ty<'tcx>, attrs: &[ast::Attribute]) -> String {
2236     match ccx.external_srcs().borrow().get(&id) {
2237         Some(&did) => {
2238             let sym = csearch::get_symbol(&ccx.sess().cstore, did);
2239             debug!("found item {} in other crate...", sym);
2240             return sym;
2241         }
2242         None => {}
2243     }
2244
2245     match attr::find_export_name_attr(ccx.sess().diagnostic(), attrs) {
2246         // Use provided name
2247         Some(name) => name.to_string(),
2248         _ => ccx.tcx().map.with_path(id, |path| {
2249             if attr::contains_name(attrs, "no_mangle") {
2250                 // Don't mangle
2251                 path.last().unwrap().to_string()
2252             } else {
2253                 match weak_lang_items::link_name(attrs) {
2254                     Some(name) => name.to_string(),
2255                     None => {
2256                         // Usual name mangling
2257                         mangle_exported_name(ccx, path, ty, id)
2258                     }
2259                 }
2260             }
2261         })
2262     }
2263 }
2264
2265 fn contains_null(s: &str) -> bool {
2266     s.bytes().any(|b| b == 0)
2267 }
2268
2269 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2270     debug!("get_item_val(id=`{}`)", id);
2271
2272     match ccx.item_vals().borrow().get(&id).cloned() {
2273         Some(v) => return v,
2274         None => {}
2275     }
2276
2277     let item = ccx.tcx().map.get(id);
2278     debug!("get_item_val: id={} item={:?}", id, item);
2279     let val = match item {
2280         ast_map::NodeItem(i) => {
2281             let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2282             let sym = || exported_name(ccx, id, ty, &i.attrs);
2283
2284             let v = match i.node {
2285                 ast::ItemStatic(_, _, ref expr) => {
2286                     // If this static came from an external crate, then
2287                     // we need to get the symbol from csearch instead of
2288                     // using the current crate's name/version
2289                     // information in the hash of the symbol
2290                     let sym = sym();
2291                     debug!("making {}", sym);
2292
2293                     // We need the translated value here, because for enums the
2294                     // LLVM type is not fully determined by the Rust type.
2295                     let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
2296                     let (v, ty) = consts::const_expr(ccx, &**expr, empty_substs);
2297                     ccx.static_values().borrow_mut().insert(id, v);
2298                     unsafe {
2299                         // boolean SSA values are i1, but they have to be stored in i8 slots,
2300                         // otherwise some LLVM optimization passes don't work as expected
2301                         let llty = if ty::type_is_bool(ty) {
2302                             llvm::LLVMInt8TypeInContext(ccx.llcx())
2303                         } else {
2304                             llvm::LLVMTypeOf(v)
2305                         };
2306
2307                         // FIXME(nagisa): probably should be declare_global, because no definition
2308                         // is happening here, but we depend on it being defined here from
2309                         // const::trans_static. This all logic should be replaced.
2310                         let g = declare::define_global(ccx, &sym[..],
2311                                                        Type::from_ref(llty)).unwrap_or_else(||{
2312                             ccx.sess().span_fatal(i.span, &format!("symbol `{}` is already defined",
2313                                                                    sym))
2314                         });
2315
2316                         if attr::contains_name(&i.attrs,
2317                                                "thread_local") {
2318                             llvm::set_thread_local(g, true);
2319                         }
2320                         ccx.item_symbols().borrow_mut().insert(i.id, sym);
2321                         g
2322                     }
2323                 }
2324
2325                 ast::ItemFn(_, _, abi, _, _) => {
2326                     let sym = sym();
2327                     let llfn = if abi == Rust {
2328                         register_fn(ccx, i.span, sym, i.id, ty)
2329                     } else {
2330                         foreign::register_rust_fn_with_foreign_abi(ccx, i.span, sym, i.id)
2331                     };
2332                     attributes::from_fn_attrs(ccx, &i.attrs, llfn);
2333                     llfn
2334                 }
2335
2336                 _ => ccx.sess().bug("get_item_val: weird result in table")
2337             };
2338
2339             match attr::first_attr_value_str_by_name(&i.attrs,
2340                                                      "link_section") {
2341                 Some(sect) => {
2342                     if contains_null(&sect) {
2343                         ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`",
2344                                                  &sect));
2345                     }
2346                     unsafe {
2347                         let buf = CString::new(sect.as_bytes()).unwrap();
2348                         llvm::LLVMSetSection(v, buf.as_ptr());
2349                     }
2350                 },
2351                 None => ()
2352             }
2353
2354             v
2355         }
2356
2357         ast_map::NodeTraitItem(trait_item) => {
2358             debug!("get_item_val(): processing a NodeTraitItem");
2359             match trait_item.node {
2360                 ast::MethodTraitItem(_, Some(_)) => {
2361                     register_method(ccx, id, &trait_item.attrs, trait_item.span)
2362                 }
2363                 _ => {
2364                     ccx.sess().span_bug(trait_item.span,
2365                         "unexpected variant: trait item other than a provided \
2366                          method in get_item_val()");
2367                 }
2368             }
2369         }
2370
2371         ast_map::NodeImplItem(impl_item) => {
2372             match impl_item.node {
2373                 ast::MethodImplItem(..) => {
2374                     register_method(ccx, id, &impl_item.attrs, impl_item.span)
2375                 }
2376                 _ => {
2377                     ccx.sess().span_bug(impl_item.span,
2378                         "unexpected variant: non-method impl item in \
2379                          get_item_val()");
2380                 }
2381             }
2382         }
2383
2384         ast_map::NodeForeignItem(ni) => {
2385             match ni.node {
2386                 ast::ForeignItemFn(..) => {
2387                     let abi = ccx.tcx().map.get_foreign_abi(id);
2388                     let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2389                     let name = foreign::link_name(&*ni);
2390                     let llfn = foreign::register_foreign_item_fn(ccx, abi, ty, &name);
2391                     attributes::from_fn_attrs(ccx, &ni.attrs, llfn);
2392                     llfn
2393                 }
2394                 ast::ForeignItemStatic(..) => {
2395                     foreign::register_static(ccx, &*ni)
2396                 }
2397             }
2398         }
2399
2400         ast_map::NodeVariant(ref v) => {
2401             let llfn;
2402             let args = match v.node.kind {
2403                 ast::TupleVariantKind(ref args) => args,
2404                 ast::StructVariantKind(_) => {
2405                     ccx.sess().bug("struct variant kind unexpected in get_item_val")
2406                 }
2407             };
2408             assert!(!args.is_empty());
2409             let ty = ty::node_id_to_type(ccx.tcx(), id);
2410             let parent = ccx.tcx().map.get_parent(id);
2411             let enm = ccx.tcx().map.expect_item(parent);
2412             let sym = exported_name(ccx,
2413                                     id,
2414                                     ty,
2415                                     &enm.attrs);
2416
2417             llfn = match enm.node {
2418                 ast::ItemEnum(_, _) => {
2419                     register_fn(ccx, (*v).span, sym, id, ty)
2420                 }
2421                 _ => ccx.sess().bug("NodeVariant, shouldn't happen")
2422             };
2423             attributes::inline(llfn, attributes::InlineAttr::Hint);
2424             llfn
2425         }
2426
2427         ast_map::NodeStructCtor(struct_def) => {
2428             // Only register the constructor if this is a tuple-like struct.
2429             let ctor_id = match struct_def.ctor_id {
2430                 None => {
2431                     ccx.sess().bug("attempt to register a constructor of \
2432                                     a non-tuple-like struct")
2433                 }
2434                 Some(ctor_id) => ctor_id,
2435             };
2436             let parent = ccx.tcx().map.get_parent(id);
2437             let struct_item = ccx.tcx().map.expect_item(parent);
2438             let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2439             let sym = exported_name(ccx,
2440                                     id,
2441                                     ty,
2442                                     &struct_item.attrs);
2443             let llfn = register_fn(ccx, struct_item.span,
2444                                    sym, ctor_id, ty);
2445             attributes::inline(llfn, attributes::InlineAttr::Hint);
2446             llfn
2447         }
2448
2449         ref variant => {
2450             ccx.sess().bug(&format!("get_item_val(): unexpected variant: {:?}",
2451                                    variant))
2452         }
2453     };
2454
2455     // All LLVM globals and functions are initially created as external-linkage
2456     // declarations.  If `trans_item`/`trans_fn` later turns the declaration
2457     // into a definition, it adjusts the linkage then (using `update_linkage`).
2458     //
2459     // The exception is foreign items, which have their linkage set inside the
2460     // call to `foreign::register_*` above.  We don't touch the linkage after
2461     // that (`foreign::trans_foreign_mod` doesn't adjust the linkage like the
2462     // other item translation functions do).
2463
2464     ccx.item_vals().borrow_mut().insert(id, val);
2465     val
2466 }
2467
2468 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2469                    attrs: &[ast::Attribute], span: Span) -> ValueRef {
2470     let mty = ty::node_id_to_type(ccx.tcx(), id);
2471
2472     let sym = exported_name(ccx, id, mty, &attrs);
2473
2474     if let ty::ty_bare_fn(_, ref f) = mty.sty {
2475         let llfn = if f.abi == Rust || f.abi == RustCall {
2476             register_fn(ccx, span, sym, id, mty)
2477         } else {
2478             foreign::register_rust_fn_with_foreign_abi(ccx, span, sym, id)
2479         };
2480         attributes::from_fn_attrs(ccx, &attrs, llfn);
2481         return llfn;
2482     } else {
2483         ccx.sess().span_bug(span, "expected bare rust function");
2484     }
2485 }
2486
2487 pub fn crate_ctxt_to_encode_parms<'a, 'tcx>(cx: &'a SharedCrateContext<'tcx>,
2488                                             ie: encoder::EncodeInlinedItem<'a>)
2489                                             -> encoder::EncodeParams<'a, 'tcx> {
2490     encoder::EncodeParams {
2491         diag: cx.sess().diagnostic(),
2492         tcx: cx.tcx(),
2493         reexports: cx.export_map(),
2494         item_symbols: cx.item_symbols(),
2495         link_meta: cx.link_meta(),
2496         cstore: &cx.sess().cstore,
2497         encode_inlined_item: ie,
2498         reachable: cx.reachable(),
2499     }
2500 }
2501
2502 pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
2503     use flate;
2504
2505     let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2506         *ty != config::CrateTypeExecutable
2507     });
2508     if !any_library {
2509         return Vec::new()
2510     }
2511
2512     let encode_inlined_item: encoder::EncodeInlinedItem =
2513         Box::new(|ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii));
2514
2515     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2516     let metadata = encoder::encode_metadata(encode_parms, krate);
2517     let mut compressed = encoder::metadata_encoding_version.to_vec();
2518     compressed.push_all(&flate::deflate_bytes(&metadata));
2519     let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
2520     let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
2521     let name = format!("rust_metadata_{}_{}",
2522                        cx.link_meta().crate_name,
2523                        cx.link_meta().crate_hash);
2524     let buf = CString::new(name).unwrap();
2525     let llglobal = unsafe {
2526         llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(),
2527                             buf.as_ptr())
2528     };
2529     unsafe {
2530         llvm::LLVMSetInitializer(llglobal, llconst);
2531         let name = loader::meta_section_name(&cx.sess().target.target);
2532         let name = CString::new(name).unwrap();
2533         llvm::LLVMSetSection(llglobal, name.as_ptr())
2534     }
2535     return metadata;
2536 }
2537
2538 /// Find any symbols that are defined in one compilation unit, but not declared
2539 /// in any other compilation unit.  Give these symbols internal linkage.
2540 fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
2541     unsafe {
2542         let mut declared = HashSet::new();
2543
2544         let iter_globals = |llmod| {
2545             ValueIter {
2546                 cur: llvm::LLVMGetFirstGlobal(llmod),
2547                 step: llvm::LLVMGetNextGlobal,
2548             }
2549         };
2550
2551         let iter_functions = |llmod| {
2552             ValueIter {
2553                 cur: llvm::LLVMGetFirstFunction(llmod),
2554                 step: llvm::LLVMGetNextFunction,
2555             }
2556         };
2557
2558         // Collect all external declarations in all compilation units.
2559         for ccx in cx.iter() {
2560             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2561                 let linkage = llvm::LLVMGetLinkage(val);
2562                 // We only care about external declarations (not definitions)
2563                 // and available_externally definitions.
2564                 if !(linkage == llvm::ExternalLinkage as c_uint &&
2565                      llvm::LLVMIsDeclaration(val) != 0) &&
2566                    !(linkage == llvm::AvailableExternallyLinkage as c_uint) {
2567                     continue
2568                 }
2569
2570                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2571                                 .to_bytes().to_vec();
2572                 declared.insert(name);
2573             }
2574         }
2575
2576         // Examine each external definition.  If the definition is not used in
2577         // any other compilation unit, and is not reachable from other crates,
2578         // then give it internal linkage.
2579         for ccx in cx.iter() {
2580             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2581                 // We only care about external definitions.
2582                 if !(llvm::LLVMGetLinkage(val) == llvm::ExternalLinkage as c_uint &&
2583                      llvm::LLVMIsDeclaration(val) == 0) {
2584                     continue
2585                 }
2586
2587                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2588                                 .to_bytes().to_vec();
2589                 if !declared.contains(&name) &&
2590                    !reachable.contains(str::from_utf8(&name).unwrap()) {
2591                     llvm::SetLinkage(val, llvm::InternalLinkage);
2592                 }
2593             }
2594         }
2595     }
2596
2597
2598     struct ValueIter {
2599         cur: ValueRef,
2600         step: unsafe extern "C" fn(ValueRef) -> ValueRef,
2601     }
2602
2603     impl Iterator for ValueIter {
2604         type Item = ValueRef;
2605
2606         fn next(&mut self) -> Option<ValueRef> {
2607             let old = self.cur;
2608             if !old.is_null() {
2609                 self.cur = unsafe {
2610                     let step: unsafe extern "C" fn(ValueRef) -> ValueRef =
2611                         mem::transmute_copy(&self.step);
2612                     step(old)
2613                 };
2614                 Some(old)
2615             } else {
2616                 None
2617             }
2618         }
2619     }
2620 }
2621
2622 pub fn trans_crate<'tcx>(analysis: ty::CrateAnalysis<'tcx>)
2623                          -> (ty::ctxt<'tcx>, CrateTranslation) {
2624     let ty::CrateAnalysis { ty_cx: tcx, export_map, reachable, name, .. } = analysis;
2625     let krate = tcx.map.krate();
2626
2627     let check_overflow = if let Some(v) = tcx.sess.opts.debugging_opts.force_overflow_checks {
2628         v
2629     } else {
2630         tcx.sess.opts.debug_assertions
2631     };
2632
2633     let check_dropflag = if let Some(v) = tcx.sess.opts.debugging_opts.force_dropflag_checks {
2634         v
2635     } else {
2636         tcx.sess.opts.debug_assertions
2637     };
2638
2639     // Before we touch LLVM, make sure that multithreading is enabled.
2640     unsafe {
2641         use std::sync::{Once, ONCE_INIT};
2642         static INIT: Once = ONCE_INIT;
2643         static mut POISONED: bool = false;
2644         INIT.call_once(|| {
2645             if llvm::LLVMStartMultithreaded() != 1 {
2646                 // use an extra bool to make sure that all future usage of LLVM
2647                 // cannot proceed despite the Once not running more than once.
2648                 POISONED = true;
2649             }
2650         });
2651
2652         if POISONED {
2653             tcx.sess.bug("couldn't enable multi-threaded LLVM");
2654         }
2655     }
2656
2657     let link_meta = link::build_link_meta(&tcx.sess, krate, name);
2658
2659     let codegen_units = tcx.sess.opts.cg.codegen_units;
2660     let shared_ccx = SharedCrateContext::new(&link_meta.crate_name,
2661                                              codegen_units,
2662                                              tcx,
2663                                              export_map,
2664                                              Sha256::new(),
2665                                              link_meta.clone(),
2666                                              reachable,
2667                                              check_overflow,
2668                                              check_dropflag);
2669
2670     {
2671         let ccx = shared_ccx.get_ccx(0);
2672
2673         // First, verify intrinsics.
2674         intrinsic::check_intrinsics(&ccx);
2675
2676         // Next, translate the module.
2677         {
2678             let _icx = push_ctxt("text");
2679             trans_mod(&ccx, &krate.module);
2680         }
2681     }
2682
2683     for ccx in shared_ccx.iter() {
2684         if ccx.sess().opts.debuginfo != NoDebugInfo {
2685             debuginfo::finalize(&ccx);
2686         }
2687     }
2688
2689     // Translate the metadata.
2690     let metadata = write_metadata(&shared_ccx, krate);
2691
2692     if shared_ccx.sess().trans_stats() {
2693         let stats = shared_ccx.stats();
2694         println!("--- trans stats ---");
2695         println!("n_glues_created: {}", stats.n_glues_created.get());
2696         println!("n_null_glues: {}", stats.n_null_glues.get());
2697         println!("n_real_glues: {}", stats.n_real_glues.get());
2698
2699         println!("n_fns: {}", stats.n_fns.get());
2700         println!("n_monos: {}", stats.n_monos.get());
2701         println!("n_inlines: {}", stats.n_inlines.get());
2702         println!("n_closures: {}", stats.n_closures.get());
2703         println!("fn stats:");
2704         stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
2705             insns_b.cmp(&insns_a)
2706         });
2707         for tuple in &*stats.fn_stats.borrow() {
2708             match *tuple {
2709                 (ref name, insns) => {
2710                     println!("{} insns, {}", insns, *name);
2711                 }
2712             }
2713         }
2714     }
2715     if shared_ccx.sess().count_llvm_insns() {
2716         for (k, v) in &*shared_ccx.stats().llvm_insns.borrow() {
2717             println!("{:7} {}", *v, *k);
2718         }
2719     }
2720
2721     let modules = shared_ccx.iter()
2722         .map(|ccx| ModuleTranslation { llcx: ccx.llcx(), llmod: ccx.llmod() })
2723         .collect();
2724
2725     let mut reachable: Vec<String> = shared_ccx.reachable().iter().filter_map(|id| {
2726         shared_ccx.item_symbols().borrow().get(id).map(|s| s.to_string())
2727     }).collect();
2728
2729     // For the purposes of LTO, we add to the reachable set all of the upstream
2730     // reachable extern fns. These functions are all part of the public ABI of
2731     // the final product, so LTO needs to preserve them.
2732     shared_ccx.sess().cstore.iter_crate_data(|cnum, _| {
2733         let syms = csearch::get_reachable_extern_fns(&shared_ccx.sess().cstore, cnum);
2734         reachable.extend(syms.into_iter().map(|did| {
2735             csearch::get_symbol(&shared_ccx.sess().cstore, did)
2736         }));
2737     });
2738
2739     // Make sure that some other crucial symbols are not eliminated from the
2740     // module. This includes the main function, the crate map (used for debug
2741     // log settings and I/O), and finally the curious rust_stack_exhausted
2742     // symbol. This symbol is required for use by the libmorestack library that
2743     // we link in, so we must ensure that this symbol is not internalized (if
2744     // defined in the crate).
2745     reachable.push("main".to_string());
2746     reachable.push("rust_stack_exhausted".to_string());
2747
2748     // referenced from .eh_frame section on some platforms
2749     reachable.push("rust_eh_personality".to_string());
2750     // referenced from rt/rust_try.ll
2751     reachable.push("rust_eh_personality_catch".to_string());
2752
2753     if codegen_units > 1 {
2754         internalize_symbols(&shared_ccx, &reachable.iter().cloned().collect());
2755     }
2756
2757     let metadata_module = ModuleTranslation {
2758         llcx: shared_ccx.metadata_llcx(),
2759         llmod: shared_ccx.metadata_llmod(),
2760     };
2761     let formats = shared_ccx.tcx().dependency_formats.borrow().clone();
2762     let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
2763
2764     let translation = CrateTranslation {
2765         modules: modules,
2766         metadata_module: metadata_module,
2767         link: link_meta,
2768         metadata: metadata,
2769         reachable: reachable,
2770         crate_formats: formats,
2771         no_builtins: no_builtins,
2772     };
2773
2774     (shared_ccx.take_tcx(), translation)
2775 }