]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/base.rs
98342bfbcdc320643aa0d804544d3d7e6c46887a
[rust.git] / src / librustc / middle / 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::t 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::t`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 use back::link::{mangle_exported_name};
29 use back::{link, abi};
30 use driver::config;
31 use driver::config::{NoDebugInfo, FullDebugInfo};
32 use driver::driver::{CrateAnalysis, CrateTranslation};
33 use driver::session::Session;
34 use lint;
35 use llvm::{BasicBlockRef, ModuleRef, ValueRef, Vector, get_param};
36 use llvm;
37 use metadata::{csearch, encoder, loader};
38 use middle::astencode;
39 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
40 use middle::subst;
41 use middle::weak_lang_items;
42 use middle::subst::Subst;
43 use middle::trans::_match;
44 use middle::trans::adt;
45 use middle::trans::build::*;
46 use middle::trans::builder::{Builder, noname};
47 use middle::trans::callee;
48 use middle::trans::cleanup;
49 use middle::trans::cleanup::CleanupMethods;
50 use middle::trans::common::*;
51 use middle::trans::consts;
52 use middle::trans::controlflow;
53 use middle::trans::datum;
54 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
55 use middle::trans::debuginfo;
56 use middle::trans::expr;
57 use middle::trans::foreign;
58 use middle::trans::glue;
59 use middle::trans::inline;
60 use middle::trans::intrinsic;
61 use middle::trans::machine;
62 use middle::trans::machine::{llalign_of_min, llsize_of, llsize_of_real};
63 use middle::trans::meth;
64 use middle::trans::monomorphize;
65 use middle::trans::tvec;
66 use middle::trans::type_::Type;
67 use middle::trans::type_of;
68 use middle::trans::type_of::*;
69 use middle::trans::value::Value;
70 use middle::ty;
71 use middle::typeck;
72 use util::common::indenter;
73 use util::ppaux::{Repr, ty_to_string};
74 use util::sha2::Sha256;
75 use util::nodemap::NodeMap;
76
77 use arena::TypedArena;
78 use libc::{c_uint, uint64_t};
79 use std::c_str::ToCStr;
80 use std::cell::{Cell, RefCell};
81 use std::rc::Rc;
82 use std::{i8, i16, i32, i64};
83 use std::gc::Gc;
84 use syntax::abi::{X86, X86_64, Arm, Mips, Mipsel, Rust, RustCall};
85 use syntax::abi::{RustIntrinsic, Abi};
86 use syntax::ast_util::{local_def, is_local};
87 use syntax::attr::AttrMetaMethods;
88 use syntax::attr;
89 use syntax::codemap::Span;
90 use syntax::parse::token::InternedString;
91 use syntax::visit::Visitor;
92 use syntax::visit;
93 use syntax::{ast, ast_util, ast_map};
94
95 use time;
96
97 local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)
98
99 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
100     match task_local_insn_key.get() {
101         Some(ctx) => blk(ctx.borrow().as_slice()),
102         None => ()
103     }
104 }
105
106 pub fn init_insn_ctxt() {
107     task_local_insn_key.replace(Some(RefCell::new(Vec::new())));
108 }
109
110 pub struct _InsnCtxt {
111     _cannot_construct_outside_of_this_module: ()
112 }
113
114 #[unsafe_destructor]
115 impl Drop for _InsnCtxt {
116     fn drop(&mut self) {
117         match task_local_insn_key.get() {
118             Some(ctx) => { ctx.borrow_mut().pop(); }
119             None => {}
120         }
121     }
122 }
123
124 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
125     debug!("new InsnCtxt: {}", s);
126     match task_local_insn_key.get() {
127         Some(ctx) => ctx.borrow_mut().push(s),
128         None => {}
129     }
130     _InsnCtxt { _cannot_construct_outside_of_this_module: () }
131 }
132
133 pub struct StatRecorder<'a> {
134     ccx: &'a CrateContext,
135     name: Option<String>,
136     start: u64,
137     istart: uint,
138 }
139
140 impl<'a> StatRecorder<'a> {
141     pub fn new(ccx: &'a CrateContext, name: String) -> StatRecorder<'a> {
142         let start = if ccx.sess().trans_stats() {
143             time::precise_time_ns()
144         } else {
145             0
146         };
147         let istart = ccx.stats.n_llvm_insns.get();
148         StatRecorder {
149             ccx: ccx,
150             name: Some(name),
151             start: start,
152             istart: istart,
153         }
154     }
155 }
156
157 #[unsafe_destructor]
158 impl<'a> Drop for StatRecorder<'a> {
159     fn drop(&mut self) {
160         if self.ccx.sess().trans_stats() {
161             let end = time::precise_time_ns();
162             let elapsed = ((end - self.start) / 1_000_000) as uint;
163             let iend = self.ccx.stats.n_llvm_insns.get();
164             self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
165                                                        elapsed,
166                                                        iend - self.istart));
167             self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
168             // Reset LLVM insn count to avoid compound costs.
169             self.ccx.stats.n_llvm_insns.set(self.istart);
170         }
171     }
172 }
173
174 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
175 fn decl_fn(ccx: &CrateContext, name: &str, cc: llvm::CallConv,
176            ty: Type, output: ty::t) -> ValueRef {
177
178     let llfn: ValueRef = name.with_c_str(|buf| {
179         unsafe {
180             llvm::LLVMGetOrInsertFunction(ccx.llmod, buf, ty.to_ref())
181         }
182     });
183
184     match ty::get(output).sty {
185         // functions returning bottom may unwind, but can never return normally
186         ty::ty_bot => {
187             unsafe {
188                 llvm::LLVMAddFunctionAttribute(llfn,
189                                                llvm::FunctionIndex as c_uint,
190                                                llvm::NoReturnAttribute as uint64_t)
191             }
192         }
193         _ => {}
194     }
195
196     if ccx.tcx.sess.opts.cg.no_redzone {
197         unsafe {
198             llvm::LLVMAddFunctionAttribute(llfn,
199                                            llvm::FunctionIndex as c_uint,
200                                            llvm::NoRedZoneAttribute as uint64_t)
201         }
202     }
203
204     llvm::SetFunctionCallConv(llfn, cc);
205     // Function addresses in Rust are never significant, allowing functions to be merged.
206     llvm::SetUnnamedAddr(llfn, true);
207
208     if ccx.is_split_stack_supported() {
209         set_split_stack(llfn);
210     }
211
212     llfn
213 }
214
215 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
216 pub fn decl_cdecl_fn(ccx: &CrateContext,
217                      name: &str,
218                      ty: Type,
219                      output: ty::t) -> ValueRef {
220     decl_fn(ccx, name, llvm::CCallConv, ty, output)
221 }
222
223 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
224 pub fn get_extern_fn(ccx: &CrateContext,
225                      externs: &mut ExternMap,
226                      name: &str,
227                      cc: llvm::CallConv,
228                      ty: Type,
229                      output: ty::t)
230                      -> ValueRef {
231     match externs.find_equiv(&name) {
232         Some(n) => return *n,
233         None => {}
234     }
235     let f = decl_fn(ccx, name, cc, ty, output);
236     externs.insert(name.to_string(), f);
237     f
238 }
239
240 fn get_extern_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str, did: ast::DefId) -> ValueRef {
241     match ccx.externs.borrow().find_equiv(&name) {
242         Some(n) => return *n,
243         None => ()
244     }
245
246     let f = decl_rust_fn(ccx, fn_ty, name);
247
248     csearch::get_item_attrs(&ccx.sess().cstore, did, |attrs| {
249         set_llvm_fn_attrs(attrs.as_slice(), f)
250     });
251
252     ccx.externs.borrow_mut().insert(name.to_string(), f);
253     f
254 }
255
256 pub fn decl_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
257     let (inputs, output, abi, env) = match ty::get(fn_ty).sty {
258         ty::ty_bare_fn(ref f) => {
259             (f.sig.inputs.clone(), f.sig.output, f.abi, None)
260         }
261         ty::ty_closure(ref f) => {
262             (f.sig.inputs.clone(), f.sig.output, f.abi, Some(Type::i8p(ccx)))
263         }
264         ty::ty_unboxed_closure(closure_did) => {
265             let unboxed_closure_types = ccx.tcx
266                                            .unboxed_closure_types
267                                            .borrow();
268             let function_type = unboxed_closure_types.get(&closure_did);
269             let llenvironment_type = type_of(ccx, fn_ty).ptr_to();
270             (function_type.sig.inputs.clone(),
271              function_type.sig.output,
272              RustCall,
273              Some(llenvironment_type))
274         }
275         _ => fail!("expected closure or fn")
276     };
277
278     let llfty = type_of_rust_fn(ccx, env, inputs.as_slice(), output, abi);
279     debug!("decl_rust_fn(input count={},type={})",
280            inputs.len(),
281            ccx.tn.type_to_string(llfty));
282
283     let llfn = decl_fn(ccx, name, llvm::CCallConv, llfty, output);
284     let attrs = get_fn_llvm_attributes(ccx, fn_ty);
285     for &(idx, attr) in attrs.iter() {
286         unsafe {
287             llvm::LLVMAddFunctionAttribute(llfn, idx as c_uint, attr);
288         }
289     }
290
291     llfn
292 }
293
294 pub fn decl_internal_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
295     let llfn = decl_rust_fn(ccx, fn_ty, name);
296     llvm::SetLinkage(llfn, llvm::InternalLinkage);
297     llfn
298 }
299
300 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
301                         name: &str, ty: Type) -> ValueRef {
302     match externs.find_equiv(&name) {
303         Some(n) => return *n,
304         None => ()
305     }
306     unsafe {
307         let c = name.with_c_str(|buf| {
308             llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
309         });
310         externs.insert(name.to_string(), c);
311         return c;
312     }
313 }
314
315 // Returns a pointer to the body for the box. The box may be an opaque
316 // box. The result will be casted to the type of body_t, if it is statically
317 // known.
318 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
319     let _icx = push_ctxt("at_box_body");
320     let ccx = bcx.ccx();
321     let ty = Type::at_box(ccx, type_of(ccx, body_t));
322     let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
323     GEPi(bcx, boxptr, [0u, abi::box_field_body])
324 }
325
326 fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
327     match bcx.tcx().lang_items.require(it) {
328         Ok(id) => id,
329         Err(s) => {
330             bcx.sess().fatal(format!("allocation of `{}` {}",
331                                      bcx.ty_to_string(info_ty),
332                                      s).as_slice());
333         }
334     }
335 }
336
337 // The following malloc_raw_dyn* functions allocate a box to contain
338 // a given type, but with a potentially dynamic size.
339
340 pub fn malloc_raw_dyn<'a>(bcx: &'a Block<'a>,
341                           ptr_ty: ty::t,
342                           size: ValueRef,
343                           align: ValueRef)
344                           -> Result<'a> {
345     let _icx = push_ctxt("malloc_raw_exchange");
346     let ccx = bcx.ccx();
347
348     // Allocate space:
349     let r = callee::trans_lang_call(bcx,
350         require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
351         [size, align],
352         None);
353
354     let llty_ptr = type_of::type_of(ccx, ptr_ty);
355     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
356 }
357
358 pub fn malloc_raw_dyn_managed<'a>(
359                       bcx: &'a Block<'a>,
360                       t: ty::t,
361                       alloc_fn: LangItem,
362                       size: ValueRef)
363                       -> Result<'a> {
364     let _icx = push_ctxt("malloc_raw_managed");
365     let ccx = bcx.ccx();
366
367     let langcall = require_alloc_fn(bcx, t, alloc_fn);
368
369     // Grab the TypeRef type of box_ptr_ty.
370     let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
371     let llty = type_of(ccx, box_ptr_ty);
372     let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
373
374     // Allocate space:
375     let drop_glue = glue::get_drop_glue(ccx, t);
376     let r = callee::trans_lang_call(
377         bcx,
378         langcall,
379         [
380             PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
381             size,
382             llalign
383         ],
384         None);
385     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
386 }
387
388 // Type descriptor and type glue stuff
389
390 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
391     match ccx.tydescs.borrow().find(&t) {
392         Some(inf) => return inf.clone(),
393         _ => { }
394     }
395
396     ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
397     let inf = Rc::new(glue::declare_tydesc(ccx, t));
398
399     ccx.tydescs.borrow_mut().insert(t, inf.clone());
400     inf
401 }
402
403 #[allow(dead_code)] // useful
404 pub fn set_optimize_for_size(f: ValueRef) {
405     llvm::SetFunctionAttribute(f, llvm::OptimizeForSizeAttribute)
406 }
407
408 pub fn set_no_inline(f: ValueRef) {
409     llvm::SetFunctionAttribute(f, llvm::NoInlineAttribute)
410 }
411
412 #[allow(dead_code)] // useful
413 pub fn set_no_unwind(f: ValueRef) {
414     llvm::SetFunctionAttribute(f, llvm::NoUnwindAttribute)
415 }
416
417 // Tell LLVM to emit the information necessary to unwind the stack for the
418 // function f.
419 pub fn set_uwtable(f: ValueRef) {
420     llvm::SetFunctionAttribute(f, llvm::UWTableAttribute)
421 }
422
423 pub fn set_inline_hint(f: ValueRef) {
424     llvm::SetFunctionAttribute(f, llvm::InlineHintAttribute)
425 }
426
427 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
428     use syntax::attr::*;
429     // Set the inline hint if there is one
430     match find_inline_attr(attrs) {
431         InlineHint   => set_inline_hint(llfn),
432         InlineAlways => set_always_inline(llfn),
433         InlineNever  => set_no_inline(llfn),
434         InlineNone   => { /* fallthrough */ }
435     }
436
437     // Add the no-split-stack attribute if requested
438     if contains_name(attrs, "no_split_stack") {
439         unset_split_stack(llfn);
440     }
441
442     if contains_name(attrs, "cold") {
443         unsafe {
444             llvm::LLVMAddFunctionAttribute(llfn,
445                                            llvm::FunctionIndex as c_uint,
446                                            llvm::ColdAttribute as uint64_t)
447         }
448     }
449 }
450
451 pub fn set_always_inline(f: ValueRef) {
452     llvm::SetFunctionAttribute(f, llvm::AlwaysInlineAttribute)
453 }
454
455 pub fn set_split_stack(f: ValueRef) {
456     "split-stack".with_c_str(|buf| {
457         unsafe { llvm::LLVMAddFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
458     })
459 }
460
461 pub fn unset_split_stack(f: ValueRef) {
462     "split-stack".with_c_str(|buf| {
463         unsafe { llvm::LLVMRemoveFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
464     })
465 }
466
467 // Double-check that we never ask LLVM to declare the same symbol twice. It
468 // silently mangles such symbols, breaking our linkage model.
469 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) {
470     if ccx.all_llvm_symbols.borrow().contains(&sym) {
471         ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).as_slice());
472     }
473     ccx.all_llvm_symbols.borrow_mut().insert(sym);
474 }
475
476
477 pub fn get_res_dtor(ccx: &CrateContext,
478                     did: ast::DefId,
479                     t: ty::t,
480                     parent_id: ast::DefId,
481                     substs: &subst::Substs)
482                  -> ValueRef {
483     let _icx = push_ctxt("trans_res_dtor");
484     let did = if did.krate != ast::LOCAL_CRATE {
485         inline::maybe_instantiate_inline(ccx, did)
486     } else {
487         did
488     };
489
490     if !substs.types.is_empty() {
491         assert_eq!(did.krate, ast::LOCAL_CRATE);
492
493         let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, substs);
494         let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, vtables, None);
495
496         val
497     } else if did.krate == ast::LOCAL_CRATE {
498         get_item_val(ccx, did.node)
499     } else {
500         let tcx = ccx.tcx();
501         let name = csearch::get_symbol(&ccx.sess().cstore, did);
502         let class_ty = ty::lookup_item_type(tcx, parent_id).ty.subst(tcx, substs);
503         let llty = type_of_dtor(ccx, class_ty);
504         let dtor_ty = ty::mk_ctor_fn(ccx.tcx(), ast::DUMMY_NODE_ID,
505                                      [glue::get_drop_glue_type(ccx, t)], ty::mk_nil());
506         get_extern_fn(ccx,
507                       &mut *ccx.externs.borrow_mut(),
508                       name.as_slice(),
509                       llvm::CCallConv,
510                       llty,
511                       dtor_ty)
512     }
513 }
514
515 // Structural comparison: a rather involved form of glue.
516 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
517     if cx.sess().opts.cg.save_temps {
518         s.with_c_str(|buf| {
519             unsafe {
520                 llvm::LLVMSetValueName(v, buf)
521             }
522         })
523     }
524 }
525
526
527 // Used only for creating scalar comparison glue.
528 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
529
530 pub fn compare_scalar_types<'a>(
531                             cx: &'a Block<'a>,
532                             lhs: ValueRef,
533                             rhs: ValueRef,
534                             t: ty::t,
535                             op: ast::BinOp)
536                             -> Result<'a> {
537     let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
538
539     match ty::get(t).sty {
540         ty::ty_nil => f(nil_type),
541         ty::ty_bool | ty::ty_ptr(_) |
542         ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
543         ty::ty_int(_) => f(signed_int),
544         ty::ty_float(_) => f(floating_point),
545             // Should never get here, because t is scalar.
546         _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
547     }
548 }
549
550
551 // A helper function to do the actual comparison of scalar values.
552 pub fn compare_scalar_values<'a>(
553                              cx: &'a Block<'a>,
554                              lhs: ValueRef,
555                              rhs: ValueRef,
556                              nt: scalar_type,
557                              op: ast::BinOp)
558                              -> ValueRef {
559     let _icx = push_ctxt("compare_scalar_values");
560     fn die(cx: &Block) -> ! {
561         cx.sess().bug("compare_scalar_values: must be a comparison operator");
562     }
563     match nt {
564       nil_type => {
565         // We don't need to do actual comparisons for nil.
566         // () == () holds but () < () does not.
567         match op {
568           ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(cx.ccx(), true),
569           ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(cx.ccx(), false),
570           // refinements would be nice
571           _ => die(cx)
572         }
573       }
574       floating_point => {
575         let cmp = match op {
576           ast::BiEq => llvm::RealOEQ,
577           ast::BiNe => llvm::RealUNE,
578           ast::BiLt => llvm::RealOLT,
579           ast::BiLe => llvm::RealOLE,
580           ast::BiGt => llvm::RealOGT,
581           ast::BiGe => llvm::RealOGE,
582           _ => die(cx)
583         };
584         return FCmp(cx, cmp, lhs, rhs);
585       }
586       signed_int => {
587         let cmp = match op {
588           ast::BiEq => llvm::IntEQ,
589           ast::BiNe => llvm::IntNE,
590           ast::BiLt => llvm::IntSLT,
591           ast::BiLe => llvm::IntSLE,
592           ast::BiGt => llvm::IntSGT,
593           ast::BiGe => llvm::IntSGE,
594           _ => die(cx)
595         };
596         return ICmp(cx, cmp, lhs, rhs);
597       }
598       unsigned_int => {
599         let cmp = match op {
600           ast::BiEq => llvm::IntEQ,
601           ast::BiNe => llvm::IntNE,
602           ast::BiLt => llvm::IntULT,
603           ast::BiLe => llvm::IntULE,
604           ast::BiGt => llvm::IntUGT,
605           ast::BiGe => llvm::IntUGE,
606           _ => die(cx)
607         };
608         return ICmp(cx, cmp, lhs, rhs);
609       }
610     }
611 }
612
613 pub fn compare_simd_types(
614                     cx: &Block,
615                     lhs: ValueRef,
616                     rhs: ValueRef,
617                     t: ty::t,
618                     size: uint,
619                     op: ast::BinOp)
620                     -> ValueRef {
621     match ty::get(t).sty {
622         ty::ty_float(_) => {
623             // The comparison operators for floating point vectors are challenging.
624             // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
625             // then bitcast to a floating point vector, the result will be `-NaN`
626             // for each truth value. Because of this they are unsupported.
627             cx.sess().bug("compare_simd_types: comparison operators \
628                            not supported for floating point SIMD types")
629         },
630         ty::ty_uint(_) | ty::ty_int(_) => {
631             let cmp = match op {
632                 ast::BiEq => llvm::IntEQ,
633                 ast::BiNe => llvm::IntNE,
634                 ast::BiLt => llvm::IntSLT,
635                 ast::BiLe => llvm::IntSLE,
636                 ast::BiGt => llvm::IntSGT,
637                 ast::BiGe => llvm::IntSGE,
638                 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
639             };
640             let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
641             // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
642             // to get the correctly sized type. This will compile to a single instruction
643             // once the IR is converted to assembly if the SIMD instruction is supported
644             // by the target architecture.
645             SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
646         },
647         _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
648     }
649 }
650
651 pub type val_and_ty_fn<'r,'b> =
652     |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
653
654 // Iterates through the elements of a structural type.
655 pub fn iter_structural_ty<'r,
656                           'b>(
657                           cx: &'b Block<'b>,
658                           av: ValueRef,
659                           t: ty::t,
660                           f: val_and_ty_fn<'r,'b>)
661                           -> &'b Block<'b> {
662     let _icx = push_ctxt("iter_structural_ty");
663
664     fn iter_variant<'r,
665                     'b>(
666                     cx: &'b Block<'b>,
667                     repr: &adt::Repr,
668                     av: ValueRef,
669                     variant: &ty::VariantInfo,
670                     substs: &subst::Substs,
671                     f: val_and_ty_fn<'r,'b>)
672                     -> &'b Block<'b> {
673         let _icx = push_ctxt("iter_variant");
674         let tcx = cx.tcx();
675         let mut cx = cx;
676
677         for (i, &arg) in variant.args.iter().enumerate() {
678             cx = f(cx,
679                    adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
680                    arg.subst(tcx, substs));
681         }
682         return cx;
683     }
684
685     let mut cx = cx;
686     match ty::get(t).sty {
687       ty::ty_struct(..) => {
688           let repr = adt::represent_type(cx.ccx(), t);
689           expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
690               for (i, field_ty) in field_tys.iter().enumerate() {
691                   let llfld_a = adt::trans_field_ptr(cx, &*repr, av, discr, i);
692                   cx = f(cx, llfld_a, field_ty.mt.ty);
693               }
694           })
695       }
696       ty::ty_unboxed_closure(def_id) => {
697           let repr = adt::represent_type(cx.ccx(), t);
698           let upvars = ty::unboxed_closure_upvars(cx.tcx(), def_id);
699           for (i, upvar) in upvars.iter().enumerate() {
700               let llupvar = adt::trans_field_ptr(cx, &*repr, av, 0, i);
701               cx = f(cx, llupvar, upvar.ty);
702           }
703       }
704       ty::ty_vec(_, Some(n)) => {
705         let unit_ty = ty::sequence_element_type(cx.tcx(), t);
706         let (base, len) = tvec::get_fixed_base_and_byte_len(cx, av, unit_ty, n);
707         cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
708       }
709       ty::ty_tup(ref args) => {
710           let repr = adt::represent_type(cx.ccx(), t);
711           for (i, arg) in args.iter().enumerate() {
712               let llfld_a = adt::trans_field_ptr(cx, &*repr, av, 0, i);
713               cx = f(cx, llfld_a, *arg);
714           }
715       }
716       ty::ty_enum(tid, ref substs) => {
717           let fcx = cx.fcx;
718           let ccx = fcx.ccx;
719
720           let repr = adt::represent_type(ccx, t);
721           let variants = ty::enum_variants(ccx.tcx(), tid);
722           let n_variants = (*variants).len();
723
724           // NB: we must hit the discriminant first so that structural
725           // comparison know not to proceed when the discriminants differ.
726
727           match adt::trans_switch(cx, &*repr, av) {
728               (_match::single, None) => {
729                   cx = iter_variant(cx, &*repr, av, &**variants.get(0),
730                                     substs, f);
731               }
732               (_match::switch, Some(lldiscrim_a)) => {
733                   cx = f(cx, lldiscrim_a, ty::mk_int());
734                   let unr_cx = fcx.new_temp_block("enum-iter-unr");
735                   Unreachable(unr_cx);
736                   let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
737                                         n_variants);
738                   let next_cx = fcx.new_temp_block("enum-iter-next");
739
740                   for variant in (*variants).iter() {
741                       let variant_cx =
742                           fcx.new_temp_block(
743                               format!("enum-iter-variant-{}",
744                                       variant.disr_val.to_string().as_slice())
745                                      .as_slice());
746                       match adt::trans_case(cx, &*repr, variant.disr_val) {
747                           _match::single_result(r) => {
748                               AddCase(llswitch, r.val, variant_cx.llbb)
749                           }
750                           _ => ccx.sess().unimpl("value from adt::trans_case \
751                                                   in iter_structural_ty")
752                       }
753                       let variant_cx =
754                           iter_variant(variant_cx,
755                                        &*repr,
756                                        av,
757                                        &**variant,
758                                        substs,
759                                        |x,y,z| f(x,y,z));
760                       Br(variant_cx, next_cx.llbb);
761                   }
762                   cx = next_cx;
763               }
764               _ => ccx.sess().unimpl("value from adt::trans_switch \
765                                       in iter_structural_ty")
766           }
767       }
768       _ => cx.sess().unimpl("type in iter_structural_ty")
769     }
770     return cx;
771 }
772
773 pub fn cast_shift_expr_rhs<'a>(
774                            cx: &'a Block<'a>,
775                            op: ast::BinOp,
776                            lhs: ValueRef,
777                            rhs: ValueRef)
778                            -> ValueRef {
779     cast_shift_rhs(op, lhs, rhs,
780                    |a,b| Trunc(cx, a, b),
781                    |a,b| ZExt(cx, a, b))
782 }
783
784 pub fn cast_shift_const_rhs(op: ast::BinOp,
785                             lhs: ValueRef, rhs: ValueRef) -> ValueRef {
786     cast_shift_rhs(op, lhs, rhs,
787                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
788                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
789 }
790
791 pub fn cast_shift_rhs(op: ast::BinOp,
792                       lhs: ValueRef,
793                       rhs: ValueRef,
794                       trunc: |ValueRef, Type| -> ValueRef,
795                       zext: |ValueRef, Type| -> ValueRef)
796                       -> ValueRef {
797     // Shifts may have any size int on the rhs
798     unsafe {
799         if ast_util::is_shift_binop(op) {
800             let mut rhs_llty = val_ty(rhs);
801             let mut lhs_llty = val_ty(lhs);
802             if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
803             if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
804             let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
805             let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
806             if lhs_sz < rhs_sz {
807                 trunc(rhs, lhs_llty)
808             } else if lhs_sz > rhs_sz {
809                 // FIXME (#1877: If shifting by negative
810                 // values becomes not undefined then this is wrong.
811                 zext(rhs, lhs_llty)
812             } else {
813                 rhs
814             }
815         } else {
816             rhs
817         }
818     }
819 }
820
821 pub fn fail_if_zero_or_overflows<'a>(
822                     cx: &'a Block<'a>,
823                     span: Span,
824                     divrem: ast::BinOp,
825                     lhs: ValueRef,
826                     rhs: ValueRef,
827                     rhs_t: ty::t)
828                     -> &'a Block<'a> {
829     let (zero_text, overflow_text) = if divrem == ast::BiDiv {
830         ("attempted to divide by zero",
831          "attempted to divide with overflow")
832     } else {
833         ("attempted remainder with a divisor of zero",
834          "attempted remainder with overflow")
835     };
836     let (is_zero, is_signed) = match ty::get(rhs_t).sty {
837         ty::ty_int(t) => {
838             let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
839             (ICmp(cx, llvm::IntEQ, rhs, zero), true)
840         }
841         ty::ty_uint(t) => {
842             let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
843             (ICmp(cx, llvm::IntEQ, rhs, zero), false)
844         }
845         _ => {
846             cx.sess().bug(format!("fail-if-zero on unexpected type: {}",
847                                   ty_to_string(cx.tcx(), rhs_t)).as_slice());
848         }
849     };
850     let bcx = with_cond(cx, is_zero, |bcx| {
851         controlflow::trans_fail(bcx, span, InternedString::new(zero_text))
852     });
853
854     // To quote LLVM's documentation for the sdiv instruction:
855     //
856     //      Division by zero leads to undefined behavior. Overflow also leads
857     //      to undefined behavior; this is a rare case, but can occur, for
858     //      example, by doing a 32-bit division of -2147483648 by -1.
859     //
860     // In order to avoid undefined behavior, we perform runtime checks for
861     // signed division/remainder which would trigger overflow. For unsigned
862     // integers, no action beyond checking for zero need be taken.
863     if is_signed {
864         let (llty, min) = match ty::get(rhs_t).sty {
865             ty::ty_int(t) => {
866                 let llty = Type::int_from_ty(cx.ccx(), t);
867                 let min = match t {
868                     ast::TyI if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
869                     ast::TyI => i64::MIN as u64,
870                     ast::TyI8 => i8::MIN as u64,
871                     ast::TyI16 => i16::MIN as u64,
872                     ast::TyI32 => i32::MIN as u64,
873                     ast::TyI64 => i64::MIN as u64,
874                 };
875                 (llty, min)
876             }
877             _ => unreachable!(),
878         };
879         let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
880                              C_integral(llty, -1, false));
881         with_cond(bcx, minus_one, |bcx| {
882             let is_min = ICmp(bcx, llvm::IntEQ, lhs,
883                               C_integral(llty, min, true));
884             with_cond(bcx, is_min, |bcx| {
885                 controlflow::trans_fail(bcx, span,
886                                         InternedString::new(overflow_text))
887             })
888         })
889     } else {
890         bcx
891     }
892 }
893
894 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
895     let name = csearch::get_symbol(&ccx.sess().cstore, did);
896     match ty::get(t).sty {
897         ty::ty_bare_fn(ref fn_ty) => {
898             match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
899                                        ccx.sess().targ_cfg.arch) {
900                 Some(Rust) | Some(RustCall) => {
901                     get_extern_rust_fn(ccx, t, name.as_slice(), did)
902                 }
903                 Some(RustIntrinsic) => {
904                     ccx.sess().bug("unexpected intrinsic in trans_external_path")
905                 }
906                 Some(..) | None => {
907                     foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
908                                                       name.as_slice(), None)
909                 }
910             }
911         }
912         ty::ty_closure(_) => {
913             get_extern_rust_fn(ccx, t, name.as_slice(), did)
914         }
915         _ => {
916             let llty = type_of(ccx, t);
917             get_extern_const(&mut *ccx.externs.borrow_mut(),
918                              ccx.llmod,
919                              name.as_slice(),
920                              llty)
921         }
922     }
923 }
924
925 pub fn invoke<'a>(
926               bcx: &'a Block<'a>,
927               llfn: ValueRef,
928               llargs: Vec<ValueRef> ,
929               fn_ty: ty::t,
930               call_info: Option<NodeInfo>)
931               -> (ValueRef, &'a Block<'a>) {
932     let _icx = push_ctxt("invoke_");
933     if bcx.unreachable.get() {
934         return (C_null(Type::i8(bcx.ccx())), bcx);
935     }
936
937     let attributes = get_fn_llvm_attributes(bcx.ccx(), fn_ty);
938
939     match bcx.opt_node_id {
940         None => {
941             debug!("invoke at ???");
942         }
943         Some(id) => {
944             debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
945         }
946     }
947
948     if need_invoke(bcx) {
949         debug!("invoking {} at {}", llfn, bcx.llbb);
950         for &llarg in llargs.iter() {
951             debug!("arg: {}", llarg);
952         }
953         let normal_bcx = bcx.fcx.new_temp_block("normal-return");
954         let landing_pad = bcx.fcx.get_landing_pad();
955
956         match call_info {
957             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
958             None => debuginfo::clear_source_location(bcx.fcx)
959         };
960
961         let llresult = Invoke(bcx,
962                               llfn,
963                               llargs.as_slice(),
964                               normal_bcx.llbb,
965                               landing_pad,
966                               attributes.as_slice());
967         return (llresult, normal_bcx);
968     } else {
969         debug!("calling {} at {}", llfn, bcx.llbb);
970         for &llarg in llargs.iter() {
971             debug!("arg: {}", llarg);
972         }
973
974         match call_info {
975             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
976             None => debuginfo::clear_source_location(bcx.fcx)
977         };
978
979         let llresult = Call(bcx, llfn, llargs.as_slice(), attributes.as_slice());
980         return (llresult, bcx);
981     }
982 }
983
984 pub fn need_invoke(bcx: &Block) -> bool {
985     if bcx.sess().no_landing_pads() {
986         return false;
987     }
988
989     // Avoid using invoke if we are already inside a landing pad.
990     if bcx.is_lpad {
991         return false;
992     }
993
994     bcx.fcx.needs_invoke()
995 }
996
997 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
998     let _icx = push_ctxt("load_if_immediate");
999     if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
1000     return v;
1001 }
1002
1003 pub fn load_ty(cx: &Block, ptr: ValueRef, t: ty::t) -> ValueRef {
1004     /*!
1005      * Helper for loading values from memory. Does the necessary conversion if
1006      * the in-memory type differs from the type used for SSA values. Also
1007      * handles various special cases where the type gives us better information
1008      * about what we are loading.
1009      */
1010     if type_is_zero_size(cx.ccx(), t) {
1011         C_undef(type_of::type_of(cx.ccx(), t))
1012     } else if ty::type_is_bool(t) {
1013         Trunc(cx, LoadRangeAssert(cx, ptr, 0, 2, llvm::False), Type::i1(cx.ccx()))
1014     } else if ty::type_is_char(t) {
1015         // a char is a unicode codepoint, and so takes values from 0
1016         // to 0x10FFFF inclusive only.
1017         LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
1018     } else {
1019         Load(cx, ptr)
1020     }
1021 }
1022
1023 pub fn store_ty(cx: &Block, v: ValueRef, dst: ValueRef, t: ty::t) {
1024     /*!
1025      * Helper for storing values in memory. Does the necessary conversion if
1026      * the in-memory type differs from the type used for SSA values.
1027      */
1028     if ty::type_is_bool(t) {
1029         Store(cx, ZExt(cx, v, Type::i8(cx.ccx())), dst);
1030     } else {
1031         Store(cx, v, dst);
1032     };
1033 }
1034
1035 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
1036     match local.pat.node {
1037         ast::PatWild => true, _ => false
1038     }
1039 }
1040
1041 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
1042                   -> &'a Block<'a> {
1043     debug!("init_local(bcx={}, local.id={:?})", bcx.to_str(), local.id);
1044     let _indenter = indenter();
1045     let _icx = push_ctxt("init_local");
1046     _match::store_local(bcx, local)
1047 }
1048
1049 pub fn raw_block<'a>(
1050                  fcx: &'a FunctionContext<'a>,
1051                  is_lpad: bool,
1052                  llbb: BasicBlockRef)
1053                  -> &'a Block<'a> {
1054     Block::new(llbb, is_lpad, None, fcx)
1055 }
1056
1057 pub fn with_cond<'a>(
1058                  bcx: &'a Block<'a>,
1059                  val: ValueRef,
1060                  f: |&'a Block<'a>| -> &'a Block<'a>)
1061                  -> &'a Block<'a> {
1062     let _icx = push_ctxt("with_cond");
1063     let fcx = bcx.fcx;
1064     let next_cx = fcx.new_temp_block("next");
1065     let cond_cx = fcx.new_temp_block("cond");
1066     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1067     let after_cx = f(cond_cx);
1068     if !after_cx.terminated.get() {
1069         Br(after_cx, next_cx.llbb);
1070     }
1071     next_cx
1072 }
1073
1074 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1075     let _icx = push_ctxt("call_memcpy");
1076     let ccx = cx.ccx();
1077     let key = match ccx.sess().targ_cfg.arch {
1078         X86 | Arm | Mips | Mipsel => "llvm.memcpy.p0i8.p0i8.i32",
1079         X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1080     };
1081     let memcpy = ccx.get_intrinsic(&key);
1082     let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1083     let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1084     let size = IntCast(cx, n_bytes, ccx.int_type);
1085     let align = C_i32(ccx, align as i32);
1086     let volatile = C_bool(ccx, false);
1087     Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1088 }
1089
1090 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1091     let _icx = push_ctxt("memcpy_ty");
1092     let ccx = bcx.ccx();
1093     if ty::type_is_structural(t) {
1094         let llty = type_of::type_of(ccx, t);
1095         let llsz = llsize_of(ccx, llty);
1096         let llalign = llalign_of_min(ccx, llty);
1097         call_memcpy(bcx, dst, src, llsz, llalign as u32);
1098     } else {
1099         Store(bcx, Load(bcx, src), dst);
1100     }
1101 }
1102
1103 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1104     if cx.unreachable.get() { return; }
1105     let _icx = push_ctxt("zero_mem");
1106     let bcx = cx;
1107     let ccx = cx.ccx();
1108     let llty = type_of::type_of(ccx, t);
1109     memzero(&B(bcx), llptr, llty);
1110 }
1111
1112 // Always use this function instead of storing a zero constant to the memory
1113 // in question. If you store a zero constant, LLVM will drown in vreg
1114 // allocation for large data structures, and the generated code will be
1115 // awful. (A telltale sign of this is large quantities of
1116 // `mov [byte ptr foo],0` in the generated code.)
1117 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1118     let _icx = push_ctxt("memzero");
1119     let ccx = b.ccx;
1120
1121     let intrinsic_key = match ccx.sess().targ_cfg.arch {
1122         X86 | Arm | Mips | Mipsel => "llvm.memset.p0i8.i32",
1123         X86_64 => "llvm.memset.p0i8.i64"
1124     };
1125
1126     let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1127     let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1128     let llzeroval = C_u8(ccx, 0);
1129     let size = machine::llsize_of(ccx, ty);
1130     let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1131     let volatile = C_bool(ccx, false);
1132     b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1133 }
1134
1135 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1136     let _icx = push_ctxt("alloc_ty");
1137     let ccx = bcx.ccx();
1138     let ty = type_of::type_of(ccx, t);
1139     assert!(!ty::type_has_params(t));
1140     let val = alloca(bcx, ty, name);
1141     return val;
1142 }
1143
1144 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1145     alloca_maybe_zeroed(cx, ty, name, false)
1146 }
1147
1148 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1149     let _icx = push_ctxt("alloca");
1150     if cx.unreachable.get() {
1151         unsafe {
1152             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1153         }
1154     }
1155     debuginfo::clear_source_location(cx.fcx);
1156     let p = Alloca(cx, ty, name);
1157     if zero {
1158         let b = cx.fcx.ccx.builder();
1159         b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1160         memzero(&b, p, ty);
1161     }
1162     p
1163 }
1164
1165 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1166     let _icx = push_ctxt("arrayalloca");
1167     if cx.unreachable.get() {
1168         unsafe {
1169             return llvm::LLVMGetUndef(ty.to_ref());
1170         }
1171     }
1172     debuginfo::clear_source_location(cx.fcx);
1173     return ArrayAlloca(cx, ty, v);
1174 }
1175
1176 // Creates and returns space for, or returns the argument representing, the
1177 // slot where the return value of the function must go.
1178 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1179                            -> ValueRef {
1180     if type_of::return_uses_outptr(fcx.ccx, output_type) {
1181         get_param(fcx.llfn, 0)
1182     } else {
1183         let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1184         AllocaFcx(fcx, lloutputtype, "__make_return_pointer")
1185     }
1186 }
1187
1188 // NB: must keep 4 fns in sync:
1189 //
1190 //  - type_of_fn
1191 //  - create_datums_for_fn_args.
1192 //  - new_fn_ctxt
1193 //  - trans_args
1194 //
1195 // Be warned! You must call `init_function` before doing anything with the
1196 // returned function context.
1197 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1198                        llfndecl: ValueRef,
1199                        id: ast::NodeId,
1200                        has_env: bool,
1201                        output_type: ty::t,
1202                        param_substs: &'a param_substs,
1203                        sp: Option<Span>,
1204                        block_arena: &'a TypedArena<Block<'a>>)
1205                        -> FunctionContext<'a> {
1206     param_substs.validate();
1207
1208     debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1209            if id == -1 {
1210                "".to_string()
1211            } else {
1212                ccx.tcx.map.path_to_string(id).to_string()
1213            },
1214            id, param_substs.repr(ccx.tcx()));
1215
1216     let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1217     let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1218     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1219
1220     let mut fcx = FunctionContext {
1221           llfn: llfndecl,
1222           llenv: None,
1223           llretptr: Cell::new(None),
1224           alloca_insert_pt: Cell::new(None),
1225           llreturn: Cell::new(None),
1226           personality: Cell::new(None),
1227           caller_expects_out_pointer: uses_outptr,
1228           llargs: RefCell::new(NodeMap::new()),
1229           lllocals: RefCell::new(NodeMap::new()),
1230           llupvars: RefCell::new(NodeMap::new()),
1231           id: id,
1232           param_substs: param_substs,
1233           span: sp,
1234           block_arena: block_arena,
1235           ccx: ccx,
1236           debug_context: debug_context,
1237           scopes: RefCell::new(Vec::new())
1238     };
1239
1240     if has_env {
1241         fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1242     }
1243
1244     fcx
1245 }
1246
1247 /// Performs setup on a newly created function, creating the entry scope block
1248 /// and allocating space for the return pointer.
1249 pub fn init_function<'a>(fcx: &'a FunctionContext<'a>,
1250                          skip_retptr: bool,
1251                          output_type: ty::t) -> &'a Block<'a> {
1252     let entry_bcx = fcx.new_temp_block("entry-block");
1253
1254     // Use a dummy instruction as the insertion point for all allocas.
1255     // This is later removed in FunctionContext::cleanup.
1256     fcx.alloca_insert_pt.set(Some(unsafe {
1257         Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1258         llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1259     }));
1260
1261     // This shouldn't need to recompute the return type,
1262     // as new_fn_ctxt did it already.
1263     let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1264
1265     if !return_type_is_void(fcx.ccx, substd_output_type) {
1266         // If the function returns nil/bot, there is no real return
1267         // value, so do not set `llretptr`.
1268         if !skip_retptr || fcx.caller_expects_out_pointer {
1269             // Otherwise, we normally allocate the llretptr, unless we
1270             // have been instructed to skip it for immediate return
1271             // values.
1272             fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1273         }
1274     }
1275
1276     entry_bcx
1277 }
1278
1279 // NB: must keep 4 fns in sync:
1280 //
1281 //  - type_of_fn
1282 //  - create_datums_for_fn_args.
1283 //  - new_fn_ctxt
1284 //  - trans_args
1285
1286 pub fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1287     use middle::trans::datum::{ByRef, ByValue};
1288
1289     datum::Rvalue {
1290         mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1291     }
1292 }
1293
1294 // work around bizarre resolve errors
1295 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1296 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1297
1298 // create_datums_for_fn_args: creates rvalue datums for each of the
1299 // incoming function arguments. These will later be stored into
1300 // appropriate lvalue datums.
1301 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1302                                  arg_tys: &[ty::t])
1303                                  -> Vec<RvalueDatum> {
1304     let _icx = push_ctxt("create_datums_for_fn_args");
1305
1306     // Return an array wrapping the ValueRefs that we get from `get_param` for
1307     // each argument into datums.
1308     arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1309         let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1310         datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1311     }).collect()
1312 }
1313
1314 /// Creates rvalue datums for each of the incoming function arguments and
1315 /// tuples the arguments. These will later be stored into appropriate lvalue
1316 /// datums.
1317 fn create_datums_for_fn_args_under_call_abi<
1318         'a>(
1319         mut bcx: &'a Block<'a>,
1320         arg_scope: cleanup::CustomScopeIndex,
1321         arg_tys: &[ty::t])
1322         -> Vec<RvalueDatum> {
1323     let mut result = Vec::new();
1324     for (i, &arg_ty) in arg_tys.iter().enumerate() {
1325         if i < arg_tys.len() - 1 {
1326             // Regular argument.
1327             let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1328             result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1329                                                                   arg_ty)));
1330             continue
1331         }
1332
1333         // This is the last argument. Tuple it.
1334         match ty::get(arg_ty).sty {
1335             ty::ty_tup(ref tupled_arg_tys) => {
1336                 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1337                 let tuple =
1338                     unpack_datum!(bcx,
1339                                   datum::lvalue_scratch_datum(bcx,
1340                                                               arg_ty,
1341                                                               "tupled_args",
1342                                                               false,
1343                                                               tuple_args_scope_id,
1344                                                               (),
1345                                                               |(),
1346                                                                mut bcx,
1347                                                                llval| {
1348                         for (j, &tupled_arg_ty) in
1349                                     tupled_arg_tys.iter().enumerate() {
1350                             let llarg =
1351                                 get_param(bcx.fcx.llfn,
1352                                           bcx.fcx.arg_pos(i + j) as c_uint);
1353                             let lldest = GEPi(bcx, llval, [0, j]);
1354                             let datum = datum::Datum::new(
1355                                 llarg,
1356                                 tupled_arg_ty,
1357                                 arg_kind(bcx.fcx, tupled_arg_ty));
1358                             bcx = datum.store_to(bcx, lldest);
1359                         }
1360                         bcx
1361                     }));
1362                 let tuple = unpack_datum!(bcx,
1363                                           tuple.to_expr_datum()
1364                                                .to_rvalue_datum(bcx,
1365                                                                 "argtuple"));
1366                 result.push(tuple);
1367             }
1368             ty::ty_nil => {
1369                 let mode = datum::Rvalue::new(datum::ByValue);
1370                 result.push(datum::Datum::new(C_nil(bcx.ccx()),
1371                                               ty::mk_nil(),
1372                                               mode))
1373             }
1374             _ => {
1375                 bcx.tcx().sess.bug("last argument of a function with \
1376                                     `rust-call` ABI isn't a tuple?!")
1377             }
1378         };
1379
1380     }
1381
1382     result
1383 }
1384
1385 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1386                             arg_scope: cleanup::CustomScopeIndex,
1387                             bcx: &'a Block<'a>,
1388                             args: &[ast::Arg],
1389                             arg_datums: Vec<RvalueDatum> )
1390                             -> &'a Block<'a> {
1391     debug!("copy_args_to_allocas");
1392
1393     let _icx = push_ctxt("copy_args_to_allocas");
1394     let mut bcx = bcx;
1395
1396     let arg_scope_id = cleanup::CustomScope(arg_scope);
1397
1398     for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1399         // For certain mode/type combinations, the raw llarg values are passed
1400         // by value.  However, within the fn body itself, we want to always
1401         // have all locals and arguments be by-ref so that we can cancel the
1402         // cleanup and for better interaction with LLVM's debug info.  So, if
1403         // the argument would be passed by value, we store it into an alloca.
1404         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1405         // the event it's not truly needed.
1406
1407         bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1408
1409         if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1410             debuginfo::create_argument_metadata(bcx, &args[i]);
1411         }
1412     }
1413
1414     bcx
1415 }
1416
1417 fn copy_unboxed_closure_args_to_allocas<'a>(
1418                                         mut bcx: &'a Block<'a>,
1419                                         arg_scope: cleanup::CustomScopeIndex,
1420                                         args: &[ast::Arg],
1421                                         arg_datums: Vec<RvalueDatum>,
1422                                         monomorphized_arg_types: &[ty::t])
1423                                         -> &'a Block<'a> {
1424     let _icx = push_ctxt("copy_unboxed_closure_args_to_allocas");
1425     let arg_scope_id = cleanup::CustomScope(arg_scope);
1426
1427     assert_eq!(arg_datums.len(), 1);
1428
1429     let arg_datum = arg_datums.move_iter().next().unwrap();
1430
1431     // Untuple the rest of the arguments.
1432     let tuple_datum =
1433         unpack_datum!(bcx,
1434                       arg_datum.to_lvalue_datum_in_scope(bcx,
1435                                                          "argtuple",
1436                                                          arg_scope_id));
1437     let empty = Vec::new();
1438     let untupled_arg_types = match ty::get(monomorphized_arg_types[0]).sty {
1439         ty::ty_tup(ref types) => types.as_slice(),
1440         ty::ty_nil => empty.as_slice(),
1441         _ => {
1442             bcx.tcx().sess.span_bug(args[0].pat.span,
1443                                     "first arg to `rust-call` ABI function \
1444                                      wasn't a tuple?!")
1445         }
1446     };
1447     for j in range(0, args.len()) {
1448         let tuple_element_type = untupled_arg_types[j];
1449         let tuple_element_datum =
1450             tuple_datum.get_element(tuple_element_type,
1451                                     |llval| GEPi(bcx, llval, [0, j]));
1452         let tuple_element_datum = tuple_element_datum.to_expr_datum();
1453         let tuple_element_datum =
1454             unpack_datum!(bcx,
1455                           tuple_element_datum.to_rvalue_datum(bcx,
1456                                                               "arg"));
1457         bcx = _match::store_arg(bcx,
1458                                 args[j].pat,
1459                                 tuple_element_datum,
1460                                 arg_scope_id);
1461
1462         if bcx.fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1463             debuginfo::create_argument_metadata(bcx, &args[j]);
1464         }
1465     }
1466
1467     bcx
1468 }
1469
1470 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1471 // and builds the return block.
1472 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1473                      last_bcx: &'a Block<'a>,
1474                      retty: ty::t) {
1475     let _icx = push_ctxt("finish_fn");
1476
1477     // This shouldn't need to recompute the return type,
1478     // as new_fn_ctxt did it already.
1479     let substd_retty = retty.substp(fcx.ccx.tcx(), fcx.param_substs);
1480
1481     let ret_cx = match fcx.llreturn.get() {
1482         Some(llreturn) => {
1483             if !last_bcx.terminated.get() {
1484                 Br(last_bcx, llreturn);
1485             }
1486             raw_block(fcx, false, llreturn)
1487         }
1488         None => last_bcx
1489     };
1490     build_return_block(fcx, ret_cx, substd_retty);
1491     debuginfo::clear_source_location(fcx);
1492     fcx.cleanup();
1493 }
1494
1495 // Builds the return block for a function.
1496 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block, retty: ty::t) {
1497     // Return the value if this function immediate; otherwise, return void.
1498     if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1499         return RetVoid(ret_cx);
1500     }
1501
1502     let retptr = Value(fcx.llretptr.get().unwrap());
1503     let retval = match retptr.get_dominating_store(ret_cx) {
1504         // If there's only a single store to the ret slot, we can directly return
1505         // the value that was stored and omit the store and the alloca
1506         Some(s) => {
1507             let retval = s.get_operand(0).unwrap().get();
1508             s.erase_from_parent();
1509
1510             if retptr.has_no_uses() {
1511                 retptr.erase_from_parent();
1512             }
1513
1514             if ty::type_is_bool(retty) {
1515                 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1516             } else {
1517                 retval
1518             }
1519         }
1520         // Otherwise, load the return value from the ret slot
1521         None => load_ty(ret_cx, fcx.llretptr.get().unwrap(), retty)
1522     };
1523
1524     Ret(ret_cx, retval);
1525 }
1526
1527 #[deriving(Clone, Eq, PartialEq)]
1528 pub enum IsUnboxedClosureFlag {
1529     NotUnboxedClosure,
1530     IsUnboxedClosure,
1531 }
1532
1533 // trans_closure: Builds an LLVM function out of a source function.
1534 // If the function closes over its environment a closure will be
1535 // returned.
1536 pub fn trans_closure(ccx: &CrateContext,
1537                      decl: &ast::FnDecl,
1538                      body: &ast::Block,
1539                      llfndecl: ValueRef,
1540                      param_substs: &param_substs,
1541                      id: ast::NodeId,
1542                      _attributes: &[ast::Attribute],
1543                      arg_types: Vec<ty::t>,
1544                      output_type: ty::t,
1545                      abi: Abi,
1546                      has_env: bool,
1547                      is_unboxed_closure: IsUnboxedClosureFlag,
1548                      maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1549     ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1550
1551     let _icx = push_ctxt("trans_closure");
1552     set_uwtable(llfndecl);
1553
1554     debug!("trans_closure(..., param_substs={})",
1555            param_substs.repr(ccx.tcx()));
1556
1557     let arena = TypedArena::new();
1558     let fcx = new_fn_ctxt(ccx,
1559                           llfndecl,
1560                           id,
1561                           has_env,
1562                           output_type,
1563                           param_substs,
1564                           Some(body.span),
1565                           &arena);
1566     let mut bcx = init_function(&fcx, false, output_type);
1567
1568     // cleanup scope for the incoming arguments
1569     let arg_scope = fcx.push_custom_cleanup_scope();
1570
1571     let block_ty = node_id_type(bcx, body.id);
1572
1573     // Set up arguments to the function.
1574     let monomorphized_arg_types =
1575         arg_types.iter()
1576                  .map(|at| monomorphize_type(bcx, *at))
1577                  .collect::<Vec<_>>();
1578     for monomorphized_arg_type in monomorphized_arg_types.iter() {
1579         debug!("trans_closure: monomorphized_arg_type: {}",
1580                ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1581     }
1582     debug!("trans_closure: function lltype: {}",
1583            bcx.fcx.ccx.tn.val_to_string(bcx.fcx.llfn));
1584
1585     let arg_datums = if abi != RustCall {
1586         create_datums_for_fn_args(&fcx,
1587                                   monomorphized_arg_types.as_slice())
1588     } else {
1589         create_datums_for_fn_args_under_call_abi(
1590             bcx,
1591             arg_scope,
1592             monomorphized_arg_types.as_slice())
1593     };
1594
1595     bcx = match is_unboxed_closure {
1596         NotUnboxedClosure => {
1597             copy_args_to_allocas(&fcx,
1598                                  arg_scope,
1599                                  bcx,
1600                                  decl.inputs.as_slice(),
1601                                  arg_datums)
1602         }
1603         IsUnboxedClosure => {
1604             copy_unboxed_closure_args_to_allocas(
1605                 bcx,
1606                 arg_scope,
1607                 decl.inputs.as_slice(),
1608                 arg_datums,
1609                 monomorphized_arg_types.as_slice())
1610         }
1611     };
1612
1613     bcx = maybe_load_env(bcx);
1614
1615     // Up until here, IR instructions for this function have explicitly not been annotated with
1616     // source code location, so we don't step into call setup code. From here on, source location
1617     // emitting should be enabled.
1618     debuginfo::start_emitting_source_locations(&fcx);
1619
1620     let dest = match fcx.llretptr.get() {
1621         Some(e) => {expr::SaveIn(e)}
1622         None => {
1623             assert!(type_is_zero_size(bcx.ccx(), block_ty))
1624             expr::Ignore
1625         }
1626     };
1627
1628     // This call to trans_block is the place where we bridge between
1629     // translation calls that don't have a return value (trans_crate,
1630     // trans_mod, trans_item, et cetera) and those that do
1631     // (trans_block, trans_expr, et cetera).
1632     bcx = controlflow::trans_block(bcx, body, dest);
1633
1634     match fcx.llreturn.get() {
1635         Some(_) => {
1636             Br(bcx, fcx.return_exit_block());
1637             fcx.pop_custom_cleanup_scope(arg_scope);
1638         }
1639         None => {
1640             // Microoptimization writ large: avoid creating a separate
1641             // llreturn basic block
1642             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1643         }
1644     };
1645
1646     // Put return block after all other blocks.
1647     // This somewhat improves single-stepping experience in debugger.
1648     unsafe {
1649         let llreturn = fcx.llreturn.get();
1650         for &llreturn in llreturn.iter() {
1651             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1652         }
1653     }
1654
1655     // Insert the mandatory first few basic blocks before lltop.
1656     finish_fn(&fcx, bcx, output_type);
1657 }
1658
1659 // trans_fn: creates an LLVM function corresponding to a source language
1660 // function.
1661 pub fn trans_fn(ccx: &CrateContext,
1662                 decl: &ast::FnDecl,
1663                 body: &ast::Block,
1664                 llfndecl: ValueRef,
1665                 param_substs: &param_substs,
1666                 id: ast::NodeId,
1667                 attrs: &[ast::Attribute]) {
1668     let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_string(id).to_string());
1669     debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1670     let _icx = push_ctxt("trans_fn");
1671     let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1672     let arg_types = ty::ty_fn_args(fn_ty);
1673     let output_type = ty::ty_fn_ret(fn_ty);
1674     let abi = ty::ty_fn_abi(fn_ty);
1675     trans_closure(ccx,
1676                   decl,
1677                   body,
1678                   llfndecl,
1679                   param_substs,
1680                   id,
1681                   attrs,
1682                   arg_types,
1683                   output_type,
1684                   abi,
1685                   false,
1686                   NotUnboxedClosure,
1687                   |bcx| bcx);
1688 }
1689
1690 pub fn trans_enum_variant(ccx: &CrateContext,
1691                           _enum_id: ast::NodeId,
1692                           variant: &ast::Variant,
1693                           _args: &[ast::VariantArg],
1694                           disr: ty::Disr,
1695                           param_substs: &param_substs,
1696                           llfndecl: ValueRef) {
1697     let _icx = push_ctxt("trans_enum_variant");
1698
1699     trans_enum_variant_or_tuple_like_struct(
1700         ccx,
1701         variant.node.id,
1702         disr,
1703         param_substs,
1704         llfndecl);
1705 }
1706
1707 pub fn trans_tuple_struct(ccx: &CrateContext,
1708                           _fields: &[ast::StructField],
1709                           ctor_id: ast::NodeId,
1710                           param_substs: &param_substs,
1711                           llfndecl: ValueRef) {
1712     let _icx = push_ctxt("trans_tuple_struct");
1713
1714     trans_enum_variant_or_tuple_like_struct(
1715         ccx,
1716         ctor_id,
1717         0,
1718         param_substs,
1719         llfndecl);
1720 }
1721
1722 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1723                                            ctor_id: ast::NodeId,
1724                                            disr: ty::Disr,
1725                                            param_substs: &param_substs,
1726                                            llfndecl: ValueRef) {
1727     let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1728     let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
1729
1730     let result_ty = match ty::get(ctor_ty).sty {
1731         ty::ty_bare_fn(ref bft) => bft.sig.output,
1732         _ => ccx.sess().bug(
1733             format!("trans_enum_variant_or_tuple_like_struct: \
1734                      unexpected ctor return type {}",
1735                     ty_to_string(ccx.tcx(), ctor_ty)).as_slice())
1736     };
1737
1738     let arena = TypedArena::new();
1739     let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1740                           param_substs, None, &arena);
1741     let bcx = init_function(&fcx, false, result_ty);
1742
1743     let arg_tys = ty::ty_fn_args(ctor_ty);
1744
1745     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1746
1747     if !type_is_zero_size(fcx.ccx, result_ty) {
1748         let repr = adt::represent_type(ccx, result_ty);
1749         adt::trans_start_init(bcx, &*repr, fcx.llretptr.get().unwrap(), disr);
1750         for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1751             let lldestptr = adt::trans_field_ptr(bcx,
1752                                                  &*repr,
1753                                                  fcx.llretptr.get().unwrap(),
1754                                                  disr,
1755                                                  i);
1756             arg_datum.store_to(bcx, lldestptr);
1757         }
1758     }
1759
1760     finish_fn(&fcx, bcx, result_ty);
1761 }
1762
1763 fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1764                   sp: Span, id: ast::NodeId, vi: &[Rc<ty::VariantInfo>],
1765                   i: &mut uint) {
1766     for variant in enum_definition.variants.iter() {
1767         let disr_val = vi[*i].disr_val;
1768         *i += 1;
1769
1770         match variant.node.kind {
1771             ast::TupleVariantKind(ref args) if args.len() > 0 => {
1772                 let llfn = get_item_val(ccx, variant.node.id);
1773                 trans_enum_variant(ccx, id, &**variant, args.as_slice(),
1774                                    disr_val, &param_substs::empty(), llfn);
1775             }
1776             ast::TupleVariantKind(_) => {
1777                 // Nothing to do.
1778             }
1779             ast::StructVariantKind(struct_def) => {
1780                 trans_struct_def(ccx, struct_def);
1781             }
1782         }
1783     }
1784
1785     enum_variant_size_lint(ccx, enum_definition, sp, id);
1786 }
1787
1788 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
1789     let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
1790
1791     let levels = ccx.tcx.node_lint_levels.borrow();
1792     let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCE);
1793     let lvlsrc = match levels.find(&(id, lint_id)) {
1794         None | Some(&(lint::Allow, _)) => return,
1795         Some(&lvlsrc) => lvlsrc,
1796     };
1797
1798     let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
1799     match *avar {
1800         adt::General(_, ref variants) => {
1801             for var in variants.iter() {
1802                 let mut size = 0;
1803                 for field in var.fields.iter().skip(1) {
1804                     // skip the discriminant
1805                     size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
1806                 }
1807                 sizes.push(size);
1808             }
1809         },
1810         _ => { /* its size is either constant or unimportant */ }
1811     }
1812
1813     let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
1814         |(l, s, li), (idx, &size)|
1815             if size > l {
1816                 (size, l, idx)
1817             } else if size > s {
1818                 (l, size, li)
1819             } else {
1820                 (l, s, li)
1821             }
1822     );
1823
1824     // we only warn if the largest variant is at least thrice as large as
1825     // the second-largest.
1826     if largest > slargest * 3 && slargest > 0 {
1827         // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
1828         // pass for the latter already ran.
1829         lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCE,
1830                             lvlsrc, Some(sp),
1831                             format!("enum variant is more than three times larger \
1832                                      ({} bytes) than the next largest (ignoring padding)",
1833                                     largest).as_slice());
1834
1835         ccx.sess().span_note(enum_def.variants.get(largest_index).span,
1836                              "this variant is the largest");
1837     }
1838 }
1839
1840 pub struct TransItemVisitor<'a> {
1841     pub ccx: &'a CrateContext,
1842 }
1843
1844 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1845     fn visit_item(&mut self, i: &ast::Item, _:()) {
1846         trans_item(self.ccx, i);
1847     }
1848 }
1849
1850 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1851     let _icx = push_ctxt("trans_item");
1852     match item.node {
1853       ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
1854         if abi != Rust {
1855             let llfndecl = get_item_val(ccx, item.id);
1856             foreign::trans_rust_fn_with_foreign_abi(
1857                 ccx, &**decl, &**body, item.attrs.as_slice(), llfndecl, item.id);
1858         } else if !generics.is_type_parameterized() {
1859             let llfn = get_item_val(ccx, item.id);
1860             trans_fn(ccx,
1861                      &**decl,
1862                      &**body,
1863                      llfn,
1864                      &param_substs::empty(),
1865                      item.id,
1866                      item.attrs.as_slice());
1867         } else {
1868             // Be sure to travel more than just one layer deep to catch nested
1869             // items in blocks and such.
1870             let mut v = TransItemVisitor{ ccx: ccx };
1871             v.visit_block(&**body, ());
1872         }
1873       }
1874       ast::ItemImpl(ref generics, _, _, ref ms) => {
1875         meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1876       }
1877       ast::ItemMod(ref m) => {
1878         trans_mod(ccx, m);
1879       }
1880       ast::ItemEnum(ref enum_definition, ref generics) => {
1881         if !generics.is_type_parameterized() {
1882             let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1883             let mut i = 0;
1884             trans_enum_def(ccx, enum_definition, item.span, item.id, vi.as_slice(), &mut i);
1885         }
1886       }
1887       ast::ItemStatic(_, m, ref expr) => {
1888           // Recurse on the expression to catch items in blocks
1889           let mut v = TransItemVisitor{ ccx: ccx };
1890           v.visit_expr(&**expr, ());
1891           consts::trans_const(ccx, m, item.id);
1892           // Do static_assert checking. It can't really be done much earlier
1893           // because we need to get the value of the bool out of LLVM
1894           if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1895               if m == ast::MutMutable {
1896                   ccx.sess().span_fatal(expr.span,
1897                                         "cannot have static_assert on a mutable \
1898                                          static");
1899               }
1900
1901               let v = ccx.const_values.borrow().get_copy(&item.id);
1902               unsafe {
1903                   if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1904                       ccx.sess().span_fatal(expr.span, "static assertion failed");
1905                   }
1906               }
1907           }
1908       },
1909       ast::ItemForeignMod(ref foreign_mod) => {
1910         foreign::trans_foreign_mod(ccx, foreign_mod);
1911       }
1912       ast::ItemStruct(struct_def, ref generics) => {
1913         if !generics.is_type_parameterized() {
1914             trans_struct_def(ccx, struct_def);
1915         }
1916       }
1917       ast::ItemTrait(..) => {
1918         // Inside of this trait definition, we won't be actually translating any
1919         // functions, but the trait still needs to be walked. Otherwise default
1920         // methods with items will not get translated and will cause ICE's when
1921         // metadata time comes around.
1922         let mut v = TransItemVisitor{ ccx: ccx };
1923         visit::walk_item(&mut v, item, ());
1924       }
1925       _ => {/* fall through */ }
1926     }
1927 }
1928
1929 pub fn trans_struct_def(ccx: &CrateContext, struct_def: Gc<ast::StructDef>) {
1930     // If this is a tuple-like struct, translate the constructor.
1931     match struct_def.ctor_id {
1932         // We only need to translate a constructor if there are fields;
1933         // otherwise this is a unit-like struct.
1934         Some(ctor_id) if struct_def.fields.len() > 0 => {
1935             let llfndecl = get_item_val(ccx, ctor_id);
1936             trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1937                                ctor_id, &param_substs::empty(), llfndecl);
1938         }
1939         Some(_) | None => {}
1940     }
1941 }
1942
1943 // Translate a module. Doing this amounts to translating the items in the
1944 // module; there ends up being no artifact (aside from linkage names) of
1945 // separate modules in the compiled program.  That's because modules exist
1946 // only as a convenience for humans working with the code, to organize names
1947 // and control visibility.
1948 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1949     let _icx = push_ctxt("trans_mod");
1950     for item in m.items.iter() {
1951         trans_item(ccx, &**item);
1952     }
1953 }
1954
1955 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
1956                       llfn: ValueRef) {
1957     ccx.item_symbols.borrow_mut().insert(node_id, sym);
1958
1959     if !ccx.reachable.contains(&node_id) {
1960         llvm::SetLinkage(llfn, llvm::InternalLinkage);
1961     }
1962
1963     // The stack exhaustion lang item shouldn't have a split stack because
1964     // otherwise it would continue to be exhausted (bad), and both it and the
1965     // eh_personality functions need to be externally linkable.
1966     let def = ast_util::local_def(node_id);
1967     if ccx.tcx.lang_items.stack_exhausted() == Some(def) {
1968         unset_split_stack(llfn);
1969         llvm::SetLinkage(llfn, llvm::ExternalLinkage);
1970     }
1971     if ccx.tcx.lang_items.eh_personality() == Some(def) {
1972         llvm::SetLinkage(llfn, llvm::ExternalLinkage);
1973     }
1974
1975
1976     if is_entry_fn(ccx.sess(), node_id) {
1977         create_entry_wrapper(ccx, sp, llfn);
1978     }
1979 }
1980
1981 fn register_fn(ccx: &CrateContext,
1982                sp: Span,
1983                sym: String,
1984                node_id: ast::NodeId,
1985                node_type: ty::t)
1986                -> ValueRef {
1987     match ty::get(node_type).sty {
1988         ty::ty_bare_fn(ref f) => {
1989             assert!(f.abi == Rust || f.abi == RustCall);
1990         }
1991         _ => fail!("expected bare rust fn")
1992     };
1993
1994     let llfn = decl_rust_fn(ccx, node_type, sym.as_slice());
1995     finish_register_fn(ccx, sp, sym, node_id, llfn);
1996     llfn
1997 }
1998
1999 pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t)
2000                               -> Vec<(uint, u64)> {
2001     use middle::ty::{BrAnon, ReLateBound};
2002
2003     let (fn_sig, abi, has_env) = match ty::get(fn_ty).sty {
2004         ty::ty_closure(ref f) => (f.sig.clone(), f.abi, true),
2005         ty::ty_bare_fn(ref f) => (f.sig.clone(), f.abi, false),
2006         ty::ty_unboxed_closure(closure_did) => {
2007             let unboxed_closure_types = ccx.tcx
2008                                            .unboxed_closure_types
2009                                            .borrow();
2010             let function_type = unboxed_closure_types.get(&closure_did);
2011             (function_type.sig.clone(), RustCall, true)
2012         }
2013         _ => fail!("expected closure or function.")
2014     };
2015
2016     // These have an odd calling convention, so we skip them for now.
2017     //
2018     // FIXME(pcwalton): We don't have to skip them; just untuple the result.
2019     if abi == RustCall {
2020         return Vec::new()
2021     }
2022
2023     // Since index 0 is the return value of the llvm func, we start
2024     // at either 1 or 2 depending on whether there's an env slot or not
2025     let mut first_arg_offset = if has_env { 2 } else { 1 };
2026     let mut attrs = Vec::new();
2027     let ret_ty = fn_sig.output;
2028
2029     // A function pointer is called without the declaration
2030     // available, so we have to apply any attributes with ABI
2031     // implications directly to the call instruction. Right now,
2032     // the only attribute we need to worry about is `sret`.
2033     if type_of::return_uses_outptr(ccx, ret_ty) {
2034         attrs.push((1, llvm::StructRetAttribute as u64));
2035
2036         // The outptr can be noalias and nocapture because it's entirely
2037         // invisible to the program. We can also mark it as nonnull
2038         attrs.push((1, llvm::NoAliasAttribute as u64));
2039         attrs.push((1, llvm::NoCaptureAttribute as u64));
2040         attrs.push((1, llvm::NonNullAttribute as u64));
2041
2042         // Add one more since there's an outptr
2043         first_arg_offset += 1;
2044     } else {
2045         // The `noalias` attribute on the return value is useful to a
2046         // function ptr caller.
2047         match ty::get(ret_ty).sty {
2048             // `~` pointer return values never alias because ownership
2049             // is transferred
2050             ty::ty_uniq(it)  if match ty::get(it).sty {
2051                 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
2052             } => {}
2053             ty::ty_uniq(_) => {
2054                 attrs.push((llvm::ReturnIndex as uint, llvm::NoAliasAttribute as u64));
2055             }
2056             _ => {}
2057         }
2058
2059         // We can also mark the return value as `nonnull` in certain cases
2060         match ty::get(ret_ty).sty {
2061             // These are not really pointers but pairs, (pointer, len)
2062             ty::ty_uniq(it) |
2063             ty::ty_rptr(_, ty::mt { ty: it, .. }) if match ty::get(it).sty {
2064                 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
2065             } => {}
2066             ty::ty_uniq(_) | ty::ty_rptr(_, _) => {
2067                 attrs.push((llvm::ReturnIndex as uint, llvm::NonNullAttribute as u64));
2068             }
2069             _ => {}
2070         }
2071
2072         match ty::get(ret_ty).sty {
2073             ty::ty_bool => {
2074                 attrs.push((llvm::ReturnIndex as uint, llvm::ZExtAttribute as u64));
2075             }
2076             _ => {}
2077         }
2078     }
2079
2080     for (idx, &t) in fn_sig.inputs.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
2081         match ty::get(t).sty {
2082             // this needs to be first to prevent fat pointers from falling through
2083             _ if !type_is_immediate(ccx, t) => {
2084                 // For non-immediate arguments the callee gets its own copy of
2085                 // the value on the stack, so there are no aliases. It's also
2086                 // program-invisible so can't possibly capture
2087                 attrs.push((idx, llvm::NoAliasAttribute as u64));
2088                 attrs.push((idx, llvm::NoCaptureAttribute as u64));
2089                 attrs.push((idx, llvm::NonNullAttribute as u64));
2090             }
2091             ty::ty_bool => {
2092                 attrs.push((idx, llvm::ZExtAttribute as u64));
2093             }
2094             // `~` pointer parameters never alias because ownership is transferred
2095             ty::ty_uniq(_) => {
2096                 attrs.push((idx, llvm::NoAliasAttribute as u64));
2097                 attrs.push((idx, llvm::NonNullAttribute as u64));
2098             }
2099             // `&mut` pointer parameters never alias other parameters, or mutable global data
2100             ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable => {
2101                 attrs.push((idx, llvm::NoAliasAttribute as u64));
2102                 attrs.push((idx, llvm::NonNullAttribute as u64));
2103                 match b {
2104                     ReLateBound(_, BrAnon(_)) => {
2105                         attrs.push((idx, llvm::NoCaptureAttribute as u64));
2106                     }
2107                     _ => {}
2108                 }
2109             }
2110             // When a reference in an argument has no named lifetime, it's impossible for that
2111             // reference to escape this function (returned or stored beyond the call by a closure).
2112             ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
2113                 attrs.push((idx, llvm::NoCaptureAttribute as u64));
2114                 attrs.push((idx, llvm::NonNullAttribute as u64));
2115             }
2116             // & pointer parameters are never null
2117             ty::ty_rptr(_, _) => {
2118                 attrs.push((idx, llvm::NonNullAttribute as u64));
2119             }
2120             _ => ()
2121         }
2122     }
2123
2124     attrs
2125 }
2126
2127 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2128 pub fn register_fn_llvmty(ccx: &CrateContext,
2129                           sp: Span,
2130                           sym: String,
2131                           node_id: ast::NodeId,
2132                           cc: llvm::CallConv,
2133                           llfty: Type) -> ValueRef {
2134     debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2135
2136     let llfn = decl_fn(ccx, sym.as_slice(), cc, llfty, ty::mk_nil());
2137     finish_register_fn(ccx, sp, sym, node_id, llfn);
2138     llfn
2139 }
2140
2141 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2142     match *sess.entry_fn.borrow() {
2143         Some((entry_id, _)) => node_id == entry_id,
2144         None => false
2145     }
2146 }
2147
2148 // Create a _rust_main(args: ~[str]) function which will be called from the
2149 // runtime rust_start function
2150 pub fn create_entry_wrapper(ccx: &CrateContext,
2151                            _sp: Span,
2152                            main_llfn: ValueRef) {
2153     let et = ccx.sess().entry_type.get().unwrap();
2154     match et {
2155         config::EntryMain => {
2156             create_entry_fn(ccx, main_llfn, true);
2157         }
2158         config::EntryStart => create_entry_fn(ccx, main_llfn, false),
2159         config::EntryNone => {}    // Do nothing.
2160     }
2161
2162     fn create_entry_fn(ccx: &CrateContext,
2163                        rust_main: ValueRef,
2164                        use_start_lang_item: bool) {
2165         let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
2166                                &ccx.int_type);
2167
2168         let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil());
2169         let llbb = "top".with_c_str(|buf| {
2170             unsafe {
2171                 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2172             }
2173         });
2174         let bld = ccx.builder.b;
2175         unsafe {
2176             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2177
2178             let (start_fn, args) = if use_start_lang_item {
2179                 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2180                     Ok(id) => id,
2181                     Err(s) => { ccx.sess().fatal(s.as_slice()); }
2182                 };
2183                 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2184                     get_item_val(ccx, start_def_id.node)
2185                 } else {
2186                     let start_fn_type = csearch::get_type(ccx.tcx(),
2187                                                           start_def_id).ty;
2188                     trans_external_path(ccx, start_def_id, start_fn_type)
2189                 };
2190
2191                 let args = {
2192                     let opaque_rust_main = "rust_main".with_c_str(|buf| {
2193                         llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
2194                     });
2195
2196                     vec!(
2197                         opaque_rust_main,
2198                         get_param(llfn, 0),
2199                         get_param(llfn, 1)
2200                      )
2201                 };
2202                 (start_fn, args)
2203             } else {
2204                 debug!("using user-defined start fn");
2205                 let args = vec!(
2206                     get_param(llfn, 0 as c_uint),
2207                     get_param(llfn, 1 as c_uint)
2208                 );
2209
2210                 (rust_main, args)
2211             };
2212
2213             let result = llvm::LLVMBuildCall(bld,
2214                                              start_fn,
2215                                              args.as_ptr(),
2216                                              args.len() as c_uint,
2217                                              noname());
2218
2219             llvm::LLVMBuildRet(bld, result);
2220         }
2221     }
2222 }
2223
2224 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
2225                  ty: ty::t, attrs: &[ast::Attribute]) -> String {
2226     match attr::first_attr_value_str_by_name(attrs, "export_name") {
2227         // Use provided name
2228         Some(name) => name.get().to_string(),
2229
2230         _ => ccx.tcx.map.with_path(id, |mut path| {
2231             if attr::contains_name(attrs, "no_mangle") {
2232                 // Don't mangle
2233                 path.last().unwrap().to_string()
2234             } else {
2235                 match weak_lang_items::link_name(attrs) {
2236                     Some(name) => name.get().to_string(),
2237                     None => {
2238                         // Usual name mangling
2239                         mangle_exported_name(ccx, path, ty, id)
2240                     }
2241                 }
2242             }
2243         })
2244     }
2245 }
2246
2247 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2248     debug!("get_item_val(id=`{:?}`)", id);
2249
2250     match ccx.item_vals.borrow().find_copy(&id) {
2251         Some(v) => return v,
2252         None => {}
2253     }
2254
2255     let mut foreign = false;
2256     let item = ccx.tcx.map.get(id);
2257     let val = match item {
2258         ast_map::NodeItem(i) => {
2259             let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2260             let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
2261
2262             let v = match i.node {
2263                 ast::ItemStatic(_, mutbl, ref expr) => {
2264                     // If this static came from an external crate, then
2265                     // we need to get the symbol from csearch instead of
2266                     // using the current crate's name/version
2267                     // information in the hash of the symbol
2268                     debug!("making {}", sym);
2269                     let (sym, is_local) = {
2270                         match ccx.external_srcs.borrow().find(&i.id) {
2271                             Some(&did) => {
2272                                 debug!("but found in other crate...");
2273                                 (csearch::get_symbol(&ccx.sess().cstore,
2274                                                      did), false)
2275                             }
2276                             None => (sym, true)
2277                         }
2278                     };
2279
2280                     // We need the translated value here, because for enums the
2281                     // LLVM type is not fully determined by the Rust type.
2282                     let (v, inlineable) = consts::const_expr(ccx, &**expr, is_local);
2283                     ccx.const_values.borrow_mut().insert(id, v);
2284                     let mut inlineable = inlineable;
2285
2286                     unsafe {
2287                         let llty = llvm::LLVMTypeOf(v);
2288                         let g = sym.as_slice().with_c_str(|buf| {
2289                             llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2290                         });
2291
2292                         if !ccx.reachable.contains(&id) {
2293                             llvm::SetLinkage(g, llvm::InternalLinkage);
2294                         }
2295
2296                         // Apply the `unnamed_addr` attribute if
2297                         // requested
2298                         if !ast_util::static_has_significant_address(
2299                                 mutbl,
2300                                 i.attrs.as_slice()) {
2301                             llvm::SetUnnamedAddr(g, true);
2302
2303                             // This is a curious case where we must make
2304                             // all of these statics inlineable. If a
2305                             // global is not tagged as `#[inline(never)]`,
2306                             // then LLVM won't coalesce globals unless they
2307                             // have an internal linkage type. This means that
2308                             // external crates cannot use this global.
2309                             // This is a problem for things like inner
2310                             // statics in generic functions, because the
2311                             // function will be inlined into another
2312                             // crate and then attempt to link to the
2313                             // static in the original crate, only to
2314                             // find that it's not there. On the other
2315                             // side of inlining, the crates knows to
2316                             // not declare this static as
2317                             // available_externally (because it isn't)
2318                             inlineable = true;
2319                         }
2320
2321                         if attr::contains_name(i.attrs.as_slice(),
2322                                                "thread_local") {
2323                             llvm::set_thread_local(g, true);
2324                         }
2325
2326                         if !inlineable {
2327                             debug!("{} not inlined", sym);
2328                             ccx.non_inlineable_statics.borrow_mut()
2329                                                       .insert(id);
2330                         }
2331
2332                         ccx.item_symbols.borrow_mut().insert(i.id, sym);
2333                         g
2334                     }
2335                 }
2336
2337                 ast::ItemFn(_, _, abi, _, _) => {
2338                     let llfn = if abi == Rust {
2339                         register_fn(ccx, i.span, sym, i.id, ty)
2340                     } else {
2341                         foreign::register_rust_fn_with_foreign_abi(ccx,
2342                                                                    i.span,
2343                                                                    sym,
2344                                                                    i.id)
2345                     };
2346                     set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2347                     llfn
2348                 }
2349
2350                 _ => fail!("get_item_val: weird result in table")
2351             };
2352
2353             match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
2354                                                      "link_section") {
2355                 Some(sect) => unsafe {
2356                     sect.get().with_c_str(|buf| {
2357                         llvm::LLVMSetSection(v, buf);
2358                     })
2359                 },
2360                 None => ()
2361             }
2362
2363             v
2364         }
2365
2366         ast_map::NodeTraitMethod(trait_method) => {
2367             debug!("get_item_val(): processing a NodeTraitMethod");
2368             match *trait_method {
2369                 ast::Required(_) => {
2370                     ccx.sess().bug("unexpected variant: required trait method in \
2371                                    get_item_val()");
2372                 }
2373                 ast::Provided(m) => {
2374                     register_method(ccx, id, &*m)
2375                 }
2376             }
2377         }
2378
2379         ast_map::NodeMethod(m) => {
2380             register_method(ccx, id, &*m)
2381         }
2382
2383         ast_map::NodeForeignItem(ni) => {
2384             foreign = true;
2385
2386             match ni.node {
2387                 ast::ForeignItemFn(..) => {
2388                     let abi = ccx.tcx.map.get_foreign_abi(id);
2389                     let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2390                     let name = foreign::link_name(&*ni);
2391                     foreign::register_foreign_item_fn(ccx, abi, ty,
2392                                                       name.get().as_slice(),
2393                                                       Some(ni.span))
2394                 }
2395                 ast::ForeignItemStatic(..) => {
2396                     foreign::register_static(ccx, &*ni)
2397                 }
2398             }
2399         }
2400
2401         ast_map::NodeVariant(ref v) => {
2402             let llfn;
2403             let args = match v.node.kind {
2404                 ast::TupleVariantKind(ref args) => args,
2405                 ast::StructVariantKind(_) => {
2406                     fail!("struct variant kind unexpected in get_item_val")
2407                 }
2408             };
2409             assert!(args.len() != 0u);
2410             let ty = ty::node_id_to_type(ccx.tcx(), id);
2411             let parent = ccx.tcx.map.get_parent(id);
2412             let enm = ccx.tcx.map.expect_item(parent);
2413             let sym = exported_name(ccx,
2414                                     id,
2415                                     ty,
2416                                     enm.attrs.as_slice());
2417
2418             llfn = match enm.node {
2419                 ast::ItemEnum(_, _) => {
2420                     register_fn(ccx, (*v).span, sym, id, ty)
2421                 }
2422                 _ => fail!("NodeVariant, shouldn't happen")
2423             };
2424             set_inline_hint(llfn);
2425             llfn
2426         }
2427
2428         ast_map::NodeStructCtor(struct_def) => {
2429             // Only register the constructor if this is a tuple-like struct.
2430             let ctor_id = match struct_def.ctor_id {
2431                 None => {
2432                     ccx.sess().bug("attempt to register a constructor of \
2433                                     a non-tuple-like struct")
2434                 }
2435                 Some(ctor_id) => ctor_id,
2436             };
2437             let parent = ccx.tcx.map.get_parent(id);
2438             let struct_item = ccx.tcx.map.expect_item(parent);
2439             let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2440             let sym = exported_name(ccx,
2441                                     id,
2442                                     ty,
2443                                     struct_item.attrs
2444                                                .as_slice());
2445             let llfn = register_fn(ccx, struct_item.span,
2446                                    sym, ctor_id, ty);
2447             set_inline_hint(llfn);
2448             llfn
2449         }
2450
2451         ref variant => {
2452             ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2453                                    variant).as_slice())
2454         }
2455     };
2456
2457     // foreign items (extern fns and extern statics) don't have internal
2458     // linkage b/c that doesn't quite make sense. Otherwise items can
2459     // have internal linkage if they're not reachable.
2460     if !foreign && !ccx.reachable.contains(&id) {
2461         llvm::SetLinkage(val, llvm::InternalLinkage);
2462     }
2463
2464     ccx.item_vals.borrow_mut().insert(id, val);
2465     val
2466 }
2467
2468 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2469                    m: &ast::Method) -> ValueRef {
2470     let mty = ty::node_id_to_type(ccx.tcx(), id);
2471
2472     let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2473
2474     let llfn = register_fn(ccx, m.span, sym, id, mty);
2475     set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2476     llfn
2477 }
2478
2479 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2480     unsafe {
2481         return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2482     }
2483 }
2484
2485 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2486     -> encoder::EncodeParams<'r> {
2487         encoder::EncodeParams {
2488             diag: cx.sess().diagnostic(),
2489             tcx: cx.tcx(),
2490             reexports2: &cx.exp_map2,
2491             item_symbols: &cx.item_symbols,
2492             non_inlineable_statics: &cx.non_inlineable_statics,
2493             link_meta: &cx.link_meta,
2494             cstore: &cx.sess().cstore,
2495             encode_inlined_item: ie,
2496             reachable: &cx.reachable,
2497         }
2498 }
2499
2500 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2501     use flate;
2502
2503     let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2504         *ty != config::CrateTypeExecutable
2505     });
2506     if !any_library {
2507         return Vec::new()
2508     }
2509
2510     let encode_inlined_item: encoder::EncodeInlinedItem =
2511         |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
2512
2513     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2514     let metadata = encoder::encode_metadata(encode_parms, krate);
2515     let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2516                      .append(match flate::deflate_bytes(metadata.as_slice()) {
2517                          Some(compressed) => compressed,
2518                          None => {
2519                              cx.sess().fatal("failed to compress metadata")
2520                          }
2521                      }.as_slice());
2522     let llmeta = C_bytes(cx, compressed.as_slice());
2523     let llconst = C_struct(cx, [llmeta], false);
2524     let name = format!("rust_metadata_{}_{}",
2525                        cx.link_meta.crate_name,
2526                        cx.link_meta.crate_hash);
2527     let llglobal = name.with_c_str(|buf| {
2528         unsafe {
2529             llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2530         }
2531     });
2532     unsafe {
2533         llvm::LLVMSetInitializer(llglobal, llconst);
2534         let name = loader::meta_section_name(cx.sess().targ_cfg.os);
2535         name.unwrap_or("rust_metadata").with_c_str(|buf| {
2536             llvm::LLVMSetSection(llglobal, buf)
2537         });
2538     }
2539     return metadata;
2540 }
2541
2542 pub fn trans_crate(krate: ast::Crate,
2543                    analysis: CrateAnalysis) -> (ty::ctxt, CrateTranslation) {
2544     let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, name, .. } = analysis;
2545
2546     // Before we touch LLVM, make sure that multithreading is enabled.
2547     unsafe {
2548         use std::sync::{Once, ONCE_INIT};
2549         static mut INIT: Once = ONCE_INIT;
2550         static mut POISONED: bool = false;
2551         INIT.doit(|| {
2552             if llvm::LLVMStartMultithreaded() != 1 {
2553                 // use an extra bool to make sure that all future usage of LLVM
2554                 // cannot proceed despite the Once not running more than once.
2555                 POISONED = true;
2556             }
2557         });
2558
2559         if POISONED {
2560             tcx.sess.bug("couldn't enable multi-threaded LLVM");
2561         }
2562     }
2563
2564     let link_meta = link::build_link_meta(&tcx.sess, &krate, name);
2565
2566     // Append ".rs" to crate name as LLVM module identifier.
2567     //
2568     // LLVM code generator emits a ".file filename" directive
2569     // for ELF backends. Value of the "filename" is set as the
2570     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
2571     // crashes if the module identifier is same as other symbols
2572     // such as a function name in the module.
2573     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2574     let mut llmod_id = link_meta.crate_name.clone();
2575     llmod_id.push_str(".rs");
2576
2577     let ccx = CrateContext::new(llmod_id.as_slice(), tcx, exp_map2,
2578                                 Sha256::new(), link_meta, reachable);
2579
2580     // First, verify intrinsics.
2581     intrinsic::check_intrinsics(&ccx);
2582
2583     // Next, translate the module.
2584     {
2585         let _icx = push_ctxt("text");
2586         trans_mod(&ccx, &krate.module);
2587     }
2588
2589     glue::emit_tydescs(&ccx);
2590     if ccx.sess().opts.debuginfo != NoDebugInfo {
2591         debuginfo::finalize(&ccx);
2592     }
2593
2594     // Translate the metadata.
2595     let metadata = write_metadata(&ccx, &krate);
2596     if ccx.sess().trans_stats() {
2597         println!("--- trans stats ---");
2598         println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2599         println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2600         println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2601         println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2602
2603         println!("n_fns: {}", ccx.stats.n_fns.get());
2604         println!("n_monos: {}", ccx.stats.n_monos.get());
2605         println!("n_inlines: {}", ccx.stats.n_inlines.get());
2606         println!("n_closures: {}", ccx.stats.n_closures.get());
2607         println!("fn stats:");
2608         ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2609             insns_b.cmp(&insns_a)
2610         });
2611         for tuple in ccx.stats.fn_stats.borrow().iter() {
2612             match *tuple {
2613                 (ref name, ms, insns) => {
2614                     println!("{} insns, {} ms, {}", insns, ms, *name);
2615                 }
2616             }
2617         }
2618     }
2619     if ccx.sess().count_llvm_insns() {
2620         for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2621             println!("{:7u} {}", *v, *k);
2622         }
2623     }
2624
2625     let llcx = ccx.llcx;
2626     let link_meta = ccx.link_meta.clone();
2627     let llmod = ccx.llmod;
2628
2629     let mut reachable: Vec<String> = ccx.reachable.iter().filter_map(|id| {
2630         ccx.item_symbols.borrow().find(id).map(|s| s.to_string())
2631     }).collect();
2632
2633     // For the purposes of LTO, we add to the reachable set all of the upstream
2634     // reachable extern fns. These functions are all part of the public ABI of
2635     // the final product, so LTO needs to preserve them.
2636     ccx.sess().cstore.iter_crate_data(|cnum, _| {
2637         let syms = csearch::get_reachable_extern_fns(&ccx.sess().cstore, cnum);
2638         reachable.extend(syms.move_iter().map(|did| {
2639             csearch::get_symbol(&ccx.sess().cstore, did)
2640         }));
2641     });
2642
2643     // Make sure that some other crucial symbols are not eliminated from the
2644     // module. This includes the main function, the crate map (used for debug
2645     // log settings and I/O), and finally the curious rust_stack_exhausted
2646     // symbol. This symbol is required for use by the libmorestack library that
2647     // we link in, so we must ensure that this symbol is not internalized (if
2648     // defined in the crate).
2649     reachable.push("main".to_string());
2650     reachable.push("rust_stack_exhausted".to_string());
2651
2652     // referenced from .eh_frame section on some platforms
2653     reachable.push("rust_eh_personality".to_string());
2654     // referenced from rt/rust_try.ll
2655     reachable.push("rust_eh_personality_catch".to_string());
2656
2657     let metadata_module = ccx.metadata_llmod;
2658     let formats = ccx.tcx.dependency_formats.borrow().clone();
2659     let no_builtins = attr::contains_name(krate.attrs.as_slice(), "no_builtins");
2660
2661     (ccx.tcx, CrateTranslation {
2662         context: llcx,
2663         module: llmod,
2664         link: link_meta,
2665         metadata_module: metadata_module,
2666         metadata: metadata,
2667         reachable: reachable,
2668         crate_formats: formats,
2669         no_builtins: no_builtins,
2670     })
2671 }