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