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