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