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