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