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