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