]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/base.rs
Merge remote-tracking branch 'remotes/origin/master' into str-remove-null
[rust.git] / src / librustc / middle / trans / base.rs
1 // Copyright 2012-2013 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 many TypeRefs correspond to one ty::t; for instance, tup(int, int,
24 //     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
25
26
27 use back::link::{mangle_exported_name};
28 use back::{link, abi};
29 use driver::session;
30 use driver::session::Session;
31 use driver::driver::{CrateAnalysis, CrateTranslation};
32 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
33 use lib::llvm::{llvm, True};
34 use lib;
35 use metadata::common::LinkMeta;
36 use metadata::{csearch, cstore, encoder};
37 use middle::astencode;
38 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
39 use middle::lang_items::{MallocFnLangItem, ClosureExchangeMallocFnLangItem};
40 use middle::trans::_match;
41 use middle::trans::adt;
42 use middle::trans::base;
43 use middle::trans::build::*;
44 use middle::trans::builder::{Builder, noname};
45 use middle::trans::callee;
46 use middle::trans::common::*;
47 use middle::trans::consts;
48 use middle::trans::controlflow;
49 use middle::trans::datum;
50 use middle::trans::debuginfo;
51 use middle::trans::expr;
52 use middle::trans::foreign;
53 use middle::trans::glue;
54 use middle::trans::inline;
55 use middle::trans::machine;
56 use middle::trans::machine::{llalign_of_min, llsize_of};
57 use middle::trans::meth;
58 use middle::trans::monomorphize;
59 use middle::trans::tvec;
60 use middle::trans::type_of;
61 use middle::trans::type_of::*;
62 use middle::ty;
63 use util::common::indenter;
64 use util::ppaux::{Repr, ty_to_str};
65
66 use middle::trans::type_::Type;
67
68 use std::c_str::ToCStr;
69 use std::hash;
70 use std::hashmap::HashMap;
71 use std::io;
72 use std::libc::c_uint;
73 use std::uint;
74 use std::vec;
75 use std::local_data;
76 use extra::time;
77 use extra::sort;
78 use syntax::ast::ident;
79 use syntax::ast_map::{path, path_elt_to_str, path_name};
80 use syntax::ast_util::{local_def};
81 use syntax::attr;
82 use syntax::attr::AttrMetaMethods;
83 use syntax::codemap::span;
84 use syntax::parse::token;
85 use syntax::parse::token::{special_idents};
86 use syntax::print::pprust::stmt_to_str;
87 use syntax::oldvisit;
88 use syntax::{ast, ast_util, codemap, ast_map};
89 use syntax::abi::{X86, X86_64, Arm, Mips};
90
91 pub use middle::trans::context::task_llcx;
92
93 static task_local_insn_key: local_data::Key<@~[&'static str]> = &local_data::Key;
94
95 pub fn with_insn_ctxt(blk: &fn(&[&'static str])) {
96     let opt = local_data::get(task_local_insn_key, |k| k.map(|&k| *k));
97     if opt.is_some() {
98         blk(*opt.unwrap());
99     }
100 }
101
102 pub fn init_insn_ctxt() {
103     local_data::set(task_local_insn_key, @~[]);
104 }
105
106 pub struct _InsnCtxt { _x: () }
107
108 #[unsafe_destructor]
109 impl Drop for _InsnCtxt {
110     fn drop(&self) {
111         do local_data::modify(task_local_insn_key) |c| {
112             do c.map_consume |ctx| {
113                 let mut ctx = (*ctx).clone();
114                 ctx.pop();
115                 @ctx
116             }
117         }
118     }
119 }
120
121 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
122     debug!("new InsnCtxt: %s", s);
123     do local_data::modify(task_local_insn_key) |c| {
124         do c.map_consume |ctx| {
125             let mut ctx = (*ctx).clone();
126             ctx.push(s);
127             @ctx
128         }
129     }
130     _InsnCtxt { _x: () }
131 }
132
133 fn fcx_has_nonzero_span(fcx: &FunctionContext) -> bool {
134     match fcx.span {
135         None => true,
136         Some(span) => *span.lo != 0 || *span.hi != 0
137     }
138 }
139
140 struct StatRecorder<'self> {
141     ccx: @mut CrateContext,
142     name: &'self str,
143     start: u64,
144     istart: uint,
145 }
146
147 impl<'self> StatRecorder<'self> {
148     pub fn new(ccx: @mut CrateContext,
149                name: &'self str) -> StatRecorder<'self> {
150         let start = if ccx.sess.trans_stats() {
151             time::precise_time_ns()
152         } else {
153             0
154         };
155         let istart = ccx.stats.n_llvm_insns;
156         StatRecorder {
157             ccx: ccx,
158             name: name,
159             start: start,
160             istart: istart,
161         }
162     }
163 }
164
165 #[unsafe_destructor]
166 impl<'self> Drop for StatRecorder<'self> {
167     pub fn drop(&self) {
168         if self.ccx.sess.trans_stats() {
169             let end = time::precise_time_ns();
170             let elapsed = ((end - self.start) / 1_000_000) as uint;
171             let iend = self.ccx.stats.n_llvm_insns;
172             self.ccx.stats.fn_stats.push((self.name.to_owned(),
173                                           elapsed,
174                                           iend - self.istart));
175             self.ccx.stats.n_fns += 1;
176             // Reset LLVM insn count to avoid compound costs.
177             self.ccx.stats.n_llvm_insns = self.istart;
178         }
179     }
180 }
181
182 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
183     let llfn: ValueRef = do name.to_c_str().with_ref |buf| {
184         unsafe {
185             llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
186         }
187     };
188
189     lib::llvm::SetFunctionCallConv(llfn, cc);
190     return llfn;
191 }
192
193 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
194     return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
195 }
196
197 // Only use this if you are going to actually define the function. It's
198 // not valid to simply declare a function as internal.
199 pub fn decl_internal_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
200     let llfn = decl_cdecl_fn(llmod, name, ty);
201     lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
202     return llfn;
203 }
204
205 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: @str,
206                      cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
207     match externs.find_copy(&name) {
208         Some(n) => return n,
209         None => ()
210     }
211     let f = decl_fn(llmod, name, cc, ty);
212     externs.insert(name, f);
213     return f;
214 }
215
216 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
217                         name: @str, ty: Type) -> ValueRef {
218     match externs.find_copy(&name) {
219         Some(n) => return n,
220         None => ()
221     }
222     unsafe {
223         let c = do name.to_c_str().with_ref |buf| {
224             llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
225         };
226         externs.insert(name, c);
227         return c;
228     }
229 }
230 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
231     let _icx = push_ctxt("umax");
232     let cond = ICmp(cx, lib::llvm::IntULT, a, b);
233     return Select(cx, cond, b, a);
234 }
235
236 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
237     let _icx = push_ctxt("umin");
238     let cond = ICmp(cx, lib::llvm::IntULT, a, b);
239     return Select(cx, cond, a, b);
240 }
241
242 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
243 // The type of the returned pointer is always i8*.  If you care about the
244 // return type, use bump_ptr().
245 pub fn ptr_offs(bcx: @mut Block, base: ValueRef, sz: ValueRef) -> ValueRef {
246     let _icx = push_ctxt("ptr_offs");
247     let raw = PointerCast(bcx, base, Type::i8p());
248     InBoundsGEP(bcx, raw, [sz])
249 }
250
251 // Increment a pointer by a given amount and then cast it to be a pointer
252 // to a given type.
253 pub fn bump_ptr(bcx: @mut Block, t: ty::t, base: ValueRef, sz: ValueRef) ->
254    ValueRef {
255     let _icx = push_ctxt("bump_ptr");
256     let ccx = bcx.ccx();
257     let bumped = ptr_offs(bcx, base, sz);
258     let typ = type_of(ccx, t).ptr_to();
259     PointerCast(bcx, bumped, typ)
260 }
261
262 // Returns a pointer to the body for the box. The box may be an opaque
263 // box. The result will be casted to the type of body_t, if it is statically
264 // known.
265 //
266 // The runtime equivalent is box_body() in "rust_internal.h".
267 pub fn opaque_box_body(bcx: @mut Block,
268                        body_t: ty::t,
269                        boxptr: ValueRef) -> ValueRef {
270     let _icx = push_ctxt("opaque_box_body");
271     let ccx = bcx.ccx();
272     let ty = type_of(ccx, body_t);
273     let ty = Type::box(ccx, &ty);
274     let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
275     GEPi(bcx, boxptr, [0u, abi::box_field_body])
276 }
277
278 // malloc_raw_dyn: allocates a box to contain a given type, but with a
279 // potentially dynamic size.
280 pub fn malloc_raw_dyn(bcx: @mut Block,
281                       t: ty::t,
282                       heap: heap,
283                       size: ValueRef) -> Result {
284     let _icx = push_ctxt("malloc_raw");
285     let ccx = bcx.ccx();
286
287     fn require_alloc_fn(bcx: @mut Block, t: ty::t, it: LangItem) -> ast::def_id {
288         let li = &bcx.tcx().lang_items;
289         match li.require(it) {
290             Ok(id) => id,
291             Err(s) => {
292                 bcx.tcx().sess.fatal(fmt!("allocation of `%s` %s",
293                                           bcx.ty_to_str(t), s));
294             }
295         }
296     }
297
298     if heap == heap_exchange {
299         let llty_value = type_of::type_of(ccx, t);
300
301
302         // Allocate space:
303         let r = callee::trans_lang_call(
304             bcx,
305             require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
306             [size],
307             None);
308         rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
309     } else {
310         // we treat ~fn, @fn and @[] as @ here, which isn't ideal
311         let (mk_fn, langcall) = match heap {
312             heap_managed | heap_managed_unique => {
313                 (ty::mk_imm_box,
314                  require_alloc_fn(bcx, t, MallocFnLangItem))
315             }
316             heap_exchange_closure => {
317                 (ty::mk_imm_box,
318                  require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem))
319             }
320             _ => fail!("heap_exchange already handled")
321         };
322
323         // Grab the TypeRef type of box_ptr_ty.
324         let box_ptr_ty = mk_fn(bcx.tcx(), t);
325         let llty = type_of(ccx, box_ptr_ty);
326
327         // Get the tydesc for the body:
328         let static_ti = get_tydesc(ccx, t);
329         glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
330
331         // Allocate space:
332         let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
333         let r = callee::trans_lang_call(
334             bcx,
335             langcall,
336             [tydesc, size],
337             None);
338         let r = rslt(r.bcx, PointerCast(r.bcx, r.val, llty));
339         maybe_set_managed_unique_rc(r.bcx, r.val, heap);
340         r
341     }
342 }
343
344 // malloc_raw: expects an unboxed type and returns a pointer to
345 // enough space for a box of that type.  This includes a rust_opaque_box
346 // header.
347 pub fn malloc_raw(bcx: @mut Block, t: ty::t, heap: heap) -> Result {
348     let ty = type_of(bcx.ccx(), t);
349     let size = llsize_of(bcx.ccx(), ty);
350     malloc_raw_dyn(bcx, t, heap, size)
351 }
352
353 pub struct MallocResult {
354     bcx: @mut Block,
355     box: ValueRef,
356     body: ValueRef
357 }
358
359 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
360 // and pulls out the body
361 pub fn malloc_general_dyn(bcx: @mut Block, t: ty::t, heap: heap, size: ValueRef)
362     -> MallocResult {
363     assert!(heap != heap_exchange);
364     let _icx = push_ctxt("malloc_general");
365     let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
366     let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
367
368     MallocResult { bcx: bcx, box: llbox, body: body }
369 }
370
371 pub fn malloc_general(bcx: @mut Block, t: ty::t, heap: heap) -> MallocResult {
372     let ty = type_of(bcx.ccx(), t);
373     assert!(heap != heap_exchange);
374     malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
375 }
376 pub fn malloc_boxed(bcx: @mut Block, t: ty::t)
377     -> MallocResult {
378     malloc_general(bcx, t, heap_managed)
379 }
380
381 pub fn heap_for_unique(bcx: @mut Block, t: ty::t) -> heap {
382     if ty::type_contents(bcx.tcx(), t).contains_managed() {
383         heap_managed_unique
384     } else {
385         heap_exchange
386     }
387 }
388
389 pub fn maybe_set_managed_unique_rc(bcx: @mut Block, bx: ValueRef, heap: heap) {
390     assert!(heap != heap_exchange);
391     if heap == heap_managed_unique {
392         // In cases where we are looking at a unique-typed allocation in the
393         // managed heap (thus have refcount 1 from the managed allocator),
394         // such as a ~(@foo) or such. These need to have their refcount forced
395         // to -2 so the annihilator ignores them.
396         let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
397         let rc_val = C_int(bcx.ccx(), -2);
398         Store(bcx, rc_val, rc);
399     }
400 }
401
402 // Type descriptor and type glue stuff
403
404 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
405     get_tydesc(ccx, t).tydesc
406 }
407
408 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
409     match ccx.tydescs.find(&t) {
410         Some(&inf) => {
411             return inf;
412         }
413         _ => { }
414     }
415
416     ccx.stats.n_static_tydescs += 1u;
417     let inf = glue::declare_tydesc(ccx, t);
418     ccx.tydescs.insert(t, inf);
419     return inf;
420 }
421
422 pub fn set_optimize_for_size(f: ValueRef) {
423     lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
424 }
425
426 pub fn set_no_inline(f: ValueRef) {
427     lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
428 }
429
430 pub fn set_no_unwind(f: ValueRef) {
431     lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
432 }
433
434 // Tell LLVM to emit the information necessary to unwind the stack for the
435 // function f.
436 pub fn set_uwtable(f: ValueRef) {
437     lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
438 }
439
440 pub fn set_inline_hint(f: ValueRef) {
441     lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
442 }
443
444 pub fn set_inline_hint_if_appr(attrs: &[ast::Attribute],
445                                llfn: ValueRef) {
446     use syntax::attr::*;
447     match find_inline_attr(attrs) {
448         InlineHint   => set_inline_hint(llfn),
449         InlineAlways => set_always_inline(llfn),
450         InlineNever  => set_no_inline(llfn),
451         InlineNone   => { /* fallthrough */ }
452     }
453 }
454
455 pub fn set_always_inline(f: ValueRef) {
456     lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
457 }
458
459 pub fn set_fixed_stack_segment(f: ValueRef) {
460     lib::llvm::SetFixedStackSegmentAttribute(f);
461 }
462
463 pub fn set_glue_inlining(f: ValueRef, t: ty::t) {
464     if ty::type_is_structural(t) {
465         set_optimize_for_size(f);
466     } else { set_always_inline(f); }
467 }
468
469 // Double-check that we never ask LLVM to declare the same symbol twice. It
470 // silently mangles such symbols, breaking our linkage model.
471 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
472     if ccx.all_llvm_symbols.contains(&sym) {
473         ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
474     }
475     ccx.all_llvm_symbols.insert(sym);
476 }
477
478
479 pub fn get_res_dtor(ccx: @mut CrateContext,
480                     did: ast::def_id,
481                     parent_id: ast::def_id,
482                     substs: &[ty::t])
483                  -> ValueRef {
484     let _icx = push_ctxt("trans_res_dtor");
485     if !substs.is_empty() {
486         let did = if did.crate != ast::LOCAL_CRATE {
487             inline::maybe_instantiate_inline(ccx, did)
488         } else {
489             did
490         };
491         assert_eq!(did.crate, ast::LOCAL_CRATE);
492         let tsubsts = ty::substs {regions: ty::ErasedRegions,
493                                   self_ty: None,
494                                   tps: /*bad*/ substs.to_owned() };
495         let (val, _) = monomorphize::monomorphic_fn(ccx,
496                                                     did,
497                                                     &tsubsts,
498                                                     None,
499                                                     None,
500                                                     None);
501
502         val
503     } else if did.crate == ast::LOCAL_CRATE {
504         get_item_val(ccx, did.node)
505     } else {
506         let tcx = ccx.tcx;
507         let name = csearch::get_symbol(ccx.sess.cstore, did);
508         let class_ty = ty::subst_tps(tcx,
509                                      substs,
510                                      None,
511                                      ty::lookup_item_type(tcx, parent_id).ty);
512         let llty = type_of_dtor(ccx, class_ty);
513         let name = name.to_managed(); // :-(
514         get_extern_fn(&mut ccx.externs,
515                       ccx.llmod,
516                       name,
517                       lib::llvm::CCallConv,
518                       llty)
519     }
520 }
521
522 // Structural comparison: a rather involved form of glue.
523 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
524     if cx.sess.opts.save_temps {
525         do s.to_c_str().with_ref |buf| {
526             unsafe {
527                 llvm::LLVMSetValueName(v, buf)
528             }
529         }
530     }
531 }
532
533
534 // Used only for creating scalar comparison glue.
535 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
536
537 // NB: This produces an i1, not a Rust bool (i8).
538 pub fn compare_scalar_types(cx: @mut Block,
539                             lhs: ValueRef,
540                             rhs: ValueRef,
541                             t: ty::t,
542                             op: ast::binop)
543                          -> Result {
544     let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
545
546     match ty::get(t).sty {
547         ty::ty_nil => rslt(cx, f(nil_type)),
548         ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
549         ty::ty_int(_) => rslt(cx, f(signed_int)),
550         ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
551         ty::ty_float(_) => rslt(cx, f(floating_point)),
552         ty::ty_type => {
553             rslt(
554                 controlflow::trans_fail(
555                     cx, None,
556                     @"attempt to compare values of type type"),
557                 C_nil())
558         }
559         _ => {
560             // Should never get here, because t is scalar.
561             cx.sess().bug("non-scalar type passed to \
562                            compare_scalar_types")
563         }
564     }
565 }
566
567
568 // A helper function to do the actual comparison of scalar values.
569 pub fn compare_scalar_values(cx: @mut Block,
570                              lhs: ValueRef,
571                              rhs: ValueRef,
572                              nt: scalar_type,
573                              op: ast::binop)
574                           -> ValueRef {
575     let _icx = push_ctxt("compare_scalar_values");
576     fn die(cx: @mut Block) -> ! {
577         cx.tcx().sess.bug("compare_scalar_values: must be a\
578                            comparison operator");
579     }
580     match nt {
581       nil_type => {
582         // We don't need to do actual comparisons for nil.
583         // () == () holds but () < () does not.
584         match op {
585           ast::eq | ast::le | ast::ge => return C_i1(true),
586           ast::ne | ast::lt | ast::gt => return C_i1(false),
587           // refinements would be nice
588           _ => die(cx)
589         }
590       }
591       floating_point => {
592         let cmp = match op {
593           ast::eq => lib::llvm::RealOEQ,
594           ast::ne => lib::llvm::RealUNE,
595           ast::lt => lib::llvm::RealOLT,
596           ast::le => lib::llvm::RealOLE,
597           ast::gt => lib::llvm::RealOGT,
598           ast::ge => lib::llvm::RealOGE,
599           _ => die(cx)
600         };
601         return FCmp(cx, cmp, lhs, rhs);
602       }
603       signed_int => {
604         let cmp = match op {
605           ast::eq => lib::llvm::IntEQ,
606           ast::ne => lib::llvm::IntNE,
607           ast::lt => lib::llvm::IntSLT,
608           ast::le => lib::llvm::IntSLE,
609           ast::gt => lib::llvm::IntSGT,
610           ast::ge => lib::llvm::IntSGE,
611           _ => die(cx)
612         };
613         return ICmp(cx, cmp, lhs, rhs);
614       }
615       unsigned_int => {
616         let cmp = match op {
617           ast::eq => lib::llvm::IntEQ,
618           ast::ne => lib::llvm::IntNE,
619           ast::lt => lib::llvm::IntULT,
620           ast::le => lib::llvm::IntULE,
621           ast::gt => lib::llvm::IntUGT,
622           ast::ge => lib::llvm::IntUGE,
623           _ => die(cx)
624         };
625         return ICmp(cx, cmp, lhs, rhs);
626       }
627     }
628 }
629
630 pub type val_and_ty_fn<'self> = &'self fn(@mut Block, ValueRef, ty::t) -> @mut Block;
631
632 pub fn load_inbounds(cx: @mut Block, p: ValueRef, idxs: &[uint]) -> ValueRef {
633     return Load(cx, GEPi(cx, p, idxs));
634 }
635
636 pub fn store_inbounds(cx: @mut Block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
637     Store(cx, v, GEPi(cx, p, idxs));
638 }
639
640 // Iterates through the elements of a structural type.
641 pub fn iter_structural_ty(cx: @mut Block, av: ValueRef, t: ty::t,
642                           f: val_and_ty_fn) -> @mut Block {
643     let _icx = push_ctxt("iter_structural_ty");
644
645     fn iter_variant(cx: @mut Block, repr: &adt::Repr, av: ValueRef,
646                     variant: @ty::VariantInfo,
647                     tps: &[ty::t], f: val_and_ty_fn) -> @mut Block {
648         let _icx = push_ctxt("iter_variant");
649         let tcx = cx.tcx();
650         let mut cx = cx;
651
652         for (i, &arg) in variant.args.iter().enumerate() {
653             cx = f(cx,
654                    adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
655                    ty::subst_tps(tcx, tps, None, arg));
656         }
657         return cx;
658     }
659
660     let mut cx = cx;
661     match ty::get(t).sty {
662       ty::ty_struct(*) => {
663           let repr = adt::represent_type(cx.ccx(), t);
664           do expr::with_field_tys(cx.tcx(), t, None) |discr, field_tys| {
665               for (i, field_ty) in field_tys.iter().enumerate() {
666                   let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
667                   cx = f(cx, llfld_a, field_ty.mt.ty);
668               }
669           }
670       }
671       ty::ty_estr(ty::vstore_fixed(_)) |
672       ty::ty_evec(_, ty::vstore_fixed(_)) => {
673         let (base, len) = tvec::get_base_and_len(cx, av, t);
674         cx = tvec::iter_vec_raw(cx, base, t, len, f);
675       }
676       ty::ty_tup(ref args) => {
677           let repr = adt::represent_type(cx.ccx(), t);
678           for (i, arg) in args.iter().enumerate() {
679               let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
680               cx = f(cx, llfld_a, *arg);
681           }
682       }
683       ty::ty_enum(tid, ref substs) => {
684           let ccx = cx.ccx();
685
686           let repr = adt::represent_type(ccx, t);
687           let variants = ty::enum_variants(ccx.tcx, tid);
688           let n_variants = (*variants).len();
689
690           // NB: we must hit the discriminant first so that structural
691           // comparison know not to proceed when the discriminants differ.
692
693           match adt::trans_switch(cx, repr, av) {
694               (_match::single, None) => {
695                   cx = iter_variant(cx, repr, av, variants[0],
696                                     substs.tps, f);
697               }
698               (_match::switch, Some(lldiscrim_a)) => {
699                   cx = f(cx, lldiscrim_a, ty::mk_int());
700                   let unr_cx = sub_block(cx, "enum-iter-unr");
701                   Unreachable(unr_cx);
702                   let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
703                                         n_variants);
704                   let next_cx = sub_block(cx, "enum-iter-next");
705
706                   for variant in (*variants).iter() {
707                       let variant_cx =
708                           sub_block(cx, ~"enum-iter-variant-" +
709                                     uint::to_str(variant.disr_val));
710                       let variant_cx =
711                           iter_variant(variant_cx, repr, av, *variant,
712                                        substs.tps, |x,y,z| f(x,y,z));
713                       match adt::trans_case(cx, repr, variant.disr_val) {
714                           _match::single_result(r) => {
715                               AddCase(llswitch, r.val, variant_cx.llbb)
716                           }
717                           _ => ccx.sess.unimpl("value from adt::trans_case \
718                                                 in iter_structural_ty")
719                       }
720                       Br(variant_cx, next_cx.llbb);
721                   }
722                   cx = next_cx;
723               }
724               _ => ccx.sess.unimpl("value from adt::trans_switch \
725                                     in iter_structural_ty")
726           }
727       }
728       _ => cx.sess().unimpl("type in iter_structural_ty")
729     }
730     return cx;
731 }
732
733 pub fn cast_shift_expr_rhs(cx: @mut Block, op: ast::binop,
734                            lhs: ValueRef, rhs: ValueRef) -> ValueRef {
735     cast_shift_rhs(op, lhs, rhs,
736                    |a,b| Trunc(cx, a, b),
737                    |a,b| ZExt(cx, a, b))
738 }
739
740 pub fn cast_shift_const_rhs(op: ast::binop,
741                             lhs: ValueRef, rhs: ValueRef) -> ValueRef {
742     cast_shift_rhs(op, lhs, rhs,
743                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
744                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
745 }
746
747 pub fn cast_shift_rhs(op: ast::binop,
748                       lhs: ValueRef, rhs: ValueRef,
749                       trunc: &fn(ValueRef, Type) -> ValueRef,
750                       zext: &fn(ValueRef, Type) -> ValueRef)
751                    -> ValueRef {
752     // Shifts may have any size int on the rhs
753     unsafe {
754         if ast_util::is_shift_binop(op) {
755             let rhs_llty = val_ty(rhs);
756             let lhs_llty = val_ty(lhs);
757             let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
758             let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
759             if lhs_sz < rhs_sz {
760                 trunc(rhs, lhs_llty)
761             } else if lhs_sz > rhs_sz {
762                 // FIXME (#1877: If shifting by negative
763                 // values becomes not undefined then this is wrong.
764                 zext(rhs, lhs_llty)
765             } else {
766                 rhs
767             }
768         } else {
769             rhs
770         }
771     }
772 }
773
774 pub fn fail_if_zero(cx: @mut Block, span: span, divrem: ast::binop,
775                     rhs: ValueRef, rhs_t: ty::t) -> @mut Block {
776     let text = if divrem == ast::div {
777         @"attempted to divide by zero"
778     } else {
779         @"attempted remainder with a divisor of zero"
780     };
781     let is_zero = match ty::get(rhs_t).sty {
782       ty::ty_int(t) => {
783         let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
784         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
785       }
786       ty::ty_uint(t) => {
787         let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
788         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
789       }
790       _ => {
791         cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
792                           ty_to_str(cx.ccx().tcx, rhs_t));
793       }
794     };
795     do with_cond(cx, is_zero) |bcx| {
796         controlflow::trans_fail(bcx, Some(span), text)
797     }
798 }
799
800 pub fn null_env_ptr(bcx: @mut Block) -> ValueRef {
801     C_null(Type::opaque_box(bcx.ccx()).ptr_to())
802 }
803
804 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::def_id, t: ty::t)
805     -> ValueRef {
806     let name = csearch::get_symbol(ccx.sess.cstore, did).to_managed(); // Sad
807     match ty::get(t).sty {
808       ty::ty_bare_fn(_) | ty::ty_closure(_) => {
809         let llty = type_of_fn_from_ty(ccx, t);
810         return get_extern_fn(&mut ccx.externs, ccx.llmod, name,
811                              lib::llvm::CCallConv, llty);
812       }
813       _ => {
814         let llty = type_of(ccx, t);
815         return get_extern_const(&mut ccx.externs, ccx.llmod, name, llty);
816       }
817     };
818 }
819
820 pub fn invoke(bcx: @mut Block, llfn: ValueRef, llargs: ~[ValueRef])
821            -> (ValueRef, @mut Block) {
822     let _icx = push_ctxt("invoke_");
823     if bcx.unreachable {
824         return (C_null(Type::i8()), bcx);
825     }
826
827     match bcx.node_info {
828         None => debug!("invoke at ???"),
829         Some(node_info) => {
830             debug!("invoke at %s",
831                    bcx.sess().codemap.span_to_str(node_info.span));
832         }
833     }
834
835     if need_invoke(bcx) {
836         unsafe {
837             debug!("invoking %x at %x",
838                    ::std::cast::transmute(llfn),
839                    ::std::cast::transmute(bcx.llbb));
840             for &llarg in llargs.iter() {
841                 debug!("arg: %x", ::std::cast::transmute(llarg));
842             }
843         }
844         let normal_bcx = sub_block(bcx, "normal return");
845         let llresult = Invoke(bcx,
846                               llfn,
847                               llargs,
848                               normal_bcx.llbb,
849                               get_landing_pad(bcx));
850         return (llresult, normal_bcx);
851     } else {
852         unsafe {
853             debug!("calling %x at %x",
854                    ::std::cast::transmute(llfn),
855                    ::std::cast::transmute(bcx.llbb));
856             for &llarg in llargs.iter() {
857                 debug!("arg: %x", ::std::cast::transmute(llarg));
858             }
859         }
860         let llresult = Call(bcx, llfn, llargs);
861         return (llresult, bcx);
862     }
863 }
864
865 pub fn need_invoke(bcx: @mut Block) -> bool {
866     if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
867         return false;
868     }
869
870     // Avoid using invoke if we are already inside a landing pad.
871     if bcx.is_lpad {
872         return false;
873     }
874
875     if have_cached_lpad(bcx) {
876         return true;
877     }
878
879     // Walk the scopes to look for cleanups
880     let mut cur = bcx;
881     let mut cur_scope = cur.scope;
882     loop {
883         cur_scope = match cur_scope {
884             Some(inf) => {
885                 for cleanup in inf.cleanups.iter() {
886                     match *cleanup {
887                         clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
888                             if cleanup_type == normal_exit_and_unwind {
889                                 return true;
890                             }
891                         }
892                     }
893                 }
894                 inf.parent
895             }
896             None => {
897                 cur = match cur.parent {
898                     Some(next) => next,
899                     None => return false
900                 };
901                 cur.scope
902             }
903         }
904     }
905 }
906
907 pub fn have_cached_lpad(bcx: @mut Block) -> bool {
908     let mut res = false;
909     do in_lpad_scope_cx(bcx) |inf| {
910         match inf.landing_pad {
911           Some(_) => res = true,
912           None => res = false
913         }
914     }
915     return res;
916 }
917
918 pub fn in_lpad_scope_cx(bcx: @mut Block, f: &fn(si: &mut ScopeInfo)) {
919     let mut bcx = bcx;
920     let mut cur_scope = bcx.scope;
921     loop {
922         cur_scope = match cur_scope {
923             Some(inf) => {
924                 if !inf.empty_cleanups() || (inf.parent.is_none() && bcx.parent.is_none()) {
925                     f(inf);
926                     return;
927                 }
928                 inf.parent
929             }
930             None => {
931                 bcx = block_parent(bcx);
932                 bcx.scope
933             }
934         }
935     }
936 }
937
938 pub fn get_landing_pad(bcx: @mut Block) -> BasicBlockRef {
939     let _icx = push_ctxt("get_landing_pad");
940
941     let mut cached = None;
942     let mut pad_bcx = bcx; // Guaranteed to be set below
943     do in_lpad_scope_cx(bcx) |inf| {
944         // If there is a valid landing pad still around, use it
945         match inf.landing_pad {
946           Some(target) => cached = Some(target),
947           None => {
948             pad_bcx = lpad_block(bcx, "unwind");
949             inf.landing_pad = Some(pad_bcx.llbb);
950           }
951         }
952     }
953     // Can't return from block above
954     match cached { Some(b) => return b, None => () }
955     // The landing pad return type (the type being propagated). Not sure what
956     // this represents but it's determined by the personality function and
957     // this is what the EH proposal example uses.
958     let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
959     // The exception handling personality function. This is the C++
960     // personality function __gxx_personality_v0, wrapped in our naming
961     // convention.
962     let personality = bcx.ccx().upcalls.rust_personality;
963     // The only landing pad clause will be 'cleanup'
964     let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
965     // The landing pad block is a cleanup
966     SetCleanup(pad_bcx, llretval);
967
968     // Because we may have unwound across a stack boundary, we must call into
969     // the runtime to figure out which stack segment we are on and place the
970     // stack limit back into the TLS.
971     Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, []);
972
973     // We store the retval in a function-central alloca, so that calls to
974     // Resume can find it.
975     match bcx.fcx.personality {
976       Some(addr) => Store(pad_bcx, llretval, addr),
977       None => {
978         let addr = alloca(pad_bcx, val_ty(llretval), "");
979         bcx.fcx.personality = Some(addr);
980         Store(pad_bcx, llretval, addr);
981       }
982     }
983
984     // Unwind all parent scopes, and finish with a Resume instr
985     cleanup_and_leave(pad_bcx, None, None);
986     return pad_bcx.llbb;
987 }
988
989 pub fn find_bcx_for_scope(bcx: @mut Block, scope_id: ast::NodeId) -> @mut Block {
990     let mut bcx_sid = bcx;
991     let mut cur_scope = bcx_sid.scope;
992     loop {
993         cur_scope = match cur_scope {
994             Some(inf) => {
995                 match inf.node_info {
996                     Some(NodeInfo { id, _ }) if id == scope_id => {
997                         return bcx_sid
998                     }
999                     // FIXME(#6268, #6248) hacky cleanup for nested method calls
1000                     Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
1001                         return bcx_sid
1002                     }
1003                     _ => inf.parent
1004                 }
1005             }
1006             None => {
1007                 bcx_sid = match bcx_sid.parent {
1008                     None => bcx.tcx().sess.bug(fmt!("no enclosing scope with id %d", scope_id)),
1009                     Some(bcx_par) => bcx_par
1010                 };
1011                 bcx_sid.scope
1012             }
1013         }
1014     }
1015 }
1016
1017
1018 pub fn do_spill(bcx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1019     if ty::type_is_bot(t) {
1020         return C_null(Type::i8p());
1021     }
1022     let llptr = alloc_ty(bcx, t, "");
1023     Store(bcx, v, llptr);
1024     return llptr;
1025 }
1026
1027 // Since this function does *not* root, it is the caller's responsibility to
1028 // ensure that the referent is pointed to by a root.
1029 pub fn do_spill_noroot(cx: @mut Block, v: ValueRef) -> ValueRef {
1030     let llptr = alloca(cx, val_ty(v), "");
1031     Store(cx, v, llptr);
1032     return llptr;
1033 }
1034
1035 pub fn spill_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1036     let _icx = push_ctxt("spill_if_immediate");
1037     if ty::type_is_immediate(cx.tcx(), t) { return do_spill(cx, v, t); }
1038     return v;
1039 }
1040
1041 pub fn load_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1042     let _icx = push_ctxt("load_if_immediate");
1043     if ty::type_is_immediate(cx.tcx(), t) { return Load(cx, v); }
1044     return v;
1045 }
1046
1047 pub fn trans_trace(bcx: @mut Block, sp_opt: Option<span>, trace_str: @str) {
1048     if !bcx.sess().trace() { return; }
1049     let _icx = push_ctxt("trans_trace");
1050     add_comment(bcx, trace_str);
1051     let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1052     let (V_filename, V_line) = match sp_opt {
1053       Some(sp) => {
1054         let sess = bcx.sess();
1055         let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1056         (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1057       }
1058       None => {
1059         (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1060       }
1061     };
1062     let ccx = bcx.ccx();
1063     let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1064     let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1065     let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1066     Call(bcx, ccx.upcalls.trace, args);
1067 }
1068
1069 pub fn ignore_lhs(_bcx: @mut Block, local: &ast::Local) -> bool {
1070     match local.pat.node {
1071         ast::pat_wild => true, _ => false
1072     }
1073 }
1074
1075 pub fn init_local(bcx: @mut Block, local: &ast::Local) -> @mut Block {
1076
1077     debug!("init_local(bcx=%s, local.id=%?)",
1078            bcx.to_str(), local.id);
1079     let _indenter = indenter();
1080
1081     let _icx = push_ctxt("init_local");
1082
1083     if ignore_lhs(bcx, local) {
1084         // Handle let _ = e; just like e;
1085         match local.init {
1086             Some(init) => {
1087               return expr::trans_into(bcx, init, expr::Ignore);
1088             }
1089             None => { return bcx; }
1090         }
1091     }
1092
1093     _match::store_local(bcx, local.pat, local.init)
1094 }
1095
1096 pub fn trans_stmt(cx: @mut Block, s: &ast::stmt) -> @mut Block {
1097     let _icx = push_ctxt("trans_stmt");
1098     debug!("trans_stmt(%s)", stmt_to_str(s, cx.tcx().sess.intr()));
1099
1100     if cx.sess().asm_comments() {
1101         add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1102     }
1103
1104     let mut bcx = cx;
1105     debuginfo::update_source_pos(cx, s.span);
1106
1107     match s.node {
1108         ast::stmt_expr(e, _) | ast::stmt_semi(e, _) => {
1109             bcx = expr::trans_into(cx, e, expr::Ignore);
1110         }
1111         ast::stmt_decl(d, _) => {
1112             match d.node {
1113                 ast::decl_local(ref local) => {
1114                     bcx = init_local(bcx, *local);
1115                     if cx.sess().opts.extra_debuginfo
1116                         && fcx_has_nonzero_span(bcx.fcx) {
1117                         debuginfo::create_local_var_metadata(bcx, *local);
1118                     }
1119                 }
1120                 ast::decl_item(i) => trans_item(cx.fcx.ccx, i)
1121             }
1122         }
1123         ast::stmt_mac(*) => cx.tcx().sess.bug("unexpanded macro")
1124     }
1125
1126     return bcx;
1127 }
1128
1129 // You probably don't want to use this one. See the
1130 // next three functions instead.
1131 pub fn new_block(cx: @mut FunctionContext,
1132                  parent: Option<@mut Block>,
1133                  scope: Option<@mut ScopeInfo>,
1134                  is_lpad: bool,
1135                  name: &str,
1136                  opt_node_info: Option<NodeInfo>)
1137               -> @mut Block {
1138     unsafe {
1139         let llbb = do name.to_c_str().with_ref |buf| {
1140             llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1141         };
1142         let bcx = @mut Block::new(llbb,
1143                                   parent,
1144                                   is_lpad,
1145                                   opt_node_info,
1146                                   cx);
1147         bcx.scope = scope;
1148         for cx in parent.iter() {
1149             if cx.unreachable {
1150                 Unreachable(bcx);
1151                 break;
1152             }
1153         }
1154         bcx
1155     }
1156 }
1157
1158 pub fn simple_block_scope(parent: Option<@mut ScopeInfo>,
1159                           node_info: Option<NodeInfo>) -> @mut ScopeInfo {
1160     @mut ScopeInfo {
1161         parent: parent,
1162         loop_break: None,
1163         loop_label: None,
1164         cleanups: ~[],
1165         cleanup_paths: ~[],
1166         landing_pad: None,
1167         node_info: node_info,
1168     }
1169 }
1170
1171 // Use this when you're at the top block of a function or the like.
1172 pub fn top_scope_block(fcx: @mut FunctionContext, opt_node_info: Option<NodeInfo>)
1173                     -> @mut Block {
1174     return new_block(fcx, None, Some(simple_block_scope(None, opt_node_info)), false,
1175                   "function top level", opt_node_info);
1176 }
1177
1178 pub fn scope_block(bcx: @mut Block,
1179                    opt_node_info: Option<NodeInfo>,
1180                    n: &str) -> @mut Block {
1181     return new_block(bcx.fcx, Some(bcx), Some(simple_block_scope(None, opt_node_info)), bcx.is_lpad,
1182                   n, opt_node_info);
1183 }
1184
1185 pub fn loop_scope_block(bcx: @mut Block,
1186                         loop_break: @mut Block,
1187                         loop_label: Option<ident>,
1188                         n: &str,
1189                         opt_node_info: Option<NodeInfo>) -> @mut Block {
1190     return new_block(bcx.fcx, Some(bcx), Some(@mut ScopeInfo {
1191         parent: None,
1192         loop_break: Some(loop_break),
1193         loop_label: loop_label,
1194         cleanups: ~[],
1195         cleanup_paths: ~[],
1196         landing_pad: None,
1197         node_info: opt_node_info,
1198     }), bcx.is_lpad, n, opt_node_info);
1199 }
1200
1201 // Use this when creating a block for the inside of a landing pad.
1202 pub fn lpad_block(bcx: @mut Block, n: &str) -> @mut Block {
1203     new_block(bcx.fcx, Some(bcx), None, true, n, None)
1204 }
1205
1206 // Use this when you're making a general CFG BB within a scope.
1207 pub fn sub_block(bcx: @mut Block, n: &str) -> @mut Block {
1208     new_block(bcx.fcx, Some(bcx), None, bcx.is_lpad, n, None)
1209 }
1210
1211 pub fn raw_block(fcx: @mut FunctionContext, is_lpad: bool, llbb: BasicBlockRef) -> @mut Block {
1212     @mut Block::new(llbb, None, is_lpad, None, fcx)
1213 }
1214
1215
1216 // trans_block_cleanups: Go through all the cleanups attached to this
1217 // block and execute them.
1218 //
1219 // When translating a block that introduces new variables during its scope, we
1220 // need to make sure those variables go out of scope when the block ends.  We
1221 // do that by running a 'cleanup' function for each variable.
1222 // trans_block_cleanups runs all the cleanup functions for the block.
1223 pub fn trans_block_cleanups(bcx: @mut Block, cleanups: ~[cleanup]) -> @mut Block {
1224     trans_block_cleanups_(bcx, cleanups, false)
1225 }
1226
1227 pub fn trans_block_cleanups_(bcx: @mut Block,
1228                              cleanups: &[cleanup],
1229                              /* cleanup_cx: block, */
1230                              is_lpad: bool) -> @mut Block {
1231     let _icx = push_ctxt("trans_block_cleanups");
1232     // NB: Don't short-circuit even if this block is unreachable because
1233     // GC-based cleanup needs to the see that the roots are live.
1234     let no_lpads =
1235         bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1236     if bcx.unreachable && !no_lpads { return bcx; }
1237     let mut bcx = bcx;
1238     for cu in cleanups.rev_iter() {
1239         match *cu {
1240             clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1241                 // Some types don't need to be cleaned up during
1242                 // landing pads because they can be freed en mass later
1243                 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1244                     bcx = cfn(bcx);
1245                 }
1246             }
1247         }
1248     }
1249     return bcx;
1250 }
1251
1252 // In the last argument, Some(block) mean jump to this block, and none means
1253 // this is a landing pad and leaving should be accomplished with a resume
1254 // instruction.
1255 pub fn cleanup_and_leave(bcx: @mut Block,
1256                          upto: Option<BasicBlockRef>,
1257                          leave: Option<BasicBlockRef>) {
1258     let _icx = push_ctxt("cleanup_and_leave");
1259     let mut cur = bcx;
1260     let mut bcx = bcx;
1261     let is_lpad = leave == None;
1262     loop {
1263         debug!("cleanup_and_leave: leaving %s", cur.to_str());
1264
1265         if bcx.sess().trace() {
1266             trans_trace(
1267                 bcx, None,
1268                 (fmt!("cleanup_and_leave(%s)", cur.to_str())).to_managed());
1269         }
1270
1271         let mut cur_scope = cur.scope;
1272         loop {
1273             cur_scope = match cur_scope {
1274                 Some (inf) if !inf.empty_cleanups() => {
1275                     let (sub_cx, dest, inf_cleanups) = {
1276                         let inf = &mut *inf;
1277                         let mut skip = 0;
1278                         let mut dest = None;
1279                         {
1280                             let r = (*inf).cleanup_paths.rev_iter().find_(|cp| cp.target == leave);
1281                             for cp in r.iter() {
1282                                 if cp.size == inf.cleanups.len() {
1283                                     Br(bcx, cp.dest);
1284                                     return;
1285                                 }
1286
1287                                 skip = cp.size;
1288                                 dest = Some(cp.dest);
1289                             }
1290                         }
1291                         let sub_cx = sub_block(bcx, "cleanup");
1292                         Br(bcx, sub_cx.llbb);
1293                         inf.cleanup_paths.push(cleanup_path {
1294                             target: leave,
1295                             size: inf.cleanups.len(),
1296                             dest: sub_cx.llbb
1297                         });
1298                         (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1299                     };
1300                     bcx = trans_block_cleanups_(sub_cx,
1301                                                 inf_cleanups,
1302                                                 is_lpad);
1303                     for &dest in dest.iter() {
1304                         Br(bcx, dest);
1305                         return;
1306                     }
1307                     inf.parent
1308                 }
1309                 Some(inf) => inf.parent,
1310                 None => break
1311             }
1312         }
1313
1314         match upto {
1315           Some(bb) => { if cur.llbb == bb { break; } }
1316           _ => ()
1317         }
1318         cur = match cur.parent {
1319           Some(next) => next,
1320           None => { assert!(upto.is_none()); break; }
1321         };
1322     }
1323     match leave {
1324       Some(target) => Br(bcx, target),
1325       None => { Resume(bcx, Load(bcx, bcx.fcx.personality.get())); }
1326     }
1327 }
1328
1329 pub fn cleanup_block(bcx: @mut Block, upto: Option<BasicBlockRef>) -> @mut Block{
1330     let _icx = push_ctxt("cleanup_block");
1331     let mut cur = bcx;
1332     let mut bcx = bcx;
1333     loop {
1334         debug!("cleanup_block: %s", cur.to_str());
1335
1336         if bcx.sess().trace() {
1337             trans_trace(
1338                 bcx, None,
1339                 (fmt!("cleanup_block(%s)", cur.to_str())).to_managed());
1340         }
1341
1342         let mut cur_scope = cur.scope;
1343         loop {
1344             cur_scope = match cur_scope {
1345                 Some (inf) => {
1346                     bcx = trans_block_cleanups_(bcx, inf.cleanups.to_owned(), false);
1347                     inf.parent
1348                 }
1349                 None => break
1350             }
1351         }
1352
1353         match upto {
1354           Some(bb) => { if cur.llbb == bb { break; } }
1355           _ => ()
1356         }
1357         cur = match cur.parent {
1358           Some(next) => next,
1359           None => { assert!(upto.is_none()); break; }
1360         };
1361     }
1362     bcx
1363 }
1364
1365 pub fn cleanup_and_Br(bcx: @mut Block, upto: @mut Block, target: BasicBlockRef) {
1366     let _icx = push_ctxt("cleanup_and_Br");
1367     cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1368 }
1369
1370 pub fn leave_block(bcx: @mut Block, out_of: @mut Block) -> @mut Block {
1371     let _icx = push_ctxt("leave_block");
1372     let next_cx = sub_block(block_parent(out_of), "next");
1373     if bcx.unreachable { Unreachable(next_cx); }
1374     cleanup_and_Br(bcx, out_of, next_cx.llbb);
1375     next_cx
1376 }
1377
1378 pub fn with_scope(bcx: @mut Block,
1379                   opt_node_info: Option<NodeInfo>,
1380                   name: &str,
1381                   f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1382     let _icx = push_ctxt("with_scope");
1383
1384     debug!("with_scope(bcx=%s, opt_node_info=%?, name=%s)",
1385            bcx.to_str(), opt_node_info, name);
1386     let _indenter = indenter();
1387
1388     let scope = simple_block_scope(bcx.scope, opt_node_info);
1389     bcx.scope = Some(scope);
1390     let ret = f(bcx);
1391     let ret = trans_block_cleanups_(ret, (scope.cleanups).clone(), false);
1392     bcx.scope = scope.parent;
1393     ret
1394 }
1395
1396 pub fn with_scope_result(bcx: @mut Block,
1397                          opt_node_info: Option<NodeInfo>,
1398                          _name: &str,
1399                          f: &fn(@mut Block) -> Result) -> Result {
1400     let _icx = push_ctxt("with_scope_result");
1401
1402     let scope = simple_block_scope(bcx.scope, opt_node_info);
1403     bcx.scope = Some(scope);
1404     let Result { bcx: out_bcx, val } = f(bcx);
1405     let out_bcx = trans_block_cleanups_(out_bcx,
1406                                         (scope.cleanups).clone(),
1407                                         false);
1408     bcx.scope = scope.parent;
1409
1410     rslt(out_bcx, val)
1411 }
1412
1413 pub fn with_scope_datumblock(bcx: @mut Block, opt_node_info: Option<NodeInfo>,
1414                              name: &str, f: &fn(@mut Block) -> datum::DatumBlock)
1415                           -> datum::DatumBlock {
1416     use middle::trans::datum::DatumBlock;
1417
1418     let _icx = push_ctxt("with_scope_result");
1419     let scope_cx = scope_block(bcx, opt_node_info, name);
1420     Br(bcx, scope_cx.llbb);
1421     let DatumBlock {bcx, datum} = f(scope_cx);
1422     DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1423 }
1424
1425 pub fn block_locals(b: &ast::Block, it: &fn(@ast::Local)) {
1426     for s in b.stmts.iter() {
1427         match s.node {
1428           ast::stmt_decl(d, _) => {
1429             match d.node {
1430               ast::decl_local(ref local) => it(*local),
1431               _ => {} /* fall through */
1432             }
1433           }
1434           _ => {} /* fall through */
1435         }
1436     }
1437 }
1438
1439 pub fn with_cond(bcx: @mut Block, val: ValueRef, f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1440     let _icx = push_ctxt("with_cond");
1441     let next_cx = base::sub_block(bcx, "next");
1442     let cond_cx = base::sub_block(bcx, "cond");
1443     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1444     let after_cx = f(cond_cx);
1445     if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1446     next_cx
1447 }
1448
1449 pub fn call_memcpy(cx: @mut Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1450     let _icx = push_ctxt("call_memcpy");
1451     let ccx = cx.ccx();
1452     let key = match ccx.sess.targ_cfg.arch {
1453         X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1454         X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1455     };
1456     let memcpy = ccx.intrinsics.get_copy(&key);
1457     let src_ptr = PointerCast(cx, src, Type::i8p());
1458     let dst_ptr = PointerCast(cx, dst, Type::i8p());
1459     let size = IntCast(cx, n_bytes, ccx.int_type);
1460     let align = C_i32(align as i32);
1461     let volatile = C_i1(false);
1462     Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile]);
1463 }
1464
1465 pub fn memcpy_ty(bcx: @mut Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1466     let _icx = push_ctxt("memcpy_ty");
1467     let ccx = bcx.ccx();
1468     if ty::type_is_structural(t) {
1469         let llty = type_of::type_of(ccx, t);
1470         let llsz = llsize_of(ccx, llty);
1471         let llalign = llalign_of_min(ccx, llty);
1472         call_memcpy(bcx, dst, src, llsz, llalign as u32);
1473     } else {
1474         Store(bcx, Load(bcx, src), dst);
1475     }
1476 }
1477
1478 pub fn zero_mem(cx: @mut Block, llptr: ValueRef, t: ty::t) {
1479     if cx.unreachable { return; }
1480     let _icx = push_ctxt("zero_mem");
1481     let bcx = cx;
1482     let ccx = cx.ccx();
1483     let llty = type_of::type_of(ccx, t);
1484     memzero(&B(bcx), llptr, llty);
1485 }
1486
1487 // Always use this function instead of storing a zero constant to the memory
1488 // in question. If you store a zero constant, LLVM will drown in vreg
1489 // allocation for large data structures, and the generated code will be
1490 // awful. (A telltale sign of this is large quantities of
1491 // `mov [byte ptr foo],0` in the generated code.)
1492 pub fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1493     let _icx = push_ctxt("memzero");
1494     let ccx = b.ccx;
1495
1496     let intrinsic_key = match ccx.sess.targ_cfg.arch {
1497         X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1498         X86_64 => "llvm.memset.p0i8.i64"
1499     };
1500
1501     let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1502     let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1503     let llzeroval = C_u8(0);
1504     let size = machine::llsize_of(ccx, ty);
1505     let align = C_i32(llalign_of_min(ccx, ty) as i32);
1506     let volatile = C_i1(false);
1507     b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile]);
1508 }
1509
1510 pub fn alloc_ty(bcx: @mut Block, t: ty::t, name: &str) -> ValueRef {
1511     let _icx = push_ctxt("alloc_ty");
1512     let ccx = bcx.ccx();
1513     let ty = type_of::type_of(ccx, t);
1514     assert!(!ty::type_has_params(t), "Type has params: %s", ty_to_str(ccx.tcx, t));
1515     let val = alloca(bcx, ty, name);
1516     return val;
1517 }
1518
1519 pub fn alloca(cx: @mut Block, ty: Type, name: &str) -> ValueRef {
1520     alloca_maybe_zeroed(cx, ty, name, false)
1521 }
1522
1523 pub fn alloca_maybe_zeroed(cx: @mut Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1524     let _icx = push_ctxt("alloca");
1525     if cx.unreachable {
1526         unsafe {
1527             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1528         }
1529     }
1530     let p = Alloca(cx, ty, name);
1531     if zero {
1532         let b = cx.fcx.ccx.builder();
1533         b.position_before(cx.fcx.alloca_insert_pt.get());
1534         memzero(&b, p, ty);
1535     }
1536     p
1537 }
1538
1539 pub fn arrayalloca(cx: @mut Block, ty: Type, v: ValueRef) -> ValueRef {
1540     let _icx = push_ctxt("arrayalloca");
1541     if cx.unreachable {
1542         unsafe {
1543             return llvm::LLVMGetUndef(ty.to_ref());
1544         }
1545     }
1546     return ArrayAlloca(cx, ty, v);
1547 }
1548
1549 pub struct BasicBlocks {
1550     sa: BasicBlockRef,
1551 }
1552
1553 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1554     unsafe {
1555         let cx = task_llcx();
1556         do "static_allocas".to_c_str().with_ref | buf| {
1557             llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1558         }
1559     }
1560 }
1561
1562 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1563     unsafe {
1564         let cx = task_llcx();
1565         do "return".to_c_str().with_ref |buf| {
1566             llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1567         }
1568     }
1569 }
1570
1571 // Creates and returns space for, or returns the argument representing, the
1572 // slot where the return value of the function must go.
1573 pub fn make_return_pointer(fcx: @mut FunctionContext, output_type: ty::t) -> ValueRef {
1574     unsafe {
1575         if !ty::type_is_immediate(fcx.ccx.tcx, output_type) {
1576             llvm::LLVMGetParam(fcx.llfn, 0)
1577         } else {
1578             let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1579             let bcx = fcx.entry_bcx.get();
1580             Alloca(bcx, lloutputtype, "__make_return_pointer")
1581         }
1582     }
1583 }
1584
1585 // NB: must keep 4 fns in sync:
1586 //
1587 //  - type_of_fn
1588 //  - create_llargs_for_fn_args.
1589 //  - new_fn_ctxt
1590 //  - trans_args
1591 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1592                         path: path,
1593                         llfndecl: ValueRef,
1594                         id: ast::NodeId,
1595                         output_type: ty::t,
1596                         skip_retptr: bool,
1597                         param_substs: Option<@param_substs>,
1598                         opt_node_info: Option<NodeInfo>,
1599                         sp: Option<span>)
1600                      -> @mut FunctionContext {
1601     for p in param_substs.iter() { p.validate(); }
1602
1603     debug!("new_fn_ctxt_w_id(path=%s, id=%?, \
1604             param_substs=%s)",
1605            path_str(ccx.sess, path),
1606            id,
1607            param_substs.repr(ccx.tcx));
1608
1609     let substd_output_type = match param_substs {
1610         None => output_type,
1611         Some(substs) => {
1612             ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1613         }
1614     };
1615     let is_immediate = ty::type_is_immediate(ccx.tcx, substd_output_type);
1616     let fcx = @mut FunctionContext {
1617           llfn: llfndecl,
1618           llenv: unsafe {
1619               llvm::LLVMGetUndef(Type::i8p().to_ref())
1620           },
1621           llretptr: None,
1622           entry_bcx: None,
1623           alloca_insert_pt: None,
1624           llreturn: None,
1625           llself: None,
1626           personality: None,
1627           loop_ret: None,
1628           has_immediate_return_value: is_immediate,
1629           llargs: @mut HashMap::new(),
1630           lllocals: @mut HashMap::new(),
1631           llupvars: @mut HashMap::new(),
1632           id: id,
1633           param_substs: param_substs,
1634           span: sp,
1635           path: path,
1636           ccx: ccx
1637     };
1638     fcx.llenv = unsafe {
1639           llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1640     };
1641
1642     unsafe {
1643         let entry_bcx = top_scope_block(fcx, opt_node_info);
1644         Load(entry_bcx, C_null(Type::i8p()));
1645
1646         fcx.entry_bcx = Some(entry_bcx);
1647         fcx.alloca_insert_pt = Some(llvm::LLVMGetFirstInstruction(entry_bcx.llbb));
1648     }
1649
1650     if !ty::type_is_nil(substd_output_type) && !(is_immediate && skip_retptr) {
1651         fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1652     }
1653     fcx
1654 }
1655
1656 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1657                    path: path,
1658                    llfndecl: ValueRef,
1659                    output_type: ty::t,
1660                    sp: Option<span>)
1661                 -> @mut FunctionContext {
1662     new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, false, None, None, sp)
1663 }
1664
1665 // NB: must keep 4 fns in sync:
1666 //
1667 //  - type_of_fn
1668 //  - create_llargs_for_fn_args.
1669 //  - new_fn_ctxt
1670 //  - trans_args
1671
1672 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1673 // allocas created for them.
1674 //
1675 // When we translate a function, we need to map its incoming arguments to the
1676 // spaces that have been created for them (by code in the llallocas field of
1677 // the function's fn_ctxt).  create_llargs_for_fn_args populates the llargs
1678 // field of the fn_ctxt with
1679 pub fn create_llargs_for_fn_args(cx: @mut FunctionContext,
1680                                  self_arg: self_arg,
1681                                  args: &[ast::arg])
1682                               -> ~[ValueRef] {
1683     let _icx = push_ctxt("create_llargs_for_fn_args");
1684
1685     match self_arg {
1686       impl_self(tt, self_mode) => {
1687         cx.llself = Some(ValSelfData {
1688             v: cx.llenv,
1689             t: tt,
1690             is_copy: self_mode == ty::ByCopy
1691         });
1692       }
1693       no_self => ()
1694     }
1695
1696     // Return an array containing the ValueRefs that we get from
1697     // llvm::LLVMGetParam for each argument.
1698     vec::from_fn(args.len(), |i| {
1699         unsafe {
1700             let arg_n = cx.arg_pos(i);
1701             let arg = &args[i];
1702             let llarg = llvm::LLVMGetParam(cx.llfn, arg_n as c_uint);
1703
1704             // FIXME #7260: aliasing should be determined by monomorphized ty::t
1705             match arg.ty.node {
1706                 // `~` pointers never alias other parameters, because ownership was transferred
1707                 ast::ty_uniq(_) => {
1708                     llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
1709                 }
1710                 // FIXME: #6785: `&mut` can only alias `&const` and `@mut`, we should check for
1711                 // those in the other parameters and then mark it as `noalias` if there aren't any
1712                 _ => {}
1713             }
1714
1715             llarg
1716         }
1717     })
1718 }
1719
1720 pub fn copy_args_to_allocas(fcx: @mut FunctionContext,
1721                             bcx: @mut Block,
1722                             args: &[ast::arg],
1723                             raw_llargs: &[ValueRef],
1724                             arg_tys: &[ty::t]) -> @mut Block {
1725     let _icx = push_ctxt("copy_args_to_allocas");
1726     let mut bcx = bcx;
1727
1728     match fcx.llself {
1729         Some(slf) => {
1730             let self_val = if slf.is_copy
1731                     && datum::appropriate_mode(bcx.tcx(), slf.t).is_by_value() {
1732                 let tmp = BitCast(bcx, slf.v, type_of(bcx.ccx(), slf.t));
1733                 let alloc = alloc_ty(bcx, slf.t, "__self");
1734                 Store(bcx, tmp, alloc);
1735                 alloc
1736             } else {
1737                 PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to())
1738             };
1739
1740             fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1741             add_clean(bcx, self_val, slf.t);
1742         }
1743         _ => {}
1744     }
1745
1746     for arg_n in range(0u, arg_tys.len()) {
1747         let arg_ty = arg_tys[arg_n];
1748         let raw_llarg = raw_llargs[arg_n];
1749
1750         // For certain mode/type combinations, the raw llarg values are passed
1751         // by value.  However, within the fn body itself, we want to always
1752         // have all locals and arguments be by-ref so that we can cancel the
1753         // cleanup and for better interaction with LLVM's debug info.  So, if
1754         // the argument would be passed by value, we store it into an alloca.
1755         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1756         // the event it's not truly needed.
1757         // only by value if immediate:
1758         let llarg = if datum::appropriate_mode(bcx.tcx(), arg_ty).is_by_value() {
1759             let alloc = alloc_ty(bcx, arg_ty, "__arg");
1760             Store(bcx, raw_llarg, alloc);
1761             alloc
1762         } else {
1763             raw_llarg
1764         };
1765         bcx = _match::store_arg(bcx, args[arg_n].pat, llarg);
1766
1767         if fcx.ccx.sess.opts.extra_debuginfo && fcx_has_nonzero_span(fcx) {
1768             debuginfo::create_argument_metadata(bcx, &args[arg_n]);
1769         }
1770     }
1771
1772     return bcx;
1773 }
1774
1775 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1776 // and builds the return block.
1777 pub fn finish_fn(fcx: @mut FunctionContext, last_bcx: @mut Block) {
1778     let _icx = push_ctxt("finish_fn");
1779
1780     let ret_cx = match fcx.llreturn {
1781         Some(llreturn) => {
1782             if !last_bcx.terminated {
1783                 Br(last_bcx, llreturn);
1784             }
1785             raw_block(fcx, false, llreturn)
1786         }
1787         None => last_bcx
1788     };
1789     build_return_block(fcx, ret_cx);
1790     fcx.cleanup();
1791 }
1792
1793 // Builds the return block for a function.
1794 pub fn build_return_block(fcx: &FunctionContext, ret_cx: @mut Block) {
1795     // Return the value if this function immediate; otherwise, return void.
1796     if fcx.llretptr.is_some() && fcx.has_immediate_return_value {
1797         Ret(ret_cx, Load(ret_cx, fcx.llretptr.get()))
1798     } else {
1799         RetVoid(ret_cx)
1800     }
1801 }
1802
1803 pub enum self_arg { impl_self(ty::t, ty::SelfMode), no_self, }
1804
1805 // trans_closure: Builds an LLVM function out of a source function.
1806 // If the function closes over its environment a closure will be
1807 // returned.
1808 pub fn trans_closure(ccx: @mut CrateContext,
1809                      path: path,
1810                      decl: &ast::fn_decl,
1811                      body: &ast::Block,
1812                      llfndecl: ValueRef,
1813                      self_arg: self_arg,
1814                      param_substs: Option<@param_substs>,
1815                      id: ast::NodeId,
1816                      attributes: &[ast::Attribute],
1817                      output_type: ty::t,
1818                      maybe_load_env: &fn(@mut FunctionContext),
1819                      finish: &fn(@mut Block)) {
1820     ccx.stats.n_closures += 1;
1821     let _icx = push_ctxt("trans_closure");
1822     set_uwtable(llfndecl);
1823
1824     debug!("trans_closure(..., param_substs=%s)",
1825            param_substs.repr(ccx.tcx));
1826
1827     // Set up arguments to the function.
1828     let fcx = new_fn_ctxt_w_id(ccx,
1829                                path,
1830                                llfndecl,
1831                                id,
1832                                output_type,
1833                                false,
1834                                param_substs,
1835                                body.info(),
1836                                Some(body.span));
1837     let raw_llargs = create_llargs_for_fn_args(fcx, self_arg, decl.inputs);
1838
1839     // Set the fixed stack segment flag if necessary.
1840     if attr::contains_name(attributes, "fixed_stack_segment") {
1841         set_no_inline(fcx.llfn);
1842         set_fixed_stack_segment(fcx.llfn);
1843     }
1844
1845     // Create the first basic block in the function and keep a handle on it to
1846     //  pass to finish_fn later.
1847     let bcx_top = fcx.entry_bcx.get();
1848     let mut bcx = bcx_top;
1849     let block_ty = node_id_type(bcx, body.id);
1850
1851     let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1852     bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1853
1854     maybe_load_env(fcx);
1855
1856     // This call to trans_block is the place where we bridge between
1857     // translation calls that don't have a return value (trans_crate,
1858     // trans_mod, trans_item, et cetera) and those that do
1859     // (trans_block, trans_expr, et cetera).
1860     if body.expr.is_none() || ty::type_is_bot(block_ty) ||
1861         ty::type_is_nil(block_ty)
1862     {
1863         bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1864     } else {
1865         let dest = expr::SaveIn(fcx.llretptr.get());
1866         bcx = controlflow::trans_block(bcx, body, dest);
1867     }
1868
1869     finish(bcx);
1870     match fcx.llreturn {
1871         Some(llreturn) => cleanup_and_Br(bcx, bcx_top, llreturn),
1872         None => bcx = cleanup_block(bcx, Some(bcx_top.llbb))
1873     };
1874
1875     // Put return block after all other blocks.
1876     // This somewhat improves single-stepping experience in debugger.
1877     unsafe {
1878         for &llreturn in fcx.llreturn.iter() {
1879             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1880         }
1881     }
1882
1883     // Insert the mandatory first few basic blocks before lltop.
1884     finish_fn(fcx, bcx);
1885 }
1886
1887 // trans_fn: creates an LLVM function corresponding to a source language
1888 // function.
1889 pub fn trans_fn(ccx: @mut CrateContext,
1890                 path: path,
1891                 decl: &ast::fn_decl,
1892                 body: &ast::Block,
1893                 llfndecl: ValueRef,
1894                 self_arg: self_arg,
1895                 param_substs: Option<@param_substs>,
1896                 id: ast::NodeId,
1897                 attrs: &[ast::Attribute]) {
1898
1899     let the_path_str = path_str(ccx.sess, path);
1900     let _s = StatRecorder::new(ccx, the_path_str);
1901     debug!("trans_fn(self_arg=%?, param_substs=%s)",
1902            self_arg,
1903            param_substs.repr(ccx.tcx));
1904     let _icx = push_ctxt("trans_fn");
1905     let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1906     trans_closure(ccx,
1907                   path.clone(),
1908                   decl,
1909                   body,
1910                   llfndecl,
1911                   self_arg,
1912                   param_substs,
1913                   id,
1914                   attrs,
1915                   output_type,
1916                   |fcx| {
1917                       if ccx.sess.opts.extra_debuginfo
1918                           && fcx_has_nonzero_span(fcx) {
1919                           debuginfo::create_function_metadata(fcx);
1920                       }
1921                   },
1922                   |_bcx| { });
1923 }
1924
1925 fn insert_synthetic_type_entries(bcx: @mut Block,
1926                                  fn_args: &[ast::arg],
1927                                  arg_tys: &[ty::t])
1928 {
1929     /*!
1930      * For tuple-like structs and enum-variants, we generate
1931      * synthetic AST nodes for the arguments.  These have no types
1932      * in the type table and no entries in the moves table,
1933      * so the code in `copy_args_to_allocas` and `bind_irrefutable_pat`
1934      * gets upset. This hack of a function bridges the gap by inserting types.
1935      *
1936      * This feels horrible. I think we should just have a special path
1937      * for these functions and not try to use the generic code, but
1938      * that's not the problem I'm trying to solve right now. - nmatsakis
1939      */
1940
1941     let tcx = bcx.tcx();
1942     for i in range(0u, fn_args.len()) {
1943         debug!("setting type of argument %u (pat node %d) to %s",
1944                i, fn_args[i].pat.id, bcx.ty_to_str(arg_tys[i]));
1945
1946         let pat_id = fn_args[i].pat.id;
1947         let arg_ty = arg_tys[i];
1948         tcx.node_types.insert(pat_id as uint, arg_ty);
1949     }
1950 }
1951
1952 pub fn trans_enum_variant(ccx: @mut CrateContext,
1953                           _enum_id: ast::NodeId,
1954                           variant: &ast::variant,
1955                           args: &[ast::variant_arg],
1956                           disr: uint,
1957                           param_substs: Option<@param_substs>,
1958                           llfndecl: ValueRef) {
1959     let _icx = push_ctxt("trans_enum_variant");
1960
1961     trans_enum_variant_or_tuple_like_struct(
1962         ccx,
1963         variant.node.id,
1964         args,
1965         disr,
1966         param_substs,
1967         llfndecl);
1968 }
1969
1970 pub fn trans_tuple_struct(ccx: @mut CrateContext,
1971                           fields: &[@ast::struct_field],
1972                           ctor_id: ast::NodeId,
1973                           param_substs: Option<@param_substs>,
1974                           llfndecl: ValueRef) {
1975     let _icx = push_ctxt("trans_tuple_struct");
1976
1977     trans_enum_variant_or_tuple_like_struct(
1978         ccx,
1979         ctor_id,
1980         fields,
1981         0,
1982         param_substs,
1983         llfndecl);
1984 }
1985
1986 trait IdAndTy {
1987     fn id(&self) -> ast::NodeId;
1988     fn ty<'a>(&'a self) -> &'a ast::Ty;
1989 }
1990
1991 impl IdAndTy for ast::variant_arg {
1992     fn id(&self) -> ast::NodeId { self.id }
1993     fn ty<'a>(&'a self) -> &'a ast::Ty { &self.ty }
1994 }
1995
1996 impl IdAndTy for @ast::struct_field {
1997     fn id(&self) -> ast::NodeId { self.node.id }
1998     fn ty<'a>(&'a self) -> &'a ast::Ty { &self.node.ty }
1999 }
2000
2001 pub fn trans_enum_variant_or_tuple_like_struct<A:IdAndTy>(
2002     ccx: @mut CrateContext,
2003     ctor_id: ast::NodeId,
2004     args: &[A],
2005     disr: uint,
2006     param_substs: Option<@param_substs>,
2007     llfndecl: ValueRef)
2008 {
2009     // Translate variant arguments to function arguments.
2010     let fn_args = do args.map |varg| {
2011         ast::arg {
2012             is_mutbl: false,
2013             ty: (*varg.ty()).clone(),
2014             pat: ast_util::ident_to_pat(
2015                 ccx.tcx.sess.next_node_id(),
2016                 codemap::dummy_sp(),
2017                 special_idents::arg),
2018             id: varg.id(),
2019         }
2020     };
2021
2022     let no_substs: &[ty::t] = [];
2023     let ty_param_substs = match param_substs {
2024         Some(ref substs) => {
2025             let v: &[ty::t] = substs.tys;
2026             v
2027         }
2028         None => {
2029             let v: &[ty::t] = no_substs;
2030             v
2031         }
2032     };
2033
2034     let ctor_ty = ty::subst_tps(ccx.tcx,
2035                                 ty_param_substs,
2036                                 None,
2037                                 ty::node_id_to_type(ccx.tcx, ctor_id));
2038
2039     let result_ty = match ty::get(ctor_ty).sty {
2040         ty::ty_bare_fn(ref bft) => bft.sig.output,
2041         _ => ccx.sess.bug(
2042             fmt!("trans_enum_variant_or_tuple_like_struct: \
2043                   unexpected ctor return type %s",
2044                  ty_to_str(ccx.tcx, ctor_ty)))
2045     };
2046
2047     let fcx = new_fn_ctxt_w_id(ccx,
2048                                ~[],
2049                                llfndecl,
2050                                ctor_id,
2051                                result_ty,
2052                                false,
2053                                param_substs,
2054                                None,
2055                                None);
2056
2057     let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
2058
2059     let bcx = fcx.entry_bcx.get();
2060     let arg_tys = ty::ty_fn_args(ctor_ty);
2061
2062     insert_synthetic_type_entries(bcx, fn_args, arg_tys);
2063     let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2064
2065     let repr = adt::represent_type(ccx, result_ty);
2066     adt::trans_start_init(bcx, repr, fcx.llretptr.get(), disr);
2067     for (i, fn_arg) in fn_args.iter().enumerate() {
2068         let lldestptr = adt::trans_field_ptr(bcx,
2069                                              repr,
2070                                              fcx.llretptr.get(),
2071                                              disr,
2072                                              i);
2073         let llarg = fcx.llargs.get_copy(&fn_arg.pat.id);
2074         let arg_ty = arg_tys[i];
2075         memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2076     }
2077     finish_fn(fcx, bcx);
2078 }
2079
2080 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2081                       id: ast::NodeId, vi: @~[@ty::VariantInfo],
2082                       i: &mut uint) {
2083     for variant in enum_definition.variants.iter() {
2084         let disr_val = vi[*i].disr_val;
2085         *i += 1;
2086
2087         match variant.node.kind {
2088             ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2089                 let llfn = get_item_val(ccx, variant.node.id);
2090                 trans_enum_variant(ccx, id, variant, *args,
2091                                    disr_val, None, llfn);
2092             }
2093             ast::tuple_variant_kind(_) => {
2094                 // Nothing to do.
2095             }
2096             ast::struct_variant_kind(struct_def) => {
2097                 trans_struct_def(ccx, struct_def);
2098             }
2099         }
2100     }
2101 }
2102
2103 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2104     let _icx = push_ctxt("trans_item");
2105     let path = match ccx.tcx.items.get_copy(&item.id) {
2106         ast_map::node_item(_, p) => p,
2107         // tjc: ?
2108         _ => fail!("trans_item"),
2109     };
2110     match item.node {
2111       ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2112         if purity == ast::extern_fn  {
2113             let llfndecl = get_item_val(ccx, item.id);
2114             foreign::trans_foreign_fn(ccx,
2115                                       vec::append((*path).clone(),
2116                                                   [path_name(item.ident)]),
2117                                       decl,
2118                                       body,
2119                                       llfndecl,
2120                                       item.id);
2121         } else if !generics.is_type_parameterized() {
2122             let llfndecl = get_item_val(ccx, item.id);
2123             trans_fn(ccx,
2124                      vec::append((*path).clone(), [path_name(item.ident)]),
2125                      decl,
2126                      body,
2127                      llfndecl,
2128                      no_self,
2129                      None,
2130                      item.id,
2131                      item.attrs);
2132         } else {
2133             for stmt in body.stmts.iter() {
2134                 match stmt.node {
2135                   ast::stmt_decl(@codemap::spanned { node: ast::decl_item(i),
2136                                                  _ }, _) => {
2137                     trans_item(ccx, i);
2138                   }
2139                   _ => ()
2140                 }
2141             }
2142         }
2143       }
2144       ast::item_impl(ref generics, _, _, ref ms) => {
2145         meth::trans_impl(ccx,
2146                          (*path).clone(),
2147                          item.ident,
2148                          *ms,
2149                          generics,
2150                          item.id);
2151       }
2152       ast::item_mod(ref m) => {
2153         trans_mod(ccx, m);
2154       }
2155       ast::item_enum(ref enum_definition, ref generics) => {
2156         if !generics.is_type_parameterized() {
2157             let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2158             let mut i = 0;
2159             trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2160         }
2161       }
2162       ast::item_static(_, m, expr) => {
2163           consts::trans_const(ccx, m, item.id);
2164           // Do static_assert checking. It can't really be done much earlier because we need to get
2165           // the value of the bool out of LLVM
2166           for attr in item.attrs.iter() {
2167               if "static_assert" == attr.name() {
2168                   if m == ast::m_mutbl {
2169                       ccx.sess.span_fatal(expr.span,
2170                                           "cannot have static_assert on a mutable static");
2171                   }
2172                   let v = ccx.const_values.get_copy(&item.id);
2173                   unsafe {
2174                       if !(llvm::LLVMConstIntGetZExtValue(v) as bool) {
2175                           ccx.sess.span_fatal(expr.span, "static assertion failed");
2176                       }
2177                   }
2178               }
2179           }
2180       },
2181       ast::item_foreign_mod(ref foreign_mod) => {
2182         foreign::trans_foreign_mod(ccx, path, foreign_mod);
2183       }
2184       ast::item_struct(struct_def, ref generics) => {
2185         if !generics.is_type_parameterized() {
2186             trans_struct_def(ccx, struct_def);
2187         }
2188       }
2189       _ => {/* fall through */ }
2190     }
2191 }
2192
2193 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2194     // If this is a tuple-like struct, translate the constructor.
2195     match struct_def.ctor_id {
2196         // We only need to translate a constructor if there are fields;
2197         // otherwise this is a unit-like struct.
2198         Some(ctor_id) if struct_def.fields.len() > 0 => {
2199             let llfndecl = get_item_val(ccx, ctor_id);
2200             trans_tuple_struct(ccx, struct_def.fields,
2201                                ctor_id, None, llfndecl);
2202         }
2203         Some(_) | None => {}
2204     }
2205 }
2206
2207 // Translate a module. Doing this amounts to translating the items in the
2208 // module; there ends up being no artifact (aside from linkage names) of
2209 // separate modules in the compiled program.  That's because modules exist
2210 // only as a convenience for humans working with the code, to organize names
2211 // and control visibility.
2212 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2213     let _icx = push_ctxt("trans_mod");
2214     for item in m.items.iter() {
2215         trans_item(ccx, *item);
2216     }
2217 }
2218
2219 pub fn register_fn(ccx: @mut CrateContext,
2220                    sp: span,
2221                    sym: ~str,
2222                    node_id: ast::NodeId)
2223                 -> ValueRef {
2224     let t = ty::node_id_to_type(ccx.tcx, node_id);
2225     register_fn_full(ccx, sp, sym, node_id, t)
2226 }
2227
2228 pub fn register_fn_full(ccx: @mut CrateContext,
2229                         sp: span,
2230                         sym: ~str,
2231                         node_id: ast::NodeId,
2232                         node_type: ty::t)
2233                      -> ValueRef {
2234     let llfty = type_of_fn_from_ty(ccx, node_type);
2235     register_fn_fuller(ccx, sp, sym, node_id, lib::llvm::CCallConv, llfty)
2236 }
2237
2238 pub fn register_fn_fuller(ccx: @mut CrateContext,
2239                           sp: span,
2240                           sym: ~str,
2241                           node_id: ast::NodeId,
2242                           cc: lib::llvm::CallConv,
2243                           fn_ty: Type)
2244                           -> ValueRef {
2245     debug!("register_fn_fuller creating fn for item %d with path %s",
2246            node_id,
2247            ast_map::path_to_str(item_path(ccx, &node_id), token::get_ident_interner()));
2248
2249     let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty);
2250     ccx.item_symbols.insert(node_id, sym);
2251
2252     // FIXME #4404 android JNI hacks
2253     let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2254                       (*ccx.sess.building_library &&
2255                        ccx.sess.targ_cfg.os == session::os_android));
2256     if is_entry {
2257         create_entry_wrapper(ccx, sp, llfn);
2258     }
2259     llfn
2260 }
2261
2262 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2263     match *sess.entry_fn {
2264         Some((entry_id, _)) => node_id == entry_id,
2265         None => false
2266     }
2267 }
2268
2269 // Create a _rust_main(args: ~[str]) function which will be called from the
2270 // runtime rust_start function
2271 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2272                            _sp: span, main_llfn: ValueRef) {
2273     let et = ccx.sess.entry_type.unwrap();
2274     if et == session::EntryMain {
2275         let llfn = create_main(ccx, main_llfn);
2276         create_entry_fn(ccx, llfn, true);
2277     } else {
2278         create_entry_fn(ccx, main_llfn, false);
2279     }
2280
2281     fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
2282         let nt = ty::mk_nil();
2283
2284         let llfty = type_of_fn(ccx, [], nt);
2285         let llfdecl = decl_fn(ccx.llmod, "_rust_main",
2286                               lib::llvm::CCallConv, llfty);
2287
2288         let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None);
2289
2290         // the args vector built in create_entry_fn will need
2291         // be updated if this assertion starts to fail.
2292         assert!(fcx.has_immediate_return_value);
2293
2294         let bcx = fcx.entry_bcx.get();
2295         // Call main.
2296         let llenvarg = unsafe {
2297             let env_arg = fcx.env_arg_pos();
2298             llvm::LLVMGetParam(llfdecl, env_arg as c_uint)
2299         };
2300         let args = ~[llenvarg];
2301         Call(bcx, main_llfn, args);
2302
2303         finish_fn(fcx, bcx);
2304         return llfdecl;
2305     }
2306
2307     fn create_entry_fn(ccx: @mut CrateContext,
2308                        rust_main: ValueRef,
2309                        use_start_lang_item: bool) {
2310         let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
2311                                &ccx.int_type);
2312
2313         // FIXME #4404 android JNI hacks
2314         let llfn = if *ccx.sess.building_library {
2315             decl_cdecl_fn(ccx.llmod, "amain", llfty)
2316         } else {
2317             let main_name = match ccx.sess.targ_cfg.os {
2318                 session::os_win32 => ~"WinMain@16",
2319                 _ => ~"main",
2320             };
2321             decl_cdecl_fn(ccx.llmod, main_name, llfty)
2322         };
2323         let llbb = do "top".to_c_str().with_ref |buf| {
2324             unsafe {
2325                 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2326             }
2327         };
2328         let bld = ccx.builder.B;
2329         unsafe {
2330             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2331
2332             let crate_map = ccx.crate_map;
2333             let opaque_crate_map = do "crate_map".to_c_str().with_ref |buf| {
2334                 llvm::LLVMBuildPointerCast(bld, crate_map, Type::i8p().to_ref(), buf)
2335             };
2336
2337             let (start_fn, args) = if use_start_lang_item {
2338                 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2339                     Ok(id) => id,
2340                     Err(s) => { ccx.tcx.sess.fatal(s); }
2341                 };
2342                 let start_fn = if start_def_id.crate == ast::LOCAL_CRATE {
2343                     get_item_val(ccx, start_def_id.node)
2344                 } else {
2345                     let start_fn_type = csearch::get_type(ccx.tcx,
2346                                                           start_def_id).ty;
2347                     trans_external_path(ccx, start_def_id, start_fn_type)
2348                 };
2349
2350                 let args = {
2351                     let opaque_rust_main = do "rust_main".to_c_str().with_ref |buf| {
2352                         llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2353                     };
2354
2355                     ~[
2356                         C_null(Type::opaque_box(ccx).ptr_to()),
2357                         opaque_rust_main,
2358                         llvm::LLVMGetParam(llfn, 0),
2359                         llvm::LLVMGetParam(llfn, 1),
2360                         opaque_crate_map
2361                      ]
2362                 };
2363                 (start_fn, args)
2364             } else {
2365                 debug!("using user-defined start fn");
2366                 let args = ~[
2367                     C_null(Type::opaque_box(ccx).ptr_to()),
2368                     llvm::LLVMGetParam(llfn, 0 as c_uint),
2369                     llvm::LLVMGetParam(llfn, 1 as c_uint),
2370                     opaque_crate_map
2371                 ];
2372
2373                 (rust_main, args)
2374             };
2375
2376             let result = do args.as_imm_buf |buf, len| {
2377                 llvm::LLVMBuildCall(bld, start_fn, buf, len as c_uint, noname())
2378             };
2379
2380             llvm::LLVMBuildRet(bld, result);
2381         }
2382     }
2383 }
2384
2385 pub fn fill_fn_pair(bcx: @mut Block, pair: ValueRef, llfn: ValueRef,
2386                     llenvptr: ValueRef) {
2387     let ccx = bcx.ccx();
2388     let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2389     Store(bcx, llfn, code_cell);
2390     let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2391     let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2392     Store(bcx, llenvblobptr, env_cell);
2393 }
2394
2395 pub fn item_path(ccx: &CrateContext, id: &ast::NodeId) -> path {
2396     match ccx.tcx.items.get_copy(id) {
2397         ast_map::node_item(i, p) =>
2398             vec::append((*p).clone(), [path_name(i.ident)]),
2399         // separate map for paths?
2400         _ => fail!("item_path")
2401     }
2402 }
2403
2404 fn exported_name(ccx: @mut CrateContext, path: path, ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
2405     if attr::contains_name(attrs, "no_mangle") {
2406         path_elt_to_str(*path.last(), token::get_ident_interner())
2407     } else {
2408         mangle_exported_name(ccx, path, ty)
2409     }
2410 }
2411
2412 pub fn get_item_val(ccx: @mut CrateContext, id: ast::NodeId) -> ValueRef {
2413     debug!("get_item_val(id=`%?`)", id);
2414
2415     let val = ccx.item_vals.find_copy(&id);
2416     match val {
2417         Some(v) => v,
2418         None => {
2419             let mut exprt = false;
2420             let item = ccx.tcx.items.get_copy(&id);
2421             let val = match item {
2422                 ast_map::node_item(i, pth) => {
2423
2424                     let my_path = vec::append((*pth).clone(), [path_name(i.ident)]);
2425                     let ty = ty::node_id_to_type(ccx.tcx, i.id);
2426                     let sym = exported_name(ccx, my_path, ty, i.attrs);
2427
2428                     let v = match i.node {
2429                         ast::item_static(_, m, expr) => {
2430                             // We need the translated value here, because for enums the
2431                             // LLVM type is not fully determined by the Rust type.
2432                             let v = consts::const_expr(ccx, expr);
2433                             ccx.const_values.insert(id, v);
2434                             exprt = (m == ast::m_mutbl || i.vis == ast::public);
2435
2436                             unsafe {
2437                                 let llty = llvm::LLVMTypeOf(v);
2438                                 let g = do sym.to_c_str().with_ref |buf| {
2439                                     llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2440                                 };
2441
2442                                 ccx.item_symbols.insert(i.id, sym);
2443                                 g
2444                             }
2445                         }
2446
2447                         ast::item_fn(_, purity, _, _, _) => {
2448                             let llfn = if purity != ast::extern_fn {
2449                                 register_fn_full(ccx, i.span, sym, i.id, ty)
2450                             } else {
2451                                 foreign::register_foreign_fn(ccx, i.span, sym, i.id)
2452                             };
2453                             set_inline_hint_if_appr(i.attrs, llfn);
2454                             llfn
2455                         }
2456
2457                         _ => fail!("get_item_val: weird result in table")
2458                     };
2459
2460                     match (attr::first_attr_value_str_by_name(i.attrs, "link_section")) {
2461                         Some(sect) => unsafe {
2462                             do sect.to_c_str().with_ref |buf| {
2463                                 llvm::LLVMSetSection(v, buf);
2464                             }
2465                         },
2466                         None => ()
2467                     }
2468
2469                     v
2470                 }
2471
2472                 ast_map::node_trait_method(trait_method, _, pth) => {
2473                     debug!("get_item_val(): processing a node_trait_method");
2474                     match *trait_method {
2475                         ast::required(_) => {
2476                             ccx.sess.bug("unexpected variant: required trait method in \
2477                                          get_item_val()");
2478                         }
2479                         ast::provided(m) => {
2480                             exprt = true;
2481                             register_method(ccx, id, pth, m)
2482                         }
2483                     }
2484                 }
2485
2486                 ast_map::node_method(m, _, pth) => {
2487                     register_method(ccx, id, pth, m)
2488                 }
2489
2490                 ast_map::node_foreign_item(ni, _, _, pth) => {
2491                     let ty = ty::node_id_to_type(ccx.tcx, ni.id);
2492                     exprt = true;
2493
2494                     match ni.node {
2495                         ast::foreign_item_fn(*) => {
2496                             let path = vec::append((*pth).clone(), [path_name(ni.ident)]);
2497                             let sym = exported_name(ccx, path, ty, ni.attrs);
2498
2499                             register_fn_full(ccx, ni.span, sym, ni.id, ty)
2500                         }
2501                         ast::foreign_item_static(*) => {
2502                             let ident = token::ident_to_str(&ni.ident);
2503                             let g = do ident.to_c_str().with_ref |buf| {
2504                                 unsafe {
2505                                     let ty = type_of(ccx, ty);
2506                                     llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf)
2507                                 }
2508                             };
2509                             g
2510                         }
2511                     }
2512                 }
2513
2514                 ast_map::node_variant(ref v, enm, pth) => {
2515                     let llfn;
2516                     match v.node.kind {
2517                         ast::tuple_variant_kind(ref args) => {
2518                             assert!(args.len() != 0u);
2519                             let pth = vec::append((*pth).clone(),
2520                                                   [path_name(enm.ident),
2521                                                    path_name((*v).node.name)]);
2522                             let ty = ty::node_id_to_type(ccx.tcx, id);
2523                             let sym = exported_name(ccx, pth, ty, enm.attrs);
2524
2525                             llfn = match enm.node {
2526                                 ast::item_enum(_, _) => {
2527                                     register_fn_full(ccx, (*v).span, sym, id, ty)
2528                                 }
2529                                 _ => fail!("node_variant, shouldn't happen")
2530                             };
2531                         }
2532                         ast::struct_variant_kind(_) => {
2533                             fail!("struct variant kind unexpected in get_item_val")
2534                         }
2535                     }
2536                     set_inline_hint(llfn);
2537                     llfn
2538                 }
2539
2540                 ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2541                     // Only register the constructor if this is a tuple-like struct.
2542                     match struct_def.ctor_id {
2543                         None => {
2544                             ccx.tcx.sess.bug("attempt to register a constructor of \
2545                                               a non-tuple-like struct")
2546                         }
2547                         Some(ctor_id) => {
2548                             let ty = ty::node_id_to_type(ccx.tcx, ctor_id);
2549                             let sym = exported_name(ccx, (*struct_path).clone(), ty,
2550                                                     struct_item.attrs);
2551                             let llfn = register_fn_full(ccx, struct_item.span, sym, ctor_id, ty);
2552                             set_inline_hint(llfn);
2553                             llfn
2554                         }
2555                     }
2556                 }
2557
2558                 ref variant => {
2559                     ccx.sess.bug(fmt!("get_item_val(): unexpected variant: %?",
2560                                  variant))
2561                 }
2562             };
2563
2564             if !exprt && !ccx.reachable.contains(&id) {
2565                 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2566             }
2567
2568             ccx.item_vals.insert(id, val);
2569             val
2570         }
2571     }
2572 }
2573
2574 pub fn register_method(ccx: @mut CrateContext,
2575                        id: ast::NodeId,
2576                        path: @ast_map::path,
2577                        m: @ast::method) -> ValueRef {
2578     let mty = ty::node_id_to_type(ccx.tcx, id);
2579
2580     let mut path = (*path).clone();
2581     path.push(path_name(gensym_name("meth")));
2582     path.push(path_name(m.ident));
2583
2584     let sym = exported_name(ccx, path, mty, m.attrs);
2585
2586     let llfn = register_fn_full(ccx, m.span, sym, id, mty);
2587     set_inline_hint_if_appr(m.attrs, llfn);
2588     llfn
2589 }
2590
2591 // The constant translation pass.
2592 pub fn trans_constant(ccx: &mut CrateContext, it: @ast::item) {
2593     let _icx = push_ctxt("trans_constant");
2594     match it.node {
2595       ast::item_enum(ref enum_definition, _) => {
2596         let vi = ty::enum_variants(ccx.tcx,
2597                                    ast::def_id { crate: ast::LOCAL_CRATE,
2598                                                  node: it.id });
2599         let mut i = 0;
2600         let path = item_path(ccx, &it.id);
2601         for variant in (*enum_definition).variants.iter() {
2602             let p = vec::append(path.clone(), [
2603                 path_name(variant.node.name),
2604                 path_name(special_idents::descrim)
2605             ]);
2606             let s = mangle_exported_name(ccx, p, ty::mk_int()).to_managed();
2607             let disr_val = vi[i].disr_val;
2608             note_unique_llvm_symbol(ccx, s);
2609             let discrim_gvar = do s.to_c_str().with_ref |buf| {
2610                 unsafe {
2611                     llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2612                 }
2613             };
2614             unsafe {
2615                 llvm::LLVMSetInitializer(discrim_gvar, C_uint(ccx, disr_val));
2616                 llvm::LLVMSetGlobalConstant(discrim_gvar, True);
2617             }
2618             ccx.discrims.insert(
2619                 local_def(variant.node.id), discrim_gvar);
2620             ccx.discrim_symbols.insert(variant.node.id, s);
2621             i += 1;
2622         }
2623       }
2624       _ => ()
2625     }
2626 }
2627
2628 pub fn trans_constants(ccx: @mut CrateContext, crate: &ast::Crate) {
2629     oldvisit::visit_crate(
2630         crate, ((),
2631         oldvisit::mk_simple_visitor(@oldvisit::SimpleVisitor {
2632             visit_item: |a| trans_constant(ccx, a),
2633             ..*oldvisit::default_simple_visitor()
2634         })));
2635 }
2636
2637 pub fn vp2i(cx: @mut Block, v: ValueRef) -> ValueRef {
2638     let ccx = cx.ccx();
2639     return PtrToInt(cx, v, ccx.int_type);
2640 }
2641
2642 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2643     unsafe {
2644         return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2645     }
2646 }
2647
2648 macro_rules! ifn (
2649     ($name:expr, $args:expr, $ret:expr) => ({
2650         let name = $name;
2651         let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2652         intrinsics.insert(name, f);
2653     })
2654 )
2655
2656 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2657     let i8p = Type::i8p();
2658     let mut intrinsics = HashMap::new();
2659
2660     ifn!("llvm.memcpy.p0i8.p0i8.i32",
2661          [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2662     ifn!("llvm.memcpy.p0i8.p0i8.i64",
2663          [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2664     ifn!("llvm.memmove.p0i8.p0i8.i32",
2665          [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2666     ifn!("llvm.memmove.p0i8.p0i8.i64",
2667          [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2668     ifn!("llvm.memset.p0i8.i32",
2669          [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2670     ifn!("llvm.memset.p0i8.i64",
2671          [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2672
2673     ifn!("llvm.trap", [], Type::void());
2674     ifn!("llvm.frameaddress", [Type::i32()], i8p);
2675
2676     ifn!("llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2677     ifn!("llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2678     ifn!("llvm.pow.f32",  [Type::f32(), Type::f32()], Type::f32());
2679     ifn!("llvm.pow.f64",  [Type::f64(), Type::f64()], Type::f64());
2680
2681     ifn!("llvm.sqrt.f32", [Type::f32()], Type::f32());
2682     ifn!("llvm.sqrt.f64", [Type::f64()], Type::f64());
2683     ifn!("llvm.sin.f32",  [Type::f32()], Type::f32());
2684     ifn!("llvm.sin.f64",  [Type::f64()], Type::f64());
2685     ifn!("llvm.cos.f32",  [Type::f32()], Type::f32());
2686     ifn!("llvm.cos.f64",  [Type::f64()], Type::f64());
2687     ifn!("llvm.exp.f32",  [Type::f32()], Type::f32());
2688     ifn!("llvm.exp.f64",  [Type::f64()], Type::f64());
2689     ifn!("llvm.exp2.f32", [Type::f32()], Type::f32());
2690     ifn!("llvm.exp2.f64", [Type::f64()], Type::f64());
2691     ifn!("llvm.log.f32",  [Type::f32()], Type::f32());
2692     ifn!("llvm.log.f64",  [Type::f64()], Type::f64());
2693     ifn!("llvm.log10.f32",[Type::f32()], Type::f32());
2694     ifn!("llvm.log10.f64",[Type::f64()], Type::f64());
2695     ifn!("llvm.log2.f32", [Type::f32()], Type::f32());
2696     ifn!("llvm.log2.f64", [Type::f64()], Type::f64());
2697
2698     ifn!("llvm.fma.f32",  [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2699     ifn!("llvm.fma.f64",  [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2700
2701     ifn!("llvm.fabs.f32", [Type::f32()], Type::f32());
2702     ifn!("llvm.fabs.f64", [Type::f64()], Type::f64());
2703     ifn!("llvm.floor.f32",[Type::f32()], Type::f32());
2704     ifn!("llvm.floor.f64",[Type::f64()], Type::f64());
2705     ifn!("llvm.ceil.f32", [Type::f32()], Type::f32());
2706     ifn!("llvm.ceil.f64", [Type::f64()], Type::f64());
2707     ifn!("llvm.trunc.f32",[Type::f32()], Type::f32());
2708     ifn!("llvm.trunc.f64",[Type::f64()], Type::f64());
2709
2710     ifn!("llvm.ctpop.i8", [Type::i8()], Type::i8());
2711     ifn!("llvm.ctpop.i16",[Type::i16()], Type::i16());
2712     ifn!("llvm.ctpop.i32",[Type::i32()], Type::i32());
2713     ifn!("llvm.ctpop.i64",[Type::i64()], Type::i64());
2714
2715     ifn!("llvm.ctlz.i8",  [Type::i8() , Type::i1()], Type::i8());
2716     ifn!("llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2717     ifn!("llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2718     ifn!("llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2719
2720     ifn!("llvm.cttz.i8",  [Type::i8() , Type::i1()], Type::i8());
2721     ifn!("llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2722     ifn!("llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2723     ifn!("llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2724
2725     ifn!("llvm.bswap.i16",[Type::i16()], Type::i16());
2726     ifn!("llvm.bswap.i32",[Type::i32()], Type::i32());
2727     ifn!("llvm.bswap.i64",[Type::i64()], Type::i64());
2728
2729     return intrinsics;
2730 }
2731
2732 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2733     ifn!("llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2734     ifn!("llvm.dbg.value",   [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2735 }
2736
2737 pub fn trap(bcx: @mut Block) {
2738     match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2739       Some(&x) => { Call(bcx, x, []); },
2740       _ => bcx.sess().bug("unbound llvm.trap in trap")
2741     }
2742 }
2743
2744 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2745     if !ccx.sess.opts.gc || !ccx.uses_gc {
2746         return;
2747     }
2748
2749     let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2750     let gc_metadata = do gc_metadata_name.to_c_str().with_ref |buf| {
2751         unsafe {
2752             llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2753         }
2754     };
2755     unsafe {
2756         llvm::LLVMSetGlobalConstant(gc_metadata, True);
2757         lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2758         ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2759     }
2760 }
2761
2762 pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
2763     let elttype = Type::struct_([ccx.int_type, ccx.int_type], false);
2764     let maptype = Type::array(&elttype, (ccx.module_data.len() + 1) as u64);
2765     let map = do "_rust_mod_map".to_c_str().with_ref |buf| {
2766         unsafe {
2767             llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2768         }
2769     };
2770     lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2771     let mut elts: ~[ValueRef] = ~[];
2772
2773     // This is not ideal, but the borrow checker doesn't
2774     // like the multiple borrows. At least, it doesn't
2775     // like them on the current snapshot. (2013-06-14)
2776     let mut keys = ~[];
2777     for (k, _) in ccx.module_data.iter() {
2778         keys.push(k.to_managed());
2779     }
2780
2781     for key in keys.iter() {
2782         let val = *ccx.module_data.find_equiv(key).get();
2783         let s_const = C_cstr(ccx, *key);
2784         let s_ptr = p2i(ccx, s_const);
2785         let v_ptr = p2i(ccx, val);
2786         let elt = C_struct([s_ptr, v_ptr]);
2787         elts.push(elt);
2788     }
2789     let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
2790     elts.push(term);
2791     unsafe {
2792         llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2793     }
2794     return map;
2795 }
2796
2797
2798 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2799                       llmod: ModuleRef) -> ValueRef {
2800     let targ_cfg = sess.targ_cfg;
2801     let int_type = Type::int(targ_cfg.arch);
2802     let mut n_subcrates = 1;
2803     let cstore = sess.cstore;
2804     while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2805     let mapname = if *sess.building_library {
2806         fmt!("%s_%s_%s", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2807     } else {
2808         ~"toplevel"
2809     };
2810     let sym_name = ~"_rust_crate_map_" + mapname;
2811     let arrtype = Type::array(&int_type, n_subcrates as u64);
2812     let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false);
2813     let map = do sym_name.to_c_str().with_ref |buf| {
2814         unsafe {
2815             llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2816         }
2817     };
2818     lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2819     return map;
2820 }
2821
2822 pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) {
2823     let mut subcrates: ~[ValueRef] = ~[];
2824     let mut i = 1;
2825     let cstore = ccx.sess.cstore;
2826     while cstore::have_crate_data(cstore, i) {
2827         let cdata = cstore::get_crate_data(cstore, i);
2828         let nm = fmt!("_rust_crate_map_%s_%s_%s",
2829                       cdata.name,
2830                       cstore::get_crate_vers(cstore, i),
2831                       cstore::get_crate_hash(cstore, i));
2832         let cr = do nm.to_c_str().with_ref |buf| {
2833             unsafe {
2834                 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2835             }
2836         };
2837         subcrates.push(p2i(ccx, cr));
2838         i += 1;
2839     }
2840     subcrates.push(C_int(ccx, 0));
2841
2842     let llannihilatefn = match ccx.tcx.lang_items.annihilate_fn() {
2843         Some(annihilate_def_id) => {
2844             if annihilate_def_id.crate == ast::LOCAL_CRATE {
2845                 get_item_val(ccx, annihilate_def_id.node)
2846             } else {
2847                 let annihilate_fn_type = csearch::get_type(ccx.tcx,
2848                                                            annihilate_def_id).ty;
2849                 trans_external_path(ccx, annihilate_def_id, annihilate_fn_type)
2850             }
2851         }
2852         None => { C_null(Type::i8p()) }
2853     };
2854
2855     unsafe {
2856         let mod_map = create_module_map(ccx);
2857         llvm::LLVMSetInitializer(map, C_struct(
2858             [C_i32(1),
2859              lib::llvm::llvm::LLVMConstPointerCast(llannihilatefn, Type::i8p().to_ref()),
2860              p2i(ccx, mod_map),
2861              C_array(ccx.int_type, subcrates)]));
2862     }
2863 }
2864
2865 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
2866     -> encoder::EncodeParams<'r> {
2867
2868         let diag = cx.sess.diagnostic();
2869         let item_symbols = &cx.item_symbols;
2870         let discrim_symbols = &cx.discrim_symbols;
2871         let link_meta = &cx.link_meta;
2872         encoder::EncodeParams {
2873             diag: diag,
2874             tcx: cx.tcx,
2875             reexports2: cx.exp_map2,
2876             item_symbols: item_symbols,
2877             discrim_symbols: discrim_symbols,
2878             link_meta: link_meta,
2879             cstore: cx.sess.cstore,
2880             encode_inlined_item: ie,
2881             reachable: cx.reachable,
2882         }
2883 }
2884
2885 pub fn write_metadata(cx: &mut CrateContext, crate: &ast::Crate) {
2886     if !*cx.sess.building_library { return; }
2887
2888     let encode_inlined_item: encoder::encode_inlined_item =
2889         |ecx, ebml_w, path, ii|
2890         astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
2891
2892     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2893     let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
2894     let llconst = C_struct([llmeta]);
2895     let mut llglobal = do "rust_metadata".to_c_str().with_ref |buf| {
2896         unsafe {
2897             llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
2898         }
2899     };
2900     unsafe {
2901         llvm::LLVMSetInitializer(llglobal, llconst);
2902         do cx.sess.targ_cfg.target_strs.meta_sect_name.to_c_str().with_ref |buf| {
2903             llvm::LLVMSetSection(llglobal, buf)
2904         };
2905         lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2906
2907         let t_ptr_i8 = Type::i8p();
2908         llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
2909         let llvm_used = do "llvm.used".to_c_str().with_ref |buf| {
2910             llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
2911         };
2912         lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
2913         llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
2914     }
2915 }
2916
2917 fn mk_global(ccx: &CrateContext,
2918              name: &str,
2919              llval: ValueRef,
2920              internal: bool)
2921           -> ValueRef {
2922     unsafe {
2923         let llglobal = do name.to_c_str().with_ref |buf| {
2924             llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval).to_ref(), buf)
2925         };
2926         llvm::LLVMSetInitializer(llglobal, llval);
2927         llvm::LLVMSetGlobalConstant(llglobal, True);
2928
2929         if internal {
2930             lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2931         }
2932
2933         return llglobal;
2934     }
2935 }
2936
2937 // Writes the current ABI version into the crate.
2938 pub fn write_abi_version(ccx: &mut CrateContext) {
2939     mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version), false);
2940 }
2941
2942 pub fn trans_crate(sess: session::Session,
2943                    crate: &ast::Crate,
2944                    analysis: &CrateAnalysis,
2945                    output: &Path) -> CrateTranslation {
2946     // Before we touch LLVM, make sure that multithreading is enabled.
2947     if unsafe { !llvm::LLVMRustStartMultithreading() } {
2948         //sess.bug("couldn't enable multi-threaded LLVM");
2949     }
2950
2951     let mut symbol_hasher = hash::default_state();
2952     let link_meta = link::build_link_meta(sess, crate, output, &mut symbol_hasher);
2953
2954     // Append ".rc" to crate name as LLVM module identifier.
2955     //
2956     // LLVM code generator emits a ".file filename" directive
2957     // for ELF backends. Value of the "filename" is set as the
2958     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
2959     // crashes if the module identifer is same as other symbols
2960     // such as a function name in the module.
2961     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2962     let llmod_id = link_meta.name.to_owned() + ".rc";
2963
2964     let ccx = @mut CrateContext::new(sess,
2965                                      llmod_id,
2966                                      analysis.ty_cx,
2967                                      analysis.exp_map2,
2968                                      analysis.maps,
2969                                      symbol_hasher,
2970                                      link_meta,
2971                                      analysis.reachable);
2972
2973     {
2974         let _icx = push_ctxt("data");
2975         trans_constants(ccx, crate);
2976     }
2977
2978     {
2979         let _icx = push_ctxt("text");
2980         trans_mod(ccx, &crate.module);
2981     }
2982
2983     decl_gc_metadata(ccx, llmod_id);
2984     fill_crate_map(ccx, ccx.crate_map);
2985     glue::emit_tydescs(ccx);
2986     write_abi_version(ccx);
2987     if ccx.sess.opts.debuginfo {
2988         debuginfo::finalize(ccx);
2989     }
2990
2991     // Translate the metadata.
2992     write_metadata(ccx, crate);
2993     if ccx.sess.trans_stats() {
2994         io::println("--- trans stats ---");
2995         printfln!("n_static_tydescs: %u", ccx.stats.n_static_tydescs);
2996         printfln!("n_glues_created: %u", ccx.stats.n_glues_created);
2997         printfln!("n_null_glues: %u", ccx.stats.n_null_glues);
2998         printfln!("n_real_glues: %u", ccx.stats.n_real_glues);
2999
3000         printfln!("n_fns: %u", ccx.stats.n_fns);
3001         printfln!("n_monos: %u", ccx.stats.n_monos);
3002         printfln!("n_inlines: %u", ccx.stats.n_inlines);
3003         printfln!("n_closures: %u", ccx.stats.n_closures);
3004         io::println("fn stats:");
3005         do sort::quick_sort(ccx.stats.fn_stats) |&(_, _, insns_a), &(_, _, insns_b)| {
3006             insns_a > insns_b
3007         }
3008         for tuple in ccx.stats.fn_stats.iter() {
3009             match *tuple {
3010                 (ref name, ms, insns) => {
3011                     printfln!("%u insns, %u ms, %s", insns, ms, *name);
3012                 }
3013             }
3014         }
3015     }
3016     if ccx.sess.count_llvm_insns() {
3017         for (k, v) in ccx.stats.llvm_insns.iter() {
3018             printfln!("%-7u %s", *v, *k);
3019         }
3020     }
3021
3022     let llcx = ccx.llcx;
3023     let link_meta = ccx.link_meta;
3024     let llmod = ccx.llmod;
3025
3026     return CrateTranslation {
3027         context: llcx,
3028         module: llmod,
3029         link: link_meta
3030     };
3031 }