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