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