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