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