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