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