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