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