]> git.lizzy.rs Git - rust.git/blob - src/comp/middle/trans.rs
revert metrics
[rust.git] / src / comp / middle / trans.rs
1 // trans.rs: Translate the completed AST to the LLVM IR.
2 //
3 // Some functions here, such as trans_block and trans_expr, return a value --
4 // the result of the translation to LLVM -- while others, such as trans_fn,
5 // trans_obj, and trans_item, are called only for the side effect of adding a
6 // particular definition to the LLVM IR output we're producing.
7 //
8 // Hopefully useful general knowledge about trans:
9 //
10 //   * There's no way to find out the ty::t type of a ValueRef.  Doing so
11 //     would be "trying to get the eggs out of an omelette" (credit:
12 //     pcwalton).  You can, instead, find out its TypeRef by calling val_ty,
13 //     but many TypeRefs correspond to one ty::t; for instance, tup(int, int,
14 //     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
15
16 import std::{map, time};
17 import std::map::hashmap;
18 import std::map::{new_int_hash, new_str_hash};
19 import option::{some, none};
20 import driver::session;
21 import front::attr;
22 import middle::{ty, gc, resolve, debuginfo};
23 import middle::freevars::*;
24 import back::{link, abi, upcall};
25 import syntax::{ast, ast_util, codemap};
26 import syntax::visit;
27 import syntax::codemap::span;
28 import syntax::print::pprust::{expr_to_str, stmt_to_str};
29 import visit::vt;
30 import util::common::*;
31 import lib::llvm::{llvm, mk_target_data, mk_type_names};
32 import lib::llvm::llvm::{ModuleRef, ValueRef, TypeRef, BasicBlockRef};
33 import lib::llvm::{True, False};
34 import link::{mangle_internal_name_by_type_only,
35               mangle_internal_name_by_seq,
36               mangle_internal_name_by_path,
37               mangle_internal_name_by_path_and_seq,
38               mangle_exported_name};
39 import metadata::{csearch, cstore};
40 import util::ppaux::{ty_to_str, ty_to_short_str};
41
42 import trans_common::*;
43 import trans_build::*;
44
45 import trans_objects::{trans_anon_obj, trans_obj};
46 import tvec = trans_vec;
47
48 fn type_of_1(bcx: @block_ctxt, t: ty::t) -> TypeRef {
49     let cx = bcx_ccx(bcx);
50     check type_has_static_size(cx, t);
51     type_of(cx, bcx.sp, t)
52 }
53
54 fn type_of(cx: @crate_ctxt, sp: span, t: ty::t) : type_has_static_size(cx, t)
55    -> TypeRef {
56     // Should follow from type_has_static_size -- argh.
57     // FIXME (requires Issue #586)
58     check non_ty_var(cx, t);
59     type_of_inner(cx, sp, t)
60 }
61
62 fn type_of_explicit_args(cx: @crate_ctxt, sp: span, inputs: [ty::arg]) ->
63    [TypeRef] {
64     let atys = [];
65     for arg in inputs {
66         let arg_ty = arg.ty;
67         // FIXME: would be nice to have a constraint on arg
68         // that would obviate the need for this check
69         check non_ty_var(cx, arg_ty);
70         let llty = type_of_inner(cx, sp, arg_ty);
71         atys += [arg.mode == ast::by_val ? llty : T_ptr(llty)];
72     }
73     ret atys;
74 }
75
76
77 // NB: must keep 4 fns in sync:
78 //
79 //  - type_of_fn
80 //  - create_llargs_for_fn_args.
81 //  - new_fn_ctxt
82 //  - trans_args
83 fn type_of_fn(cx: @crate_ctxt, sp: span, is_method: bool, inputs: [ty::arg],
84               output: ty::t, params: [ty::param_bounds]) -> TypeRef {
85     let atys: [TypeRef] = [];
86
87     // Arg 0: Output pointer.
88     check non_ty_var(cx, output);
89     let out_ty = T_ptr(type_of_inner(cx, sp, output));
90     atys += [out_ty];
91
92     // Arg 1: Env (closure-bindings / self-obj)
93     if is_method {
94         atys += [T_ptr(cx.rust_object_type)];
95     } else {
96         atys += [T_opaque_cbox_ptr(cx)];
97     }
98
99     // Args >2: ty params, if not acquired via capture...
100     if !is_method {
101         for bounds in params {
102             atys += [T_ptr(cx.tydesc_type)];
103             for bound in *bounds {
104                 alt bound {
105                   ty::bound_iface(_) { atys += [T_ptr(T_dict())]; }
106                   _ {}
107                 }
108             }
109         }
110     }
111     // ... then explicit args.
112     atys += type_of_explicit_args(cx, sp, inputs);
113     ret T_fn(atys, llvm::LLVMVoidType());
114 }
115
116 // Given a function type and a count of ty params, construct an llvm type
117 fn type_of_fn_from_ty(cx: @crate_ctxt, sp: span, fty: ty::t,
118                       param_bounds: [ty::param_bounds]) -> TypeRef {
119     // FIXME: Check should be unnecessary, b/c it's implied
120     // by returns_non_ty_var(t). Make that a postcondition
121     // (see Issue #586)
122     let ret_ty = ty::ty_fn_ret(cx.tcx, fty);
123     ret type_of_fn(cx, sp, false, ty::ty_fn_args(cx.tcx, fty),
124                    ret_ty, param_bounds);
125 }
126
127 fn type_of_inner(cx: @crate_ctxt, sp: span, t: ty::t)
128     : non_ty_var(cx, t) -> TypeRef {
129     // Check the cache.
130
131     if cx.lltypes.contains_key(t) { ret cx.lltypes.get(t); }
132     let llty = alt ty::struct(cx.tcx, t) {
133       ty::ty_native(_) { T_ptr(T_i8()) }
134       ty::ty_nil. { T_nil() }
135       ty::ty_bot. {
136         T_nil() /* ...I guess? */
137       }
138       ty::ty_bool. { T_bool() }
139       ty::ty_int(t) { T_int_ty(cx, t) }
140       ty::ty_uint(t) { T_uint_ty(cx, t) }
141       ty::ty_float(t) { T_float_ty(cx, t) }
142       ty::ty_str. { T_ptr(T_vec(cx, T_i8())) }
143       ty::ty_tag(did, _) { type_of_tag(cx, sp, did, t) }
144       ty::ty_box(mt) {
145         let mt_ty = mt.ty;
146         check non_ty_var(cx, mt_ty);
147         T_ptr(T_box(cx, type_of_inner(cx, sp, mt_ty))) }
148       ty::ty_uniq(mt) {
149         let mt_ty = mt.ty;
150         check non_ty_var(cx, mt_ty);
151         T_ptr(type_of_inner(cx, sp, mt_ty)) }
152       ty::ty_vec(mt) {
153         let mt_ty = mt.ty;
154         if ty::type_has_dynamic_size(cx.tcx, mt_ty) {
155             T_ptr(cx.opaque_vec_type)
156         } else {
157             // should be unnecessary
158             check non_ty_var(cx, mt_ty);
159             T_ptr(T_vec(cx, type_of_inner(cx, sp, mt_ty))) }
160       }
161       ty::ty_ptr(mt) {
162         let mt_ty = mt.ty;
163         check non_ty_var(cx, mt_ty);
164         T_ptr(type_of_inner(cx, sp, mt_ty)) }
165       ty::ty_rec(fields) {
166         let tys: [TypeRef] = [];
167         for f: ty::field in fields {
168             let mt_ty = f.mt.ty;
169             check non_ty_var(cx, mt_ty);
170             tys += [type_of_inner(cx, sp, mt_ty)];
171         }
172         T_struct(tys)
173       }
174       ty::ty_fn(_) {
175         T_fn_pair(cx, type_of_fn_from_ty(cx, sp, t, []))
176       }
177       ty::ty_native_fn(args, out) {
178         let nft = native_fn_wrapper_type(cx, sp, [], t);
179         T_fn_pair(cx, nft)
180       }
181       ty::ty_obj(meths) { cx.rust_object_type }
182       ty::ty_res(_, sub, tps) {
183         let sub1 = ty::substitute_type_params(cx.tcx, tps, sub);
184         check non_ty_var(cx, sub1);
185         // FIXME #1184: Resource flag is larger than necessary
186         ret T_struct([cx.int_type, type_of_inner(cx, sp, sub1)]);
187       }
188       ty::ty_var(_) {
189         // Should be unreachable b/c of precondition.
190         // FIXME: would be nice to have a way of expressing this
191         // through postconditions, and then making it sound to omit
192         // cases in the alt
193         std::util::unreachable()
194       }
195       ty::ty_param(_, _) { T_typaram(cx.tn) }
196       ty::ty_send_type. | ty::ty_type. { T_ptr(cx.tydesc_type) }
197       ty::ty_tup(elts) {
198         let tys = [];
199         for elt in elts {
200             check non_ty_var(cx, elt);
201             tys += [type_of_inner(cx, sp, elt)];
202         }
203         T_struct(tys)
204       }
205       ty::ty_opaque_closure_ptr(_) {
206         T_opaque_cbox_ptr(cx)
207       }
208       ty::ty_constr(subt,_) {
209         // FIXME: could be a constraint on ty_fn
210           check non_ty_var(cx, subt);
211           type_of_inner(cx, sp, subt)
212       }
213       _ {
214         fail "type_of_inner not implemented for this kind of type";
215       }
216     };
217     cx.lltypes.insert(t, llty);
218     ret llty;
219 }
220
221 fn type_of_tag(cx: @crate_ctxt, sp: span, did: ast::def_id, t: ty::t)
222     -> TypeRef {
223     let degen = vec::len(*ty::tag_variants(cx.tcx, did)) == 1u;
224     if check type_has_static_size(cx, t) {
225         let size = static_size_of_tag(cx, sp, t);
226         if !degen { T_tag(cx, size) }
227         else if size == 0u { T_struct([T_tag_variant(cx)]) }
228         else { T_array(T_i8(), size) }
229     }
230     else {
231         if degen { T_struct([T_tag_variant(cx)]) }
232         else { T_opaque_tag(cx) }
233     }
234 }
235
236 fn type_of_ty_param_bounds_and_ty(lcx: @local_ctxt, sp: span,
237                                  tpt: ty::ty_param_bounds_and_ty) -> TypeRef {
238     let cx = lcx.ccx;
239     let t = tpt.ty;
240     alt ty::struct(cx.tcx, t) {
241       ty::ty_fn(_) | ty::ty_native_fn(_, _) {
242         ret type_of_fn_from_ty(cx, sp, t, *tpt.bounds);
243       }
244       _ {
245         // fall through
246       }
247     }
248     // FIXME: could have a precondition on tpt, but that
249     // doesn't work right now because one predicate can't imply
250     // another
251     check (type_has_static_size(cx, t));
252     type_of(cx, sp, t)
253 }
254
255 fn type_of_or_i8(bcx: @block_ctxt, typ: ty::t) -> TypeRef {
256     let ccx = bcx_ccx(bcx);
257     if check type_has_static_size(ccx, typ) {
258         let sp = bcx.sp;
259         type_of(ccx, sp, typ)
260     } else { T_i8() }
261 }
262
263
264 // Name sanitation. LLVM will happily accept identifiers with weird names, but
265 // gas doesn't!
266 fn sanitize(s: str) -> str {
267     let result = "";
268     for c: u8 in s {
269         if c == '@' as u8 {
270             result += "boxed_";
271         } else {
272             if c == ',' as u8 {
273                 result += "_";
274             } else {
275                 if c == '{' as u8 || c == '(' as u8 {
276                     result += "_of_";
277                 } else {
278                     if c != 10u8 && c != '}' as u8 && c != ')' as u8 &&
279                            c != ' ' as u8 && c != '\t' as u8 && c != ';' as u8
280                        {
281                         let v = [c];
282                         result += str::unsafe_from_bytes(v);
283                     }
284                 }
285             }
286         }
287     }
288     ret result;
289 }
290
291
292 fn log_fn_time(ccx: @crate_ctxt, name: str, start: time::timeval,
293                end: time::timeval) {
294     let elapsed =
295         1000 * (end.sec - start.sec as int) +
296             ((end.usec as int) - (start.usec as int)) / 1000;
297     *ccx.stats.fn_times += [{ident: name, time: elapsed}];
298 }
299
300
301 fn decl_fn(llmod: ModuleRef, name: str, cc: uint, llty: TypeRef) -> ValueRef {
302     let llfn: ValueRef =
303         str::as_buf(name, {|buf|
304             llvm::LLVMGetOrInsertFunction(llmod, buf, llty) });
305     llvm::LLVMSetFunctionCallConv(llfn, cc);
306     ret llfn;
307 }
308
309 fn decl_cdecl_fn(llmod: ModuleRef, name: str, llty: TypeRef) -> ValueRef {
310     ret decl_fn(llmod, name, lib::llvm::LLVMCCallConv, llty);
311 }
312
313
314 // Only use this if you are going to actually define the function. It's
315 // not valid to simply declare a function as internal.
316 fn decl_internal_cdecl_fn(llmod: ModuleRef, name: str, llty: TypeRef) ->
317    ValueRef {
318     let llfn = decl_cdecl_fn(llmod, name, llty);
319     llvm::LLVMSetLinkage(llfn,
320                          lib::llvm::LLVMInternalLinkage as llvm::Linkage);
321     ret llfn;
322 }
323
324 fn get_extern_fn(externs: hashmap<str, ValueRef>, llmod: ModuleRef, name: str,
325                  cc: uint, ty: TypeRef) -> ValueRef {
326     if externs.contains_key(name) { ret externs.get(name); }
327     let f = decl_fn(llmod, name, cc, ty);
328     externs.insert(name, f);
329     ret f;
330 }
331
332 fn get_extern_const(externs: hashmap<str, ValueRef>, llmod: ModuleRef,
333                     name: str, ty: TypeRef) -> ValueRef {
334     if externs.contains_key(name) { ret externs.get(name); }
335     let c = str::as_buf(name, {|buf| llvm::LLVMAddGlobal(llmod, ty, buf) });
336     externs.insert(name, c);
337     ret c;
338 }
339
340 fn get_simple_extern_fn(cx: @block_ctxt,
341                         externs: hashmap<str, ValueRef>,
342                         llmod: ModuleRef,
343                         name: str, n_args: int) -> ValueRef {
344     let ccx = cx.fcx.lcx.ccx;
345     let inputs = vec::init_elt::<TypeRef>(ccx.int_type, n_args as uint);
346     let output = ccx.int_type;
347     let t = T_fn(inputs, output);
348     ret get_extern_fn(externs, llmod, name, lib::llvm::LLVMCCallConv, t);
349 }
350
351 fn trans_native_call(cx: @block_ctxt, externs: hashmap<str, ValueRef>,
352                      llmod: ModuleRef, name: str, args: [ValueRef]) ->
353    ValueRef {
354     let n: int = vec::len::<ValueRef>(args) as int;
355     let llnative: ValueRef =
356         get_simple_extern_fn(cx, externs, llmod, name, n);
357     let call_args: [ValueRef] = [];
358     for a: ValueRef in args {
359         call_args += [ZExtOrBitCast(cx, a, bcx_ccx(cx).int_type)];
360     }
361     ret Call(cx, llnative, call_args);
362 }
363
364 fn trans_free_if_not_gc(cx: @block_ctxt, v: ValueRef) -> @block_ctxt {
365     let ccx = bcx_ccx(cx);
366     if !ccx.sess.get_opts().do_gc {
367         Call(cx, ccx.upcalls.free,
368              [PointerCast(cx, v, T_ptr(T_i8())),
369               C_int(bcx_ccx(cx), 0)]);
370     }
371     ret cx;
372 }
373
374 fn trans_shared_free(cx: @block_ctxt, v: ValueRef) -> @block_ctxt {
375     Call(cx, bcx_ccx(cx).upcalls.shared_free,
376          [PointerCast(cx, v, T_ptr(T_i8()))]);
377     ret cx;
378 }
379
380 fn umax(cx: @block_ctxt, a: ValueRef, b: ValueRef) -> ValueRef {
381     let cond = ICmp(cx, lib::llvm::LLVMIntULT, a, b);
382     ret Select(cx, cond, b, a);
383 }
384
385 fn umin(cx: @block_ctxt, a: ValueRef, b: ValueRef) -> ValueRef {
386     let cond = ICmp(cx, lib::llvm::LLVMIntULT, a, b);
387     ret Select(cx, cond, a, b);
388 }
389
390 fn align_to(cx: @block_ctxt, off: ValueRef, align: ValueRef) -> ValueRef {
391     let mask = Sub(cx, align, C_int(bcx_ccx(cx), 1));
392     let bumped = Add(cx, off, mask);
393     ret And(cx, bumped, Not(cx, mask));
394 }
395
396
397 // Returns the real size of the given type for the current target.
398 fn llsize_of_real(cx: @crate_ctxt, t: TypeRef) -> uint {
399     ret llvm::LLVMStoreSizeOfType(cx.td.lltd, t);
400 }
401
402 // Returns the real alignment of the given type for the current target.
403 fn llalign_of_real(cx: @crate_ctxt, t: TypeRef) -> uint {
404     ret llvm::LLVMPreferredAlignmentOfType(cx.td.lltd, t);
405 }
406
407 fn llsize_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
408     ret llvm::LLVMConstIntCast(lib::llvm::llvm::LLVMSizeOf(t), cx.int_type,
409                                False);
410 }
411
412 fn llalign_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
413     ret llvm::LLVMConstIntCast(lib::llvm::llvm::LLVMAlignOf(t), cx.int_type,
414                                False);
415 }
416
417 fn size_of(cx: @block_ctxt, t: ty::t) -> result {
418     size_of_(cx, t, align_total)
419 }
420
421 tag align_mode {
422     align_total;
423     align_next(ty::t);
424 }
425
426 fn size_of_(cx: @block_ctxt, t: ty::t, mode: align_mode) -> result {
427     let ccx = bcx_ccx(cx);
428     if check type_has_static_size(ccx, t) {
429         let sp = cx.sp;
430         rslt(cx, llsize_of(bcx_ccx(cx), type_of(ccx, sp, t)))
431     } else { dynamic_size_of(cx, t, mode) }
432 }
433
434 fn align_of(cx: @block_ctxt, t: ty::t) -> result {
435     let ccx = bcx_ccx(cx);
436     if check type_has_static_size(ccx, t) {
437         let sp = cx.sp;
438         rslt(cx, llalign_of(bcx_ccx(cx), type_of(ccx, sp, t)))
439     } else { dynamic_align_of(cx, t) }
440 }
441
442 fn alloca(cx: @block_ctxt, t: TypeRef) -> ValueRef {
443     if cx.unreachable { ret llvm::LLVMGetUndef(t); }
444     ret Alloca(new_raw_block_ctxt(cx.fcx, cx.fcx.llstaticallocas), t);
445 }
446
447 fn dynastack_alloca(cx: @block_ctxt, t: TypeRef, n: ValueRef, ty: ty::t) ->
448    ValueRef {
449     if cx.unreachable { ret llvm::LLVMGetUndef(t); }
450     let bcx = cx;
451     let dy_cx = new_raw_block_ctxt(cx.fcx, cx.fcx.lldynamicallocas);
452     alt bcx_fcx(cx).llobstacktoken {
453       none. {
454         bcx_fcx(cx).llobstacktoken =
455             some(mk_obstack_token(bcx_ccx(cx), cx.fcx));
456       }
457       some(_) {/* no-op */ }
458     }
459
460     let dynastack_alloc = bcx_ccx(bcx).upcalls.dynastack_alloc;
461     let llsz = Mul(dy_cx,
462                    C_uint(bcx_ccx(bcx), llsize_of_real(bcx_ccx(bcx), t)),
463                    n);
464
465     let ti = none;
466     let lltydesc = get_tydesc(cx, ty, false, tps_normal, ti).result.val;
467
468     let llresult = Call(dy_cx, dynastack_alloc, [llsz, lltydesc]);
469     ret PointerCast(dy_cx, llresult, T_ptr(t));
470 }
471
472 fn mk_obstack_token(ccx: @crate_ctxt, fcx: @fn_ctxt) ->
473    ValueRef {
474     let cx = new_raw_block_ctxt(fcx, fcx.lldynamicallocas);
475     ret Call(cx, ccx.upcalls.dynastack_mark, []);
476 }
477
478
479 // Creates a simpler, size-equivalent type. The resulting type is guaranteed
480 // to have (a) the same size as the type that was passed in; (b) to be non-
481 // recursive. This is done by replacing all boxes in a type with boxed unit
482 // types.
483 fn simplify_type(ccx: @crate_ctxt, typ: ty::t) -> ty::t {
484     fn simplifier(ccx: @crate_ctxt, typ: ty::t) -> ty::t {
485         alt ty::struct(ccx.tcx, typ) {
486           ty::ty_box(_) { ret ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx)); }
487           ty::ty_uniq(_) {
488             ret ty::mk_imm_uniq(ccx.tcx, ty::mk_nil(ccx.tcx));
489           }
490           ty::ty_fn(_) {
491             ret ty::mk_tup(ccx.tcx,
492                            [ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx)),
493                             ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx))]);
494           }
495           ty::ty_obj(_) {
496             ret ty::mk_tup(ccx.tcx,
497                            [ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx)),
498                             ty::mk_imm_box(ccx.tcx, ty::mk_nil(ccx.tcx))]);
499           }
500           ty::ty_res(_, sub, tps) {
501             let sub1 = ty::substitute_type_params(ccx.tcx, tps, sub);
502             ret ty::mk_tup(ccx.tcx,
503                            [ty::mk_int(ccx.tcx), simplify_type(ccx, sub1)]);
504           }
505           _ { ret typ; }
506         }
507     }
508     ret ty::fold_ty(ccx.tcx, ty::fm_general(bind simplifier(ccx, _)), typ);
509 }
510
511
512 // Computes the size of the data part of a non-dynamically-sized tag.
513 fn static_size_of_tag(cx: @crate_ctxt, sp: span, t: ty::t)
514     : type_has_static_size(cx, t) -> uint {
515     if cx.tag_sizes.contains_key(t) { ret cx.tag_sizes.get(t); }
516     alt ty::struct(cx.tcx, t) {
517       ty::ty_tag(tid, subtys) {
518         // Compute max(variant sizes).
519
520         let max_size = 0u;
521         let variants = ty::tag_variants(cx.tcx, tid);
522         for variant: ty::variant_info in *variants {
523             let tup_ty = simplify_type(cx, ty::mk_tup(cx.tcx, variant.args));
524             // Perform any type parameter substitutions.
525
526             tup_ty = ty::substitute_type_params(cx.tcx, subtys, tup_ty);
527             // Here we possibly do a recursive call.
528
529             // FIXME: Avoid this check. Since the parent has static
530             // size, any field must as well. There should be a way to
531             // express that with constrained types.
532             check (type_has_static_size(cx, tup_ty));
533             let this_size = llsize_of_real(cx, type_of(cx, sp, tup_ty));
534             if max_size < this_size { max_size = this_size; }
535         }
536         cx.tag_sizes.insert(t, max_size);
537         ret max_size;
538       }
539       _ {
540         cx.tcx.sess.span_fatal(sp, "non-tag passed to static_size_of_tag()");
541       }
542     }
543 }
544
545 fn dynamic_size_of(cx: @block_ctxt, t: ty::t, mode: align_mode) -> result {
546     fn align_elements(cx: @block_ctxt, elts: [ty::t],
547                       mode: align_mode) -> result {
548         //
549         // C padding rules:
550         //
551         //
552         //   - Pad after each element so that next element is aligned.
553         //   - Pad after final structure member so that whole structure
554         //     is aligned to max alignment of interior.
555         //
556
557         let off = C_int(bcx_ccx(cx), 0);
558         let max_align = C_int(bcx_ccx(cx), 1);
559         let bcx = cx;
560         for e: ty::t in elts {
561             let elt_align = align_of(bcx, e);
562             bcx = elt_align.bcx;
563             let elt_size = size_of(bcx, e);
564             bcx = elt_size.bcx;
565             let aligned_off = align_to(bcx, off, elt_align.val);
566             off = Add(bcx, aligned_off, elt_size.val);
567             max_align = umax(bcx, max_align, elt_align.val);
568         }
569         off = alt mode {
570           align_total. {
571             align_to(bcx, off, max_align)
572           }
573           align_next(t) {
574             let {bcx, val: align} = align_of(bcx, t);
575             align_to(bcx, off, align)
576           }
577         };
578         ret rslt(bcx, off);
579     }
580     alt ty::struct(bcx_tcx(cx), t) {
581       ty::ty_param(p, _) {
582         let szptr = field_of_tydesc(cx, t, false, abi::tydesc_field_size);
583         ret rslt(szptr.bcx, Load(szptr.bcx, szptr.val));
584       }
585       ty::ty_rec(flds) {
586         let tys: [ty::t] = [];
587         for f: ty::field in flds { tys += [f.mt.ty]; }
588         ret align_elements(cx, tys, mode);
589       }
590       ty::ty_tup(elts) {
591         let tys = [];
592         for tp in elts { tys += [tp]; }
593         ret align_elements(cx, tys, mode);
594       }
595       ty::ty_tag(tid, tps) {
596         let bcx = cx;
597         let ccx = bcx_ccx(bcx);
598         // Compute max(variant sizes).
599
600         let max_size: ValueRef = alloca(bcx, ccx.int_type);
601         Store(bcx, C_int(ccx, 0), max_size);
602         let variants = ty::tag_variants(bcx_tcx(bcx), tid);
603         for variant: ty::variant_info in *variants {
604             // Perform type substitution on the raw argument types.
605
606             let raw_tys: [ty::t] = variant.args;
607             let tys: [ty::t] = [];
608             for raw_ty: ty::t in raw_tys {
609                 let t = ty::substitute_type_params(bcx_tcx(cx), tps, raw_ty);
610                 tys += [t];
611             }
612             let rslt = align_elements(bcx, tys, mode);
613             bcx = rslt.bcx;
614             let this_size = rslt.val;
615             let old_max_size = Load(bcx, max_size);
616             Store(bcx, umax(bcx, this_size, old_max_size), max_size);
617         }
618         let max_size_val = Load(bcx, max_size);
619         let total_size =
620             if vec::len(*variants) != 1u {
621                 Add(bcx, max_size_val, llsize_of(ccx, ccx.int_type))
622             } else { max_size_val };
623         ret rslt(bcx, total_size);
624       }
625     }
626 }
627
628 fn dynamic_align_of(cx: @block_ctxt, t: ty::t) -> result {
629 // FIXME: Typestate constraint that shows this alt is
630 // exhaustive
631     alt ty::struct(bcx_tcx(cx), t) {
632       ty::ty_param(p, _) {
633         let aptr = field_of_tydesc(cx, t, false, abi::tydesc_field_align);
634         ret rslt(aptr.bcx, Load(aptr.bcx, aptr.val));
635       }
636       ty::ty_rec(flds) {
637         let a = C_int(bcx_ccx(cx), 1);
638         let bcx = cx;
639         for f: ty::field in flds {
640             let align = align_of(bcx, f.mt.ty);
641             bcx = align.bcx;
642             a = umax(bcx, a, align.val);
643         }
644         ret rslt(bcx, a);
645       }
646       ty::ty_tag(_, _) {
647         ret rslt(cx, C_int(bcx_ccx(cx), 1)); // FIXME: stub
648       }
649       ty::ty_tup(elts) {
650         let a = C_int(bcx_ccx(cx), 1);
651         let bcx = cx;
652         for e in elts {
653             let align = align_of(bcx, e);
654             bcx = align.bcx;
655             a = umax(bcx, a, align.val);
656         }
657         ret rslt(bcx, a);
658       }
659     }
660 }
661
662 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
663 // The type of the returned pointer is always i8*.  If you care about the
664 // return type, use bump_ptr().
665 fn ptr_offs(bcx: @block_ctxt, base: ValueRef, sz: ValueRef) -> ValueRef {
666     let raw = PointerCast(bcx, base, T_ptr(T_i8()));
667     GEP(bcx, raw, [sz])
668 }
669
670 // Increment a pointer by a given amount and then cast it to be a pointer
671 // to a given type.
672 fn bump_ptr(bcx: @block_ctxt, t: ty::t, base: ValueRef, sz: ValueRef) ->
673    ValueRef {
674     let ccx = bcx_ccx(bcx);
675     let bumped = ptr_offs(bcx, base, sz);
676     if check type_has_static_size(ccx, t) {
677         let sp = bcx.sp;
678         let typ = T_ptr(type_of(ccx, sp, t));
679         PointerCast(bcx, bumped, typ)
680     } else { bumped }
681 }
682
683 // GEP_tup_like is a pain to use if you always have to precede it with a
684 // check.
685 fn GEP_tup_like_1(cx: @block_ctxt, t: ty::t, base: ValueRef, ixs: [int])
686     -> result {
687     check type_is_tup_like(cx, t);
688     ret GEP_tup_like(cx, t, base, ixs);
689 }
690
691 // Replacement for the LLVM 'GEP' instruction when field-indexing into a
692 // tuple-like structure (tup, rec) with a static index. This one is driven off
693 // ty::struct and knows what to do when it runs into a ty_param stuck in the
694 // middle of the thing it's GEP'ing into. Much like size_of and align_of,
695 // above.
696 fn GEP_tup_like(bcx: @block_ctxt, t: ty::t, base: ValueRef, ixs: [int])
697     : type_is_tup_like(bcx, t) -> result {
698     // It might be a static-known type. Handle this.
699     if !ty::type_has_dynamic_size(bcx_tcx(bcx), t) {
700         ret rslt(bcx, GEPi(bcx, base, ixs));
701     }
702     // It is a dynamic-containing type that, if we convert directly to an LLVM
703     // TypeRef, will be all wrong; there's no proper LLVM type to represent
704     // it, and the lowering function will stick in i8* values for each
705     // ty_param, which is not right; the ty_params are all of some dynamic
706     // size.
707     //
708     // What we must do instead is sadder. We must look through the indices
709     // manually and split the input type into a prefix and a target. We then
710     // measure the prefix size, bump the input pointer by that amount, and
711     // cast to a pointer-to-target type.
712
713     // Given a type, an index vector and an element number N in that vector,
714     // calculate index X and the type that results by taking the first X-1
715     // elements of the type and splitting the Xth off. Return the prefix as
716     // well as the innermost Xth type.
717
718     fn split_type(ccx: @crate_ctxt, t: ty::t, ixs: [int], n: uint) ->
719        {prefix: [ty::t], target: ty::t} {
720         let len: uint = vec::len::<int>(ixs);
721         // We don't support 0-index or 1-index GEPs: The former is nonsense
722         // and the latter would only be meaningful if we supported non-0
723         // values for the 0th index (we don't).
724
725         assert (len > 1u);
726         if n == 0u {
727             // Since we're starting from a value that's a pointer to a
728             // *single* structure, the first index (in GEP-ese) should just be
729             // 0, to yield the pointee.
730
731             assert (ixs[n] == 0);
732             ret split_type(ccx, t, ixs, n + 1u);
733         }
734         assert (n < len);
735         let ix: int = ixs[n];
736         let prefix: [ty::t] = [];
737         let i: int = 0;
738         while i < ix {
739             prefix += [ty::get_element_type(ccx.tcx, t, i as uint)];
740             i += 1;
741         }
742         let selected = ty::get_element_type(ccx.tcx, t, i as uint);
743         if n == len - 1u {
744             // We are at the innermost index.
745
746             ret {prefix: prefix, target: selected};
747         } else {
748             // Not the innermost index; call self recursively to dig deeper.
749             // Once we get an inner result, append it current prefix and
750             // return to caller.
751
752             let inner = split_type(ccx, selected, ixs, n + 1u);
753             prefix += inner.prefix;
754             ret {prefix: prefix with inner};
755         }
756     }
757     // We make a fake prefix tuple-type here; luckily for measuring sizes
758     // the tuple parens are associative so it doesn't matter that we've
759     // flattened the incoming structure.
760
761     let s = split_type(bcx_ccx(bcx), t, ixs, 0u);
762
763     let args = [];
764     for typ: ty::t in s.prefix { args += [typ]; }
765     let prefix_ty = ty::mk_tup(bcx_tcx(bcx), args);
766
767     let sz = size_of_(bcx, prefix_ty, align_next(s.target));
768     ret rslt(sz.bcx, bump_ptr(sz.bcx, s.target, base, sz.val));
769 }
770
771
772 // Replacement for the LLVM 'GEP' instruction when field indexing into a tag.
773 // This function uses GEP_tup_like() above and automatically performs casts as
774 // appropriate. @llblobptr is the data part of a tag value; its actual type is
775 // meaningless, as it will be cast away.
776 fn GEP_tag(cx: @block_ctxt, llblobptr: ValueRef, tag_id: ast::def_id,
777            variant_id: ast::def_id, ty_substs: [ty::t],
778            ix: uint) : valid_variant_index(ix, cx, tag_id, variant_id) ->
779    result {
780     let variant = ty::tag_variant_with_id(bcx_tcx(cx), tag_id, variant_id);
781     // Synthesize a tuple type so that GEP_tup_like() can work its magic.
782     // Separately, store the type of the element we're interested in.
783
784     let arg_tys = variant.args;
785
786     let true_arg_tys: [ty::t] = [];
787     for aty: ty::t in arg_tys {
788         let arg_ty = ty::substitute_type_params(bcx_tcx(cx), ty_substs, aty);
789         true_arg_tys += [arg_ty];
790     }
791
792     // We know that ix < len(variant.args) -- so
793     // it's safe to do this. (Would be nice to have
794     // typestate guarantee that a dynamic bounds check
795     // error can't happen here, but that's in the future.)
796     let elem_ty = true_arg_tys[ix];
797
798     let tup_ty = ty::mk_tup(bcx_tcx(cx), true_arg_tys);
799     // Cast the blob pointer to the appropriate type, if we need to (i.e. if
800     // the blob pointer isn't dynamically sized).
801
802     let llunionptr: ValueRef;
803     let sp = cx.sp;
804     let ccx = bcx_ccx(cx);
805     if check type_has_static_size(ccx, tup_ty) {
806         let llty = type_of(ccx, sp, tup_ty);
807         llunionptr = TruncOrBitCast(cx, llblobptr, T_ptr(llty));
808     } else { llunionptr = llblobptr; }
809
810     // Do the GEP_tup_like().
811     // Silly check -- postcondition on mk_tup?
812     check type_is_tup_like(cx, tup_ty);
813     let rs = GEP_tup_like(cx, tup_ty, llunionptr, [0, ix as int]);
814     // Cast the result to the appropriate type, if necessary.
815
816     let rs_ccx = bcx_ccx(rs.bcx);
817     let val =
818         if check type_has_static_size(rs_ccx, elem_ty) {
819             let llelemty = type_of(rs_ccx, sp, elem_ty);
820             PointerCast(rs.bcx, rs.val, T_ptr(llelemty))
821         } else { rs.val };
822
823     ret rslt(rs.bcx, val);
824 }
825
826 // trans_shared_malloc: expects a type indicating which pointer type we want
827 // and a size indicating how much space we want malloc'd.
828 fn trans_shared_malloc(cx: @block_ctxt, llptr_ty: TypeRef, llsize: ValueRef)
829    -> result {
830     // FIXME: need a table to collect tydesc globals.
831
832     let tydesc = C_null(T_ptr(bcx_ccx(cx).tydesc_type));
833     let rval =
834         Call(cx, bcx_ccx(cx).upcalls.shared_malloc,
835              [llsize, tydesc]);
836     ret rslt(cx, PointerCast(cx, rval, llptr_ty));
837 }
838
839 // trans_malloc_boxed_raw: expects an unboxed type and returns a pointer to
840 // enough space for something of that type, along with space for a reference
841 // count; in other words, it allocates a box for something of that type.
842 fn trans_malloc_boxed_raw(cx: @block_ctxt, t: ty::t) -> result {
843     let bcx = cx;
844
845     // Synthesize a fake box type structurally so we have something
846     // to measure the size of.
847
848     // We synthesize two types here because we want both the type of the
849     // pointer and the pointee.  boxed_body is the type that we measure the
850     // size of; box_ptr is the type that's converted to a TypeRef and used as
851     // the pointer cast target in trans_raw_malloc.
852
853     // The mk_int here is the space being
854     // reserved for the refcount.
855     let boxed_body = ty::mk_tup(bcx_tcx(bcx), [ty::mk_int(bcx_tcx(cx)), t]);
856     let box_ptr = ty::mk_imm_box(bcx_tcx(bcx), t);
857     let r = size_of(cx, boxed_body);
858     let llsz = r.val; bcx = r.bcx;
859
860     // Grab the TypeRef type of box_ptr, because that's what trans_raw_malloc
861     // wants.
862     // FIXME: Could avoid this check with a postcondition on mk_imm_box?
863     // (requires Issue #586)
864     let ccx = bcx_ccx(bcx);
865     let sp = bcx.sp;
866     check (type_has_static_size(ccx, box_ptr));
867     let llty = type_of(ccx, sp, box_ptr);
868
869     let ti = none;
870     let tydesc_result = get_tydesc(bcx, t, true, tps_normal, ti);
871     let lltydesc = tydesc_result.result.val; bcx = tydesc_result.result.bcx;
872
873     let rval = Call(cx, ccx.upcalls.malloc,
874                     [llsz, lltydesc]);
875     ret rslt(cx, PointerCast(cx, rval, llty));
876 }
877
878 // trans_malloc_boxed: usefully wraps trans_malloc_box_raw; allocates a box,
879 // initializes the reference count to 1, and pulls out the body and rc
880 fn trans_malloc_boxed(cx: @block_ctxt, t: ty::t) ->
881    {bcx: @block_ctxt, box: ValueRef, body: ValueRef} {
882     let res = trans_malloc_boxed_raw(cx, t);
883     let box = res.val;
884     let rc = GEPi(res.bcx, box, [0, abi::box_rc_field_refcnt]);
885     Store(res.bcx, C_int(bcx_ccx(cx), 1), rc);
886     let body = GEPi(res.bcx, box, [0, abi::box_rc_field_body]);
887     ret {bcx: res.bcx, box: res.val, body: body};
888 }
889
890 // Type descriptor and type glue stuff
891
892 // Given a type and a field index into its corresponding type descriptor,
893 // returns an LLVM ValueRef of that field from the tydesc, generating the
894 // tydesc if necessary.
895 fn field_of_tydesc(cx: @block_ctxt, t: ty::t, escapes: bool, field: int) ->
896    result {
897     let ti = none::<@tydesc_info>;
898     let tydesc = get_tydesc(cx, t, escapes, tps_normal, ti).result;
899     ret rslt(tydesc.bcx,
900              GEPi(tydesc.bcx, tydesc.val, [0, field]));
901 }
902
903 // Given a type containing ty params, build a vector containing a ValueRef for
904 // each of the ty params it uses (from the current frame) and a vector of the
905 // indices of the ty params present in the type. This is used solely for
906 // constructing derived tydescs.
907 fn linearize_ty_params(cx: @block_ctxt, t: ty::t) ->
908    {params: [uint], descs: [ValueRef]} {
909     let param_vals: [ValueRef] = [];
910     let param_defs: [uint] = [];
911     type rr =
912         {cx: @block_ctxt, mutable vals: [ValueRef], mutable defs: [uint]};
913
914     fn linearizer(r: @rr, t: ty::t) {
915         alt ty::struct(bcx_tcx(r.cx), t) {
916           ty::ty_param(pid, _) {
917             let seen: bool = false;
918             for d: uint in r.defs { if d == pid { seen = true; } }
919             if !seen {
920                 r.vals += [r.cx.fcx.lltyparams[pid].desc];
921                 r.defs += [pid];
922             }
923           }
924           _ { }
925         }
926     }
927     let x = @{cx: cx, mutable vals: param_vals, mutable defs: param_defs};
928     let f = bind linearizer(x, _);
929     ty::walk_ty(bcx_tcx(cx), f, t);
930     ret {params: x.defs, descs: x.vals};
931 }
932
933 fn trans_stack_local_derived_tydesc(cx: @block_ctxt, llsz: ValueRef,
934                                     llalign: ValueRef, llroottydesc: ValueRef,
935                                     llfirstparam: ValueRef, n_params: uint,
936                                     obj_params: uint) -> ValueRef {
937     let llmyroottydesc = alloca(cx, bcx_ccx(cx).tydesc_type);
938
939     // By convention, desc 0 is the root descriptor.
940     let llroottydesc = Load(cx, llroottydesc);
941     Store(cx, llroottydesc, llmyroottydesc);
942
943     // Store a pointer to the rest of the descriptors.
944     let ccx = bcx_ccx(cx);
945     store_inbounds(cx, llfirstparam, llmyroottydesc,
946                    [0, abi::tydesc_field_first_param]);
947     store_inbounds(cx, C_uint(ccx, n_params), llmyroottydesc,
948                    [0, abi::tydesc_field_n_params]);
949     store_inbounds(cx, llsz, llmyroottydesc,
950                    [0, abi::tydesc_field_size]);
951     store_inbounds(cx, llalign, llmyroottydesc,
952                    [0, abi::tydesc_field_align]);
953     store_inbounds(cx, C_uint(ccx, obj_params), llmyroottydesc,
954                    [0, abi::tydesc_field_obj_params]);
955     ret llmyroottydesc;
956 }
957
958 // Objects and closures store their type parameters differently (in the object
959 // or closure itself rather than in the type descriptor).
960 tag ty_param_storage { tps_normal; tps_obj(uint); tps_fn(uint); }
961
962 fn get_derived_tydesc(cx: @block_ctxt, t: ty::t, escapes: bool,
963                       storage: ty_param_storage,
964                       &static_ti: option::t<@tydesc_info>) -> result {
965     alt cx.fcx.derived_tydescs.find(t) {
966       some(info) {
967         // If the tydesc escapes in this context, the cached derived
968         // tydesc also has to be one that was marked as escaping.
969         if !(escapes && !info.escapes) && storage == tps_normal {
970             ret rslt(cx, info.lltydesc);
971         }
972       }
973       none. {/* fall through */ }
974     }
975
976     let is_obj_body;
977     alt storage {
978         tps_normal. { is_obj_body = false; }
979         tps_obj(_) | tps_fn(_) { is_obj_body = true; }
980     }
981
982     bcx_ccx(cx).stats.n_derived_tydescs += 1u;
983     let bcx = new_raw_block_ctxt(cx.fcx, cx.fcx.llderivedtydescs);
984     let tys = linearize_ty_params(bcx, t);
985     let root_ti = get_static_tydesc(bcx, t, tys.params, is_obj_body);
986     static_ti = some::<@tydesc_info>(root_ti);
987     lazily_emit_all_tydesc_glue(cx, static_ti);
988     let root = root_ti.tydesc;
989     let sz = size_of(bcx, t);
990     bcx = sz.bcx;
991     let align = align_of(bcx, t);
992     bcx = align.bcx;
993
994     // Store the captured type descriptors in an alloca if the caller isn't
995     // promising to do so itself.
996     let n_params = ty::count_ty_params(bcx_tcx(bcx), t);
997
998     assert (n_params == vec::len::<uint>(tys.params));
999     assert (n_params == vec::len::<ValueRef>(tys.descs));
1000
1001     let llparamtydescs =
1002         alloca(bcx, T_array(T_ptr(bcx_ccx(bcx).tydesc_type), n_params + 1u));
1003     let i = 0;
1004
1005     // If the type descriptor escapes, we need to add in the root as
1006     // the first parameter, because upcall_get_type_desc() expects it.
1007     if escapes {
1008         Store(bcx, root, GEPi(bcx, llparamtydescs, [0, 0]));
1009         i += 1;
1010     }
1011
1012     for td: ValueRef in tys.descs {
1013         Store(bcx, td, GEPi(bcx, llparamtydescs, [0, i]));
1014         i += 1;
1015     }
1016
1017     let llfirstparam =
1018         PointerCast(bcx, llparamtydescs,
1019                     T_ptr(T_ptr(bcx_ccx(bcx).tydesc_type)));
1020
1021     // The top bit indicates whether this type descriptor describes an object
1022     // (0) or a function (1).
1023     let obj_params;
1024     alt storage {
1025       tps_normal. { obj_params = 0u; }
1026       tps_obj(np) { obj_params = np; }
1027       tps_fn(np) { obj_params = 0x80000000u | np; }
1028     }
1029
1030     let v;
1031     if escapes {
1032         let ccx = bcx_ccx(bcx);
1033         let td_val =
1034             Call(bcx, ccx.upcalls.get_type_desc,
1035                  [C_null(T_ptr(T_nil())), sz.val,
1036                   align.val, C_uint(ccx, 1u + n_params), llfirstparam,
1037                   C_uint(ccx, obj_params)]);
1038         v = td_val;
1039     } else {
1040         v =
1041             trans_stack_local_derived_tydesc(bcx, sz.val, align.val, root,
1042                                              llfirstparam, n_params,
1043                                              obj_params);
1044     }
1045     bcx.fcx.derived_tydescs.insert(t, {lltydesc: v, escapes: escapes});
1046     ret rslt(cx, v);
1047 }
1048
1049 type get_tydesc_result = {kind: tydesc_kind, result: result};
1050
1051 fn get_tydesc(cx: @block_ctxt, t: ty::t, escapes: bool,
1052               storage: ty_param_storage, &static_ti: option::t<@tydesc_info>)
1053    -> get_tydesc_result {
1054
1055     // Is the supplied type a type param? If so, return the passed-in tydesc.
1056     alt ty::type_param(bcx_tcx(cx), t) {
1057       some(id) {
1058         if id < vec::len(cx.fcx.lltyparams) {
1059             ret {kind: tk_param,
1060                  result: rslt(cx, cx.fcx.lltyparams[id].desc)};
1061         } else {
1062             bcx_tcx(cx).sess.span_bug(cx.sp,
1063                                       "Unbound typaram in get_tydesc: " +
1064                                           "t = " +
1065                                           ty_to_str(bcx_tcx(cx), t) +
1066                                           " ty_param = " +
1067                                           uint::str(id));
1068         }
1069       }
1070       none. {/* fall through */ }
1071     }
1072
1073     // Does it contain a type param? If so, generate a derived tydesc.
1074     if ty::type_contains_params(bcx_tcx(cx), t) {
1075         ret {kind: tk_derived,
1076              result: get_derived_tydesc(cx, t, escapes, storage, static_ti)};
1077     }
1078     // Otherwise, generate a tydesc if necessary, and return it.
1079     let info = get_static_tydesc(cx, t, [], false);
1080     static_ti = some::<@tydesc_info>(info);
1081     ret {kind: tk_static, result: rslt(cx, info.tydesc)};
1082 }
1083
1084 fn get_static_tydesc(cx: @block_ctxt, t: ty::t, ty_params: [uint],
1085                      is_obj_body: bool) -> @tydesc_info {
1086     alt bcx_ccx(cx).tydescs.find(t) {
1087       some(info) { ret info; }
1088       none. {
1089         bcx_ccx(cx).stats.n_static_tydescs += 1u;
1090         let info = declare_tydesc(cx.fcx.lcx, cx.sp, t, ty_params,
1091                                   is_obj_body);
1092         bcx_ccx(cx).tydescs.insert(t, info);
1093         ret info;
1094       }
1095     }
1096 }
1097
1098 fn set_no_inline(f: ValueRef) {
1099     llvm::LLVMAddFunctionAttr(f,
1100                               lib::llvm::LLVMNoInlineAttribute as
1101                                   lib::llvm::llvm::Attribute,
1102                               0u);
1103 }
1104
1105 // Tell LLVM to emit the information necessary to unwind the stack for the
1106 // function f.
1107 fn set_uwtable(f: ValueRef) {
1108     llvm::LLVMAddFunctionAttr(f,
1109                               lib::llvm::LLVMUWTableAttribute as
1110                                   lib::llvm::llvm::Attribute,
1111                               0u);
1112 }
1113
1114 fn set_always_inline(f: ValueRef) {
1115     llvm::LLVMAddFunctionAttr(f,
1116                               lib::llvm::LLVMAlwaysInlineAttribute as
1117                                   lib::llvm::llvm::Attribute,
1118                               0u);
1119 }
1120
1121 fn set_custom_stack_growth_fn(f: ValueRef) {
1122     // TODO: Remove this hack to work around the lack of u64 in the FFI.
1123     llvm::LLVMAddFunctionAttr(f, 0 as lib::llvm::llvm::Attribute, 1u);
1124 }
1125
1126 fn set_glue_inlining(cx: @local_ctxt, f: ValueRef, t: ty::t) {
1127     if ty::type_is_structural(cx.ccx.tcx, t) {
1128         set_no_inline(f);
1129     } else { set_always_inline(f); }
1130 }
1131
1132
1133 // Generates the declaration for (but doesn't emit) a type descriptor.
1134 fn declare_tydesc(cx: @local_ctxt, sp: span, t: ty::t, ty_params: [uint],
1135                   is_obj_body: bool) ->
1136    @tydesc_info {
1137     log(debug, "+++ declare_tydesc " + ty_to_str(cx.ccx.tcx, t));
1138     let ccx = cx.ccx;
1139     let llsize;
1140     let llalign;
1141     if check type_has_static_size(ccx, t) {
1142         let llty = type_of(ccx, sp, t);
1143         llsize = llsize_of(ccx, llty);
1144         llalign = llalign_of(ccx, llty);
1145     } else {
1146         // These will be overwritten as the derived tydesc is generated, so
1147         // we create placeholder values.
1148
1149         llsize = C_int(ccx, 0);
1150         llalign = C_int(ccx, 0);
1151     }
1152     let name;
1153     if cx.ccx.sess.get_opts().debuginfo {
1154         name = mangle_internal_name_by_type_only(cx.ccx, t, "tydesc");
1155         name = sanitize(name);
1156     } else { name = mangle_internal_name_by_seq(cx.ccx, "tydesc"); }
1157     let gvar =
1158         str::as_buf(name,
1159                     {|buf|
1160                         llvm::LLVMAddGlobal(ccx.llmod, ccx.tydesc_type, buf)
1161                     });
1162     let info =
1163         @{ty: t,
1164           tydesc: gvar,
1165           size: llsize,
1166           align: llalign,
1167           mutable take_glue: none::<ValueRef>,
1168           mutable drop_glue: none::<ValueRef>,
1169           mutable free_glue: none::<ValueRef>,
1170           mutable cmp_glue: none::<ValueRef>,
1171           ty_params: ty_params,
1172           is_obj_body: is_obj_body};
1173     log(debug, "--- declare_tydesc " + ty_to_str(cx.ccx.tcx, t));
1174     ret info;
1175 }
1176
1177 type glue_helper = fn(@block_ctxt, ValueRef, ty::t);
1178
1179 fn declare_generic_glue(cx: @local_ctxt, t: ty::t, llfnty: TypeRef, name: str)
1180    -> ValueRef {
1181     let name = name;
1182     let fn_nm;
1183     if cx.ccx.sess.get_opts().debuginfo {
1184         fn_nm = mangle_internal_name_by_type_only(cx.ccx, t, "glue_" + name);
1185         fn_nm = sanitize(fn_nm);
1186     } else { fn_nm = mangle_internal_name_by_seq(cx.ccx, "glue_" + name); }
1187     let llfn = decl_cdecl_fn(cx.ccx.llmod, fn_nm, llfnty);
1188     set_glue_inlining(cx, llfn, t);
1189     ret llfn;
1190 }
1191
1192 // FIXME: was this causing the leak?
1193 fn make_generic_glue_inner(cx: @local_ctxt, sp: span, t: ty::t,
1194                            llfn: ValueRef, helper: glue_helper,
1195                            ty_params: [uint]) -> ValueRef {
1196     let fcx = new_fn_ctxt(cx, sp, llfn);
1197     llvm::LLVMSetLinkage(llfn,
1198                          lib::llvm::LLVMInternalLinkage as llvm::Linkage);
1199     cx.ccx.stats.n_glues_created += 1u;
1200     // Any nontrivial glue is with values passed *by alias*; this is a
1201     // requirement since in many contexts glue is invoked indirectly and
1202     // the caller has no idea if it's dealing with something that can be
1203     // passed by value.
1204
1205     let ccx = cx.ccx;
1206     let llty =
1207         if check type_has_static_size(ccx, t) {
1208             T_ptr(type_of(ccx, sp, t))
1209         } else { T_ptr(T_i8()) };
1210
1211     let ty_param_count = vec::len::<uint>(ty_params);
1212     let lltyparams = llvm::LLVMGetParam(llfn, 2u);
1213     let load_env_bcx = new_raw_block_ctxt(fcx, fcx.llloadenv);
1214     let lltydescs = [mutable];
1215     let p = 0u;
1216     while p < ty_param_count {
1217         let llparam = GEPi(load_env_bcx, lltyparams, [p as int]);
1218         llparam = Load(load_env_bcx, llparam);
1219         vec::grow_set(lltydescs, ty_params[p], 0 as ValueRef, llparam);
1220         p += 1u;
1221     }
1222
1223     fcx.lltyparams = vec::map_mut(lltydescs, {|d| {desc: d, dicts: none}});
1224
1225     let bcx = new_top_block_ctxt(fcx);
1226     let lltop = bcx.llbb;
1227     let llrawptr0 = llvm::LLVMGetParam(llfn, 3u);
1228     let llval0 = BitCast(bcx, llrawptr0, llty);
1229     helper(bcx, llval0, t);
1230     finish_fn(fcx, lltop);
1231     ret llfn;
1232 }
1233
1234 fn make_generic_glue(cx: @local_ctxt, sp: span, t: ty::t, llfn: ValueRef,
1235                      helper: glue_helper, ty_params: [uint], name: str) ->
1236    ValueRef {
1237     if !cx.ccx.sess.get_opts().stats {
1238         ret make_generic_glue_inner(cx, sp, t, llfn, helper, ty_params);
1239     }
1240
1241     let start = time::get_time();
1242     let llval = make_generic_glue_inner(cx, sp, t, llfn, helper, ty_params);
1243     let end = time::get_time();
1244     log_fn_time(cx.ccx, "glue " + name + " " + ty_to_short_str(cx.ccx.tcx, t),
1245                 start, end);
1246     ret llval;
1247 }
1248
1249 fn emit_tydescs(ccx: @crate_ctxt) {
1250     ccx.tydescs.items {|key, val|
1251         let glue_fn_ty = T_ptr(T_glue_fn(ccx));
1252         let cmp_fn_ty = T_ptr(T_cmp_glue_fn(ccx));
1253         let ti = val;
1254         let take_glue =
1255             alt ti.take_glue {
1256               none. { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
1257               some(v) { ccx.stats.n_real_glues += 1u; v }
1258             };
1259         let drop_glue =
1260             alt ti.drop_glue {
1261               none. { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
1262               some(v) { ccx.stats.n_real_glues += 1u; v }
1263             };
1264         let free_glue =
1265             alt ti.free_glue {
1266               none. { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
1267               some(v) { ccx.stats.n_real_glues += 1u; v }
1268             };
1269         let cmp_glue =
1270             alt ti.cmp_glue {
1271               none. { ccx.stats.n_null_glues += 1u; C_null(cmp_fn_ty) }
1272               some(v) { ccx.stats.n_real_glues += 1u; v }
1273             };
1274
1275         let shape = shape::shape_of(ccx, key, ti.ty_params,
1276                                     ti.is_obj_body);
1277         let shape_tables =
1278             llvm::LLVMConstPointerCast(ccx.shape_cx.llshapetables,
1279                                        T_ptr(T_i8()));
1280
1281         let tydesc =
1282             C_named_struct(ccx.tydesc_type,
1283                            [C_null(T_ptr(T_ptr(ccx.tydesc_type))),
1284                             ti.size, // size
1285                             ti.align, // align
1286                             take_glue, // take_glue
1287                             drop_glue, // drop_glue
1288                             free_glue, // free_glue
1289                             C_null(T_ptr(T_i8())), // unused
1290                             C_null(glue_fn_ty), // sever_glue
1291                             C_null(glue_fn_ty), // mark_glue
1292                             C_null(glue_fn_ty), // unused
1293                             cmp_glue, // cmp_glue
1294                             C_shape(ccx, shape), // shape
1295                             shape_tables, // shape_tables
1296                             C_int(ccx, 0), // n_params
1297                             C_int(ccx, 0)]); // n_obj_params
1298
1299         let gvar = ti.tydesc;
1300         llvm::LLVMSetInitializer(gvar, tydesc);
1301         llvm::LLVMSetGlobalConstant(gvar, True);
1302         llvm::LLVMSetLinkage(gvar,
1303                              lib::llvm::LLVMInternalLinkage as llvm::Linkage);
1304     };
1305 }
1306
1307 fn make_take_glue(cx: @block_ctxt, v: ValueRef, t: ty::t) {
1308
1309     let bcx = cx;
1310     let tcx = bcx_tcx(cx);
1311     // NB: v is an *alias* of type t here, not a direct value.
1312     bcx = alt ty::struct(tcx, t) {
1313       ty::ty_box(_) {
1314         incr_refcnt_of_boxed(bcx, Load(bcx, v))
1315       }
1316       ty::ty_uniq(_) {
1317         check trans_uniq::type_is_unique_box(bcx, t);
1318         let r = trans_uniq::duplicate(bcx, Load(bcx, v), t);
1319         Store(r.bcx, r.val, v);
1320         r.bcx
1321       }
1322       ty::ty_vec(_) | ty::ty_str. {
1323         let r = tvec::duplicate(bcx, Load(bcx, v), t);
1324         Store(r.bcx, r.val, v);
1325         r.bcx
1326       }
1327       ty::ty_send_type. {
1328         // sendable type descriptors are basically unique pointers,
1329         // they must be cloned when copied:
1330         let r = Load(bcx, v);
1331         let s = Call(bcx, bcx_ccx(bcx).upcalls.create_shared_type_desc, [r]);
1332         Store(bcx, s, v);
1333         bcx
1334       }
1335       ty::ty_native_fn(_, _) | ty::ty_fn(_) {
1336         trans_closure::make_fn_glue(bcx, v, t, take_ty)
1337       }
1338       ty::ty_opaque_closure_ptr(ck) {
1339         trans_closure::make_opaque_cbox_take_glue(bcx, ck, v)
1340       }
1341       _ when ty::type_is_structural(bcx_tcx(bcx), t) {
1342         iter_structural_ty(bcx, v, t, take_ty)
1343       }
1344       _ { bcx }
1345     };
1346
1347     build_return(bcx);
1348 }
1349
1350 fn incr_refcnt_of_boxed(cx: @block_ctxt, box_ptr: ValueRef) -> @block_ctxt {
1351     let ccx = bcx_ccx(cx);
1352     let rc_ptr =
1353         GEPi(cx, box_ptr, [0, abi::box_rc_field_refcnt]);
1354     let rc = Load(cx, rc_ptr);
1355     rc = Add(cx, rc, C_int(ccx, 1));
1356     Store(cx, rc, rc_ptr);
1357     ret cx;
1358 }
1359
1360 fn free_box(bcx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1361     ret alt ty::struct(bcx_tcx(bcx), t) {
1362       ty::ty_box(body_mt) {
1363         let v = PointerCast(bcx, v, type_of_1(bcx, t));
1364         let body = GEPi(bcx, v, [0, abi::box_rc_field_body]);
1365         let bcx = drop_ty(bcx, body, body_mt.ty);
1366         trans_free_if_not_gc(bcx, v)
1367       }
1368
1369       _ { fail "free_box invoked with non-box type"; }
1370     };
1371 }
1372
1373 fn make_free_glue(bcx: @block_ctxt, v: ValueRef, t: ty::t) {
1374     // v is a pointer to the actual box component of the type here. The
1375     // ValueRef will have the wrong type here (make_generic_glue is casting
1376     // everything to a pointer to the type that the glue acts on).
1377     let bcx = alt ty::struct(bcx_tcx(bcx), t) {
1378       ty::ty_box(body_mt) {
1379         free_box(bcx, v, t)
1380       }
1381       ty::ty_uniq(content_mt) {
1382         check trans_uniq::type_is_unique_box(bcx, t);
1383         let v = PointerCast(bcx, v, type_of_1(bcx, t));
1384         trans_uniq::make_free_glue(bcx, v, t)
1385       }
1386       ty::ty_vec(_) | ty::ty_str. {
1387         tvec::make_free_glue(bcx, PointerCast(bcx, v, type_of_1(bcx, t)), t)
1388       }
1389       ty::ty_obj(_) {
1390         // Call through the obj's own fields-drop glue first.
1391         // Then free the body.
1392         let ccx = bcx_ccx(bcx);
1393         let llbox_ty = T_opaque_obj_ptr(ccx);
1394         let b = PointerCast(bcx, v, llbox_ty);
1395         let body = GEPi(bcx, b, [0, abi::box_rc_field_body]);
1396         let tydescptr =
1397             GEPi(bcx, body, [0, abi::obj_body_elt_tydesc]);
1398         let tydesc = Load(bcx, tydescptr);
1399         let ti = none;
1400         call_tydesc_glue_full(bcx, body, tydesc,
1401                               abi::tydesc_field_drop_glue, ti);
1402         trans_free_if_not_gc(bcx, b)
1403       }
1404       ty::ty_send_type. {
1405         // sendable type descriptors are basically unique pointers,
1406         // they must be freed.
1407         let ccx = bcx_ccx(bcx);
1408         let v = PointerCast(bcx, v, T_ptr(ccx.tydesc_type));
1409         Call(bcx, ccx.upcalls.free_shared_type_desc, [v]);
1410         bcx
1411       }
1412       ty::ty_native_fn(_, _) | ty::ty_fn(_) {
1413         trans_closure::make_fn_glue(bcx, v, t, free_ty)
1414       }
1415       ty::ty_opaque_closure_ptr(ck) {
1416         trans_closure::make_opaque_cbox_free_glue(bcx, ck, v)
1417       }
1418       _ { bcx }
1419     };
1420     build_return(bcx);
1421 }
1422
1423 fn make_drop_glue(bcx: @block_ctxt, v0: ValueRef, t: ty::t) {
1424     // NB: v0 is an *alias* of type t here, not a direct value.
1425     let ccx = bcx_ccx(bcx);
1426     let bcx =
1427         alt ty::struct(ccx.tcx, t) {
1428           ty::ty_box(_) { decr_refcnt_maybe_free(bcx, Load(bcx, v0), t) }
1429           ty::ty_uniq(_) | ty::ty_vec(_) | ty::ty_str. | ty::ty_send_type. {
1430             free_ty(bcx, Load(bcx, v0), t)
1431           }
1432           ty::ty_obj(_) {
1433             let box_cell =
1434                 GEPi(bcx, v0, [0, abi::obj_field_box]);
1435             decr_refcnt_maybe_free(bcx, Load(bcx, box_cell), t)
1436           }
1437           ty::ty_res(did, inner, tps) {
1438             trans_res_drop(bcx, v0, did, inner, tps)
1439           }
1440           ty::ty_native_fn(_, _) | ty::ty_fn(_) {
1441             trans_closure::make_fn_glue(bcx, v0, t, drop_ty)
1442           }
1443           ty::ty_opaque_closure_ptr(ck) {
1444             trans_closure::make_opaque_cbox_drop_glue(bcx, ck, v0)
1445           }
1446           _ {
1447             if ty::type_needs_drop(ccx.tcx, t) &&
1448                ty::type_is_structural(ccx.tcx, t) {
1449                 iter_structural_ty(bcx, v0, t, drop_ty)
1450             } else { bcx }
1451           }
1452         };
1453     build_return(bcx);
1454 }
1455
1456 fn trans_res_drop(cx: @block_ctxt, rs: ValueRef, did: ast::def_id,
1457                   inner_t: ty::t, tps: [ty::t]) -> @block_ctxt {
1458     let ccx = bcx_ccx(cx);
1459     let inner_t_s = ty::substitute_type_params(ccx.tcx, tps, inner_t);
1460     let tup_ty = ty::mk_tup(ccx.tcx, [ty::mk_int(ccx.tcx), inner_t_s]);
1461     let drop_cx = new_sub_block_ctxt(cx, "drop res");
1462     let next_cx = new_sub_block_ctxt(cx, "next");
1463
1464     // Silly check
1465     check type_is_tup_like(cx, tup_ty);
1466     let drop_flag = GEP_tup_like(cx, tup_ty, rs, [0, 0]);
1467     let cx = drop_flag.bcx;
1468     let null_test = IsNull(cx, Load(cx, drop_flag.val));
1469     CondBr(cx, null_test, next_cx.llbb, drop_cx.llbb);
1470     cx = drop_cx;
1471
1472     check type_is_tup_like(cx, tup_ty);
1473     let val = GEP_tup_like(cx, tup_ty, rs, [0, 1]);
1474     cx = val.bcx;
1475     // Find and call the actual destructor.
1476     let dtor_addr = trans_common::get_res_dtor(ccx, cx.sp, did, inner_t);
1477     let args = [cx.fcx.llretptr, null_env_ptr(cx)];
1478     for tp: ty::t in tps {
1479         let ti: option::t<@tydesc_info> = none;
1480         let td = get_tydesc(cx, tp, false, tps_normal, ti).result;
1481         args += [td.val];
1482         cx = td.bcx;
1483     }
1484     // Kludge to work around the fact that we know the precise type of the
1485     // value here, but the dtor expects a type that still has opaque pointers
1486     // for type variables.
1487     let val_llty = lib::llvm::fn_ty_param_tys
1488         (llvm::LLVMGetElementType
1489          (llvm::LLVMTypeOf(dtor_addr)))[vec::len(args)];
1490     let val_cast = BitCast(cx, val.val, val_llty);
1491     Call(cx, dtor_addr, args + [val_cast]);
1492
1493     cx = drop_ty(cx, val.val, inner_t_s);
1494     // FIXME #1184: Resource flag is larger than necessary
1495     Store(cx, C_int(ccx, 0), drop_flag.val);
1496     Br(cx, next_cx.llbb);
1497     ret next_cx;
1498 }
1499
1500 fn decr_refcnt_maybe_free(cx: @block_ctxt, box_ptr: ValueRef, t: ty::t)
1501     -> @block_ctxt {
1502     let ccx = bcx_ccx(cx);
1503     let rc_adj_cx = new_sub_block_ctxt(cx, "rc--");
1504     let free_cx = new_sub_block_ctxt(cx, "free");
1505     let next_cx = new_sub_block_ctxt(cx, "next");
1506     let llbox_ty = T_opaque_obj_ptr(ccx);
1507     let box_ptr = PointerCast(cx, box_ptr, llbox_ty);
1508     let null_test = IsNull(cx, box_ptr);
1509     CondBr(cx, null_test, next_cx.llbb, rc_adj_cx.llbb);
1510     let rc_ptr =
1511         GEPi(rc_adj_cx, box_ptr, [0, abi::box_rc_field_refcnt]);
1512     let rc = Load(rc_adj_cx, rc_ptr);
1513     rc = Sub(rc_adj_cx, rc, C_int(ccx, 1));
1514     Store(rc_adj_cx, rc, rc_ptr);
1515     let zero_test = ICmp(rc_adj_cx, lib::llvm::LLVMIntEQ, C_int(ccx, 0), rc);
1516     CondBr(rc_adj_cx, zero_test, free_cx.llbb, next_cx.llbb);
1517     let free_cx = free_ty(free_cx, box_ptr, t);
1518     Br(free_cx, next_cx.llbb);
1519     ret next_cx;
1520 }
1521
1522
1523 // Structural comparison: a rather involved form of glue.
1524 fn maybe_name_value(cx: @crate_ctxt, v: ValueRef, s: str) {
1525     if cx.sess.get_opts().save_temps {
1526         let _: () = str::as_buf(s, {|buf| llvm::LLVMSetValueName(v, buf) });
1527     }
1528 }
1529
1530
1531 // Used only for creating scalar comparison glue.
1532 tag scalar_type { nil_type; signed_int; unsigned_int; floating_point; }
1533
1534
1535 fn compare_scalar_types(cx: @block_ctxt, lhs: ValueRef, rhs: ValueRef,
1536                         t: ty::t, op: ast::binop) -> result {
1537     let f = bind compare_scalar_values(cx, lhs, rhs, _, op);
1538
1539     alt ty::struct(bcx_tcx(cx), t) {
1540       ty::ty_nil. { ret rslt(cx, f(nil_type)); }
1541       ty::ty_bool. | ty::ty_ptr(_) { ret rslt(cx, f(unsigned_int)); }
1542       ty::ty_int(_) { ret rslt(cx, f(signed_int)); }
1543       ty::ty_uint(_) { ret rslt(cx, f(unsigned_int)); }
1544       ty::ty_float(_) { ret rslt(cx, f(floating_point)); }
1545       ty::ty_type. {
1546         ret rslt(trans_fail(cx, none,
1547                             "attempt to compare values of type type"),
1548                  C_nil());
1549       }
1550       ty::ty_native(_) {
1551         let cx = trans_fail(cx, none::<span>,
1552                             "attempt to compare values of type native");
1553         ret rslt(cx, C_nil());
1554       }
1555       _ {
1556         // Should never get here, because t is scalar.
1557         bcx_ccx(cx).sess.bug("non-scalar type passed to \
1558                                  compare_scalar_types");
1559       }
1560     }
1561 }
1562
1563
1564 // A helper function to do the actual comparison of scalar values.
1565 fn compare_scalar_values(cx: @block_ctxt, lhs: ValueRef, rhs: ValueRef,
1566                          nt: scalar_type, op: ast::binop) -> ValueRef {
1567     alt nt {
1568       nil_type. {
1569         // We don't need to do actual comparisons for nil.
1570         // () == () holds but () < () does not.
1571         alt op {
1572           ast::eq. | ast::le. | ast::ge. { ret C_bool(true); }
1573           ast::ne. | ast::lt. | ast::gt. { ret C_bool(false); }
1574         }
1575       }
1576       floating_point. {
1577         let cmp = alt op {
1578           ast::eq. { lib::llvm::LLVMRealOEQ }
1579           ast::ne. { lib::llvm::LLVMRealUNE }
1580           ast::lt. { lib::llvm::LLVMRealOLT }
1581           ast::le. { lib::llvm::LLVMRealOLE }
1582           ast::gt. { lib::llvm::LLVMRealOGT }
1583           ast::ge. { lib::llvm::LLVMRealOGE }
1584         };
1585         ret FCmp(cx, cmp, lhs, rhs);
1586       }
1587       signed_int. {
1588         let cmp = alt op {
1589           ast::eq. { lib::llvm::LLVMIntEQ }
1590           ast::ne. { lib::llvm::LLVMIntNE }
1591           ast::lt. { lib::llvm::LLVMIntSLT }
1592           ast::le. { lib::llvm::LLVMIntSLE }
1593           ast::gt. { lib::llvm::LLVMIntSGT }
1594           ast::ge. { lib::llvm::LLVMIntSGE }
1595         };
1596         ret ICmp(cx, cmp, lhs, rhs);
1597       }
1598       unsigned_int. {
1599         let cmp = alt op {
1600           ast::eq. { lib::llvm::LLVMIntEQ }
1601           ast::ne. { lib::llvm::LLVMIntNE }
1602           ast::lt. { lib::llvm::LLVMIntULT }
1603           ast::le. { lib::llvm::LLVMIntULE }
1604           ast::gt. { lib::llvm::LLVMIntUGT }
1605           ast::ge. { lib::llvm::LLVMIntUGE }
1606         };
1607         ret ICmp(cx, cmp, lhs, rhs);
1608       }
1609     }
1610 }
1611
1612 type val_pair_fn = fn(@block_ctxt, ValueRef, ValueRef) -> @block_ctxt;
1613 type val_and_ty_fn = fn(@block_ctxt, ValueRef, ty::t) -> @block_ctxt;
1614
1615 fn load_inbounds(cx: @block_ctxt, p: ValueRef, idxs: [int]) -> ValueRef {
1616     ret Load(cx, GEPi(cx, p, idxs));
1617 }
1618
1619 fn store_inbounds(cx: @block_ctxt, v: ValueRef, p: ValueRef,
1620                   idxs: [int]) {
1621     Store(cx, v, GEPi(cx, p, idxs));
1622 }
1623
1624 // Iterates through the elements of a structural type.
1625 fn iter_structural_ty(cx: @block_ctxt, av: ValueRef, t: ty::t,
1626                       f: val_and_ty_fn) -> @block_ctxt {
1627     fn iter_boxpp(cx: @block_ctxt, box_cell: ValueRef, f: val_and_ty_fn) ->
1628        @block_ctxt {
1629         let box_ptr = Load(cx, box_cell);
1630         let tnil = ty::mk_nil(bcx_tcx(cx));
1631         let tbox = ty::mk_imm_box(bcx_tcx(cx), tnil);
1632         let inner_cx = new_sub_block_ctxt(cx, "iter box");
1633         let next_cx = new_sub_block_ctxt(cx, "next");
1634         let null_test = IsNull(cx, box_ptr);
1635         CondBr(cx, null_test, next_cx.llbb, inner_cx.llbb);
1636         let inner_cx = f(inner_cx, box_cell, tbox);
1637         Br(inner_cx, next_cx.llbb);
1638         ret next_cx;
1639     }
1640
1641     fn iter_variant(cx: @block_ctxt, a_tup: ValueRef,
1642                     variant: ty::variant_info, tps: [ty::t], tid: ast::def_id,
1643                     f: val_and_ty_fn) -> @block_ctxt {
1644         if vec::len::<ty::t>(variant.args) == 0u { ret cx; }
1645         let fn_ty = variant.ctor_ty;
1646         let ccx = bcx_ccx(cx);
1647         let cx = cx;
1648         alt ty::struct(ccx.tcx, fn_ty) {
1649           ty::ty_fn({inputs: args, _}) {
1650             let j = 0u;
1651             let v_id = variant.id;
1652             for a: ty::arg in args {
1653                 check (valid_variant_index(j, cx, tid, v_id));
1654                 let rslt = GEP_tag(cx, a_tup, tid, v_id, tps, j);
1655                 let llfldp_a = rslt.val;
1656                 cx = rslt.bcx;
1657                 let ty_subst = ty::substitute_type_params(ccx.tcx, tps, a.ty);
1658                 cx = f(cx, llfldp_a, ty_subst);
1659                 j += 1u;
1660             }
1661           }
1662         }
1663         ret cx;
1664     }
1665
1666     /*
1667     Typestate constraint that shows the unimpl case doesn't happen?
1668     */
1669     let cx = cx;
1670     alt ty::struct(bcx_tcx(cx), t) {
1671       ty::ty_rec(fields) {
1672         let i: int = 0;
1673         for fld: ty::field in fields {
1674             // Silly check
1675             check type_is_tup_like(cx, t);
1676             let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, t, av, [0, i]);
1677             cx = f(bcx, llfld_a, fld.mt.ty);
1678             i += 1;
1679         }
1680       }
1681       ty::ty_tup(args) {
1682         let i = 0;
1683         for arg in args {
1684             // Silly check
1685             check type_is_tup_like(cx, t);
1686             let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, t, av, [0, i]);
1687             cx = f(bcx, llfld_a, arg);
1688             i += 1;
1689         }
1690       }
1691       ty::ty_res(_, inner, tps) {
1692         let tcx = bcx_tcx(cx);
1693         let inner1 = ty::substitute_type_params(tcx, tps, inner);
1694         let inner_t_s = ty::substitute_type_params(tcx, tps, inner);
1695         let tup_t = ty::mk_tup(tcx, [ty::mk_int(tcx), inner_t_s]);
1696         // Silly check
1697         check type_is_tup_like(cx, tup_t);
1698         let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, tup_t, av, [0, 1]);
1699         ret f(bcx, llfld_a, inner1);
1700       }
1701       ty::ty_tag(tid, tps) {
1702         let variants = ty::tag_variants(bcx_tcx(cx), tid);
1703         let n_variants = vec::len(*variants);
1704
1705         // Cast the tags to types we can GEP into.
1706         if n_variants == 1u {
1707             ret iter_variant(cx, av, variants[0], tps, tid, f);
1708         }
1709
1710         let ccx = bcx_ccx(cx);
1711         let lltagty = T_opaque_tag_ptr(ccx);
1712         let av_tag = PointerCast(cx, av, lltagty);
1713         let lldiscrim_a_ptr = GEPi(cx, av_tag, [0, 0]);
1714         let llunion_a_ptr = GEPi(cx, av_tag, [0, 1]);
1715         let lldiscrim_a = Load(cx, lldiscrim_a_ptr);
1716
1717         // NB: we must hit the discriminant first so that structural
1718         // comparison know not to proceed when the discriminants differ.
1719         cx = f(cx, lldiscrim_a_ptr, ty::mk_int(bcx_tcx(cx)));
1720         let unr_cx = new_sub_block_ctxt(cx, "tag-iter-unr");
1721         Unreachable(unr_cx);
1722         let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb, n_variants);
1723         let next_cx = new_sub_block_ctxt(cx, "tag-iter-next");
1724         let i = 0u;
1725         for variant: ty::variant_info in *variants {
1726             let variant_cx =
1727                 new_sub_block_ctxt(cx,
1728                                    "tag-iter-variant-" +
1729                                        uint::to_str(i, 10u));
1730             AddCase(llswitch, C_int(ccx, i as int), variant_cx.llbb);
1731             variant_cx =
1732                 iter_variant(variant_cx, llunion_a_ptr, variant, tps, tid, f);
1733             Br(variant_cx, next_cx.llbb);
1734             i += 1u;
1735         }
1736         ret next_cx;
1737       }
1738       ty::ty_obj(_) {
1739         let box_cell_a = GEPi(cx, av, [0, abi::obj_field_box]);
1740         ret iter_boxpp(cx, box_cell_a, f);
1741       }
1742       _ { bcx_ccx(cx).sess.unimpl("type in iter_structural_ty"); }
1743     }
1744     ret cx;
1745 }
1746
1747 fn lazily_emit_all_tydesc_glue(cx: @block_ctxt,
1748                                static_ti: option::t<@tydesc_info>) {
1749     lazily_emit_tydesc_glue(cx, abi::tydesc_field_take_glue, static_ti);
1750     lazily_emit_tydesc_glue(cx, abi::tydesc_field_drop_glue, static_ti);
1751     lazily_emit_tydesc_glue(cx, abi::tydesc_field_free_glue, static_ti);
1752     lazily_emit_tydesc_glue(cx, abi::tydesc_field_cmp_glue, static_ti);
1753 }
1754
1755 fn lazily_emit_all_generic_info_tydesc_glues(cx: @block_ctxt,
1756                                              gi: generic_info) {
1757     for ti: option::t<@tydesc_info> in gi.static_tis {
1758         lazily_emit_all_tydesc_glue(cx, ti);
1759     }
1760 }
1761
1762 fn lazily_emit_tydesc_glue(cx: @block_ctxt, field: int,
1763                            static_ti: option::t<@tydesc_info>) {
1764     alt static_ti {
1765       none. { }
1766       some(ti) {
1767         if field == abi::tydesc_field_take_glue {
1768             alt ti.take_glue {
1769               some(_) { }
1770               none. {
1771                 #debug("+++ lazily_emit_tydesc_glue TAKE %s",
1772                        ty_to_str(bcx_tcx(cx), ti.ty));
1773                 let lcx = cx.fcx.lcx;
1774                 let glue_fn =
1775                     declare_generic_glue(lcx, ti.ty, T_glue_fn(lcx.ccx),
1776                                          "take");
1777                 ti.take_glue = some::<ValueRef>(glue_fn);
1778                 make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
1779                                   make_take_glue,
1780                                   ti.ty_params, "take");
1781                 #debug("--- lazily_emit_tydesc_glue TAKE %s",
1782                        ty_to_str(bcx_tcx(cx), ti.ty));
1783               }
1784             }
1785         } else if field == abi::tydesc_field_drop_glue {
1786             alt ti.drop_glue {
1787               some(_) { }
1788               none. {
1789                 #debug("+++ lazily_emit_tydesc_glue DROP %s",
1790                        ty_to_str(bcx_tcx(cx), ti.ty));
1791                 let lcx = cx.fcx.lcx;
1792                 let glue_fn =
1793                     declare_generic_glue(lcx, ti.ty, T_glue_fn(lcx.ccx),
1794                                          "drop");
1795                 ti.drop_glue = some::<ValueRef>(glue_fn);
1796                 make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
1797                                   make_drop_glue,
1798                                   ti.ty_params, "drop");
1799                 #debug("--- lazily_emit_tydesc_glue DROP %s",
1800                        ty_to_str(bcx_tcx(cx), ti.ty));
1801               }
1802             }
1803         } else if field == abi::tydesc_field_free_glue {
1804             alt ti.free_glue {
1805               some(_) { }
1806               none. {
1807                 #debug("+++ lazily_emit_tydesc_glue FREE %s",
1808                        ty_to_str(bcx_tcx(cx), ti.ty));
1809                 let lcx = cx.fcx.lcx;
1810                 let glue_fn =
1811                     declare_generic_glue(lcx, ti.ty, T_glue_fn(lcx.ccx),
1812                                          "free");
1813                 ti.free_glue = some::<ValueRef>(glue_fn);
1814                 make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
1815                                   make_free_glue,
1816                                   ti.ty_params, "free");
1817                 #debug("--- lazily_emit_tydesc_glue FREE %s",
1818                        ty_to_str(bcx_tcx(cx), ti.ty));
1819               }
1820             }
1821         } else if field == abi::tydesc_field_cmp_glue {
1822             alt ti.cmp_glue {
1823               some(_) { }
1824               none. {
1825                 #debug("+++ lazily_emit_tydesc_glue CMP %s",
1826                        ty_to_str(bcx_tcx(cx), ti.ty));
1827                 ti.cmp_glue = some(bcx_ccx(cx).upcalls.cmp_type);
1828                 #debug("--- lazily_emit_tydesc_glue CMP %s",
1829                        ty_to_str(bcx_tcx(cx), ti.ty));
1830               }
1831             }
1832         }
1833       }
1834     }
1835 }
1836
1837 fn call_tydesc_glue_full(cx: @block_ctxt, v: ValueRef, tydesc: ValueRef,
1838                          field: int, static_ti: option::t<@tydesc_info>) {
1839     lazily_emit_tydesc_glue(cx, field, static_ti);
1840
1841     let static_glue_fn = none;
1842     alt static_ti {
1843       none. {/* no-op */ }
1844       some(sti) {
1845         if field == abi::tydesc_field_take_glue {
1846             static_glue_fn = sti.take_glue;
1847         } else if field == abi::tydesc_field_drop_glue {
1848             static_glue_fn = sti.drop_glue;
1849         } else if field == abi::tydesc_field_free_glue {
1850             static_glue_fn = sti.free_glue;
1851         }
1852       }
1853     }
1854
1855     let llrawptr = PointerCast(cx, v, T_ptr(T_i8()));
1856     let lltydescs =
1857         GEPi(cx, tydesc, [0, abi::tydesc_field_first_param]);
1858     lltydescs = Load(cx, lltydescs);
1859
1860     let llfn;
1861     alt static_glue_fn {
1862       none. {
1863         let llfnptr = GEPi(cx, tydesc, [0, field]);
1864         llfn = Load(cx, llfnptr);
1865       }
1866       some(sgf) { llfn = sgf; }
1867     }
1868
1869     Call(cx, llfn, [C_null(T_ptr(T_nil())), C_null(T_ptr(T_nil())),
1870                     lltydescs, llrawptr]);
1871 }
1872
1873 fn call_tydesc_glue(cx: @block_ctxt, v: ValueRef, t: ty::t, field: int) ->
1874    @block_ctxt {
1875     let ti: option::t<@tydesc_info> = none::<@tydesc_info>;
1876     let {bcx: bcx, val: td} = get_tydesc(cx, t, false, tps_normal, ti).result;
1877     call_tydesc_glue_full(bcx, v, td, field, ti);
1878     ret bcx;
1879 }
1880
1881 fn call_cmp_glue(cx: @block_ctxt, lhs: ValueRef, rhs: ValueRef, t: ty::t,
1882                  llop: ValueRef) -> result {
1883     // We can't use call_tydesc_glue_full() and friends here because compare
1884     // glue has a special signature.
1885
1886     let bcx = cx;
1887
1888     let r = spill_if_immediate(bcx, lhs, t);
1889     let lllhs = r.val;
1890     bcx = r.bcx;
1891     r = spill_if_immediate(bcx, rhs, t);
1892     let llrhs = r.val;
1893     bcx = r.bcx;
1894
1895     let llrawlhsptr = BitCast(bcx, lllhs, T_ptr(T_i8()));
1896     let llrawrhsptr = BitCast(bcx, llrhs, T_ptr(T_i8()));
1897     let ti = none::<@tydesc_info>;
1898     r = get_tydesc(bcx, t, false, tps_normal, ti).result;
1899     let lltydesc = r.val;
1900     bcx = r.bcx;
1901     lazily_emit_tydesc_glue(bcx, abi::tydesc_field_cmp_glue, ti);
1902     let lltydescs =
1903         GEPi(bcx, lltydesc, [0, abi::tydesc_field_first_param]);
1904     lltydescs = Load(bcx, lltydescs);
1905
1906     let llfn;
1907     alt ti {
1908       none. {
1909         let llfnptr =
1910             GEPi(bcx, lltydesc, [0, abi::tydesc_field_cmp_glue]);
1911         llfn = Load(bcx, llfnptr);
1912       }
1913       some(sti) { llfn = option::get(sti.cmp_glue); }
1914     }
1915
1916     let llcmpresultptr = alloca(bcx, T_i1());
1917     Call(bcx, llfn, [llcmpresultptr, lltydesc, lltydescs,
1918                      llrawlhsptr, llrawrhsptr, llop]);
1919     ret rslt(bcx, Load(bcx, llcmpresultptr));
1920 }
1921
1922 fn take_ty(cx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1923     if ty::type_needs_drop(bcx_tcx(cx), t) {
1924         ret call_tydesc_glue(cx, v, t, abi::tydesc_field_take_glue);
1925     }
1926     ret cx;
1927 }
1928
1929 fn drop_ty(cx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1930     if ty::type_needs_drop(bcx_tcx(cx), t) {
1931         ret call_tydesc_glue(cx, v, t, abi::tydesc_field_drop_glue);
1932     }
1933     ret cx;
1934 }
1935
1936 fn drop_ty_immediate(bcx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1937     alt ty::struct(bcx_tcx(bcx), t) {
1938       ty::ty_uniq(_) | ty::ty_vec(_) | ty::ty_str. {
1939         ret free_ty(bcx, v, t);
1940       }
1941       ty::ty_box(_) { ret decr_refcnt_maybe_free(bcx, v, t); }
1942     }
1943 }
1944
1945 fn take_ty_immediate(bcx: @block_ctxt, v: ValueRef, t: ty::t) -> result {
1946     alt ty::struct(bcx_tcx(bcx), t) {
1947       ty::ty_box(_) { ret rslt(incr_refcnt_of_boxed(bcx, v), v); }
1948       ty::ty_uniq(_) {
1949         check trans_uniq::type_is_unique_box(bcx, t);
1950         ret trans_uniq::duplicate(bcx, v, t);
1951       }
1952       ty::ty_str. | ty::ty_vec(_) { ret tvec::duplicate(bcx, v, t); }
1953       _ { ret rslt(bcx, v); }
1954     }
1955 }
1956
1957 fn free_ty(cx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1958     if ty::type_needs_drop(bcx_tcx(cx), t) {
1959         ret call_tydesc_glue(cx, v, t, abi::tydesc_field_free_glue);
1960     }
1961     ret cx;
1962 }
1963
1964 fn call_memmove(cx: @block_ctxt, dst: ValueRef, src: ValueRef,
1965                 n_bytes: ValueRef) -> result {
1966     // TODO: Provide LLVM with better alignment information when the alignment
1967     // is statically known (it must be nothing more than a constant int, or
1968     // LLVM complains -- not even a constant element of a tydesc works).
1969
1970     let ccx = bcx_ccx(cx);
1971     let key = alt ccx.sess.get_targ_cfg().arch {
1972       session::arch_x86. | session::arch_arm. { "llvm.memmove.p0i8.p0i8.i32" }
1973       session::arch_x86_64. { "llvm.memmove.p0i8.p0i8.i64" }
1974     };
1975     let i = ccx.intrinsics;
1976     assert (i.contains_key(key));
1977     let memmove = i.get(key);
1978     let src_ptr = PointerCast(cx, src, T_ptr(T_i8()));
1979     let dst_ptr = PointerCast(cx, dst, T_ptr(T_i8()));
1980     // FIXME #1184: Resource flag is larger than necessary
1981     let size = IntCast(cx, n_bytes, ccx.int_type);
1982     let align = C_i32(1i32);
1983     let volatile = C_bool(false);
1984     let ret_val = Call(cx, memmove, [dst_ptr, src_ptr, size,
1985                                      align, volatile]);
1986     ret rslt(cx, ret_val);
1987 }
1988
1989 fn call_bzero(cx: @block_ctxt, dst: ValueRef, n_bytes: ValueRef,
1990               align_bytes: ValueRef) -> result {
1991     // FIXME: switch to the 64-bit variant when on such a platform.
1992     let ccx = bcx_ccx(cx);
1993     let i = ccx.intrinsics;
1994     assert (i.contains_key("llvm.memset.p0i8.i32"));
1995     let memset = i.get("llvm.memset.p0i8.i32");
1996     let dst_ptr = PointerCast(cx, dst, T_ptr(T_i8()));
1997     let size = IntCast(cx, n_bytes, T_i32());
1998     let align =
1999         if lib::llvm::llvm::LLVMIsConstant(align_bytes) == True {
2000             IntCast(cx, align_bytes, T_i32())
2001         } else { IntCast(cx, C_int(ccx, 0), T_i32()) };
2002     let volatile = C_bool(false);
2003     ret rslt(cx,
2004              Call(cx, memset, [dst_ptr, C_u8(0u), size, align, volatile]));
2005 }
2006
2007 fn memmove_ty(bcx: @block_ctxt, dst: ValueRef, src: ValueRef, t: ty::t) ->
2008     @block_ctxt {
2009     let ccx = bcx_ccx(bcx);
2010     if check type_has_static_size(ccx, t) {
2011         if ty::type_is_structural(bcx_tcx(bcx), t) {
2012             let sp = bcx.sp;
2013             let llsz = llsize_of(ccx, type_of(ccx, sp, t));
2014             ret call_memmove(bcx, dst, src, llsz).bcx;
2015         }
2016         Store(bcx, Load(bcx, src), dst);
2017         ret bcx;
2018     }
2019
2020     let {bcx, val: llsz} = size_of(bcx, t);
2021     ret call_memmove(bcx, dst, src, llsz).bcx;
2022 }
2023
2024 tag copy_action { INIT; DROP_EXISTING; }
2025
2026 // These are the types that are passed by pointer.
2027 fn type_is_structural_or_param(tcx: ty::ctxt, t: ty::t) -> bool {
2028     if ty::type_is_structural(tcx, t) { ret true; }
2029     alt ty::struct(tcx, t) {
2030       ty::ty_param(_, _) { ret true; }
2031       _ { ret false; }
2032     }
2033 }
2034
2035 fn copy_val(cx: @block_ctxt, action: copy_action, dst: ValueRef,
2036             src: ValueRef, t: ty::t) -> @block_ctxt {
2037     if action == DROP_EXISTING &&
2038         (type_is_structural_or_param(bcx_tcx(cx), t) ||
2039          ty::type_is_unique(bcx_tcx(cx), t)) {
2040         let do_copy_cx = new_sub_block_ctxt(cx, "do_copy");
2041         let next_cx = new_sub_block_ctxt(cx, "next");
2042         let dstcmp = load_if_immediate(cx, dst, t);
2043         let self_assigning =
2044             ICmp(cx, lib::llvm::LLVMIntNE,
2045                  PointerCast(cx, dstcmp, val_ty(src)), src);
2046         CondBr(cx, self_assigning, do_copy_cx.llbb, next_cx.llbb);
2047         do_copy_cx = copy_val_no_check(do_copy_cx, action, dst, src, t);
2048         Br(do_copy_cx, next_cx.llbb);
2049         ret next_cx;
2050     }
2051     ret copy_val_no_check(cx, action, dst, src, t);
2052 }
2053
2054 fn copy_val_no_check(bcx: @block_ctxt, action: copy_action, dst: ValueRef,
2055                      src: ValueRef, t: ty::t) -> @block_ctxt {
2056     let ccx = bcx_ccx(bcx), bcx = bcx;
2057     if ty::type_is_scalar(ccx.tcx, t) || ty::type_is_native(ccx.tcx, t) {
2058         Store(bcx, src, dst);
2059         ret bcx;
2060     }
2061     if ty::type_is_nil(ccx.tcx, t) || ty::type_is_bot(ccx.tcx, t) { ret bcx; }
2062     if ty::type_is_boxed(ccx.tcx, t) || ty::type_is_vec(ccx.tcx, t) ||
2063        ty::type_is_unique_box(ccx.tcx, t) {
2064         if action == DROP_EXISTING { bcx = drop_ty(bcx, dst, t); }
2065         Store(bcx, src, dst);
2066         ret take_ty(bcx, dst, t);
2067     }
2068     if type_is_structural_or_param(ccx.tcx, t) {
2069         if action == DROP_EXISTING { bcx = drop_ty(bcx, dst, t); }
2070         bcx = memmove_ty(bcx, dst, src, t);
2071         ret take_ty(bcx, dst, t);
2072     }
2073     ccx.sess.bug("unexpected type in trans::copy_val_no_check: " +
2074                      ty_to_str(ccx.tcx, t));
2075 }
2076
2077
2078 // This works like copy_val, except that it deinitializes the source.
2079 // Since it needs to zero out the source, src also needs to be an lval.
2080 // FIXME: We always zero out the source. Ideally we would detect the
2081 // case where a variable is always deinitialized by block exit and thus
2082 // doesn't need to be dropped.
2083 fn move_val(cx: @block_ctxt, action: copy_action, dst: ValueRef,
2084             src: lval_result, t: ty::t) -> @block_ctxt {
2085     let src_val = src.val;
2086     let tcx = bcx_tcx(cx), cx = cx;
2087     if ty::type_is_scalar(tcx, t) || ty::type_is_native(tcx, t) {
2088         if src.kind == owned { src_val = Load(cx, src_val); }
2089         Store(cx, src_val, dst);
2090         ret cx;
2091     } else if ty::type_is_nil(tcx, t) || ty::type_is_bot(tcx, t) {
2092         ret cx;
2093     } else if ty::type_is_boxed(tcx, t) || ty::type_is_unique(tcx, t) {
2094         if src.kind == owned { src_val = Load(cx, src_val); }
2095         if action == DROP_EXISTING { cx = drop_ty(cx, dst, t); }
2096         Store(cx, src_val, dst);
2097         if src.kind == owned { ret zero_alloca(cx, src.val, t); }
2098         // If we're here, it must be a temporary.
2099         revoke_clean(cx, src_val);
2100         ret cx;
2101     } else if type_is_structural_or_param(tcx, t) {
2102         if action == DROP_EXISTING { cx = drop_ty(cx, dst, t); }
2103         cx = memmove_ty(cx, dst, src_val, t);
2104         if src.kind == owned { ret zero_alloca(cx, src_val, t); }
2105         // If we're here, it must be a temporary.
2106         revoke_clean(cx, src_val);
2107         ret cx;
2108     }
2109     /* FIXME: suggests a type constraint */
2110     bcx_ccx(cx).sess.bug("unexpected type in trans::move_val: " +
2111                              ty_to_str(tcx, t));
2112 }
2113
2114 fn store_temp_expr(cx: @block_ctxt, action: copy_action, dst: ValueRef,
2115                    src: lval_result, t: ty::t, last_use: bool)
2116     -> @block_ctxt {
2117     // Lvals in memory are not temporaries. Copy them.
2118     if src.kind != temporary && !last_use {
2119         let v = src.kind == owned ? load_if_immediate(cx, src.val, t)
2120                                   : src.val;
2121         ret copy_val(cx, action, dst, v, t);
2122     }
2123     ret move_val(cx, action, dst, src, t);
2124 }
2125
2126 fn trans_crate_lit(cx: @crate_ctxt, lit: ast::lit) -> ValueRef {
2127     alt lit.node {
2128       ast::lit_int(i, t) { C_integral(T_int_ty(cx, t), i as u64, True) }
2129       ast::lit_uint(u, t) { C_integral(T_uint_ty(cx, t), u, False) }
2130       ast::lit_float(fs, t) { C_floating(fs, T_float_ty(cx, t)) }
2131       ast::lit_bool(b) { C_bool(b) }
2132       ast::lit_nil. { C_nil() }
2133       ast::lit_str(s) {
2134         cx.sess.span_unimpl(lit.span, "unique string in this context");
2135       }
2136     }
2137 }
2138
2139 fn trans_lit(cx: @block_ctxt, lit: ast::lit, dest: dest) -> @block_ctxt {
2140     if dest == ignore { ret cx; }
2141     alt lit.node {
2142       ast::lit_str(s) { ret tvec::trans_str(cx, s, dest); }
2143       _ {
2144         ret store_in_dest(cx, trans_crate_lit(bcx_ccx(cx), lit), dest);
2145       }
2146     }
2147 }
2148
2149
2150 // Converts an annotation to a type
2151 fn node_id_type(cx: @crate_ctxt, id: ast::node_id) -> ty::t {
2152     ret ty::node_id_to_monotype(cx.tcx, id);
2153 }
2154
2155 fn node_type(cx: @crate_ctxt, sp: span, id: ast::node_id) -> TypeRef {
2156     let ty = node_id_type(cx, id);
2157     // How to make this a precondition?
2158     // FIXME (again, would require a predicate that implies
2159     // another predicate)
2160     check (type_has_static_size(cx, ty));
2161     type_of(cx, sp, ty)
2162 }
2163
2164 fn trans_unary(bcx: @block_ctxt, op: ast::unop, e: @ast::expr,
2165                id: ast::node_id, dest: dest) -> @block_ctxt {
2166     if dest == ignore { ret trans_expr(bcx, e, ignore); }
2167     let e_ty = ty::expr_ty(bcx_tcx(bcx), e);
2168     alt op {
2169       ast::not. {
2170         let {bcx, val} = trans_temp_expr(bcx, e);
2171         ret store_in_dest(bcx, Not(bcx, val), dest);
2172       }
2173       ast::neg. {
2174         let {bcx, val} = trans_temp_expr(bcx, e);
2175         let neg = if ty::type_is_fp(bcx_tcx(bcx), e_ty) {
2176             FNeg(bcx, val)
2177         } else { Neg(bcx, val) };
2178         ret store_in_dest(bcx, neg, dest);
2179       }
2180       ast::box(_) {
2181         let {bcx, box, body} = trans_malloc_boxed(bcx, e_ty);
2182         add_clean_free(bcx, box, false);
2183         // Cast the body type to the type of the value. This is needed to
2184         // make tags work, since tags have a different LLVM type depending
2185         // on whether they're boxed or not.
2186         let ccx = bcx_ccx(bcx);
2187         if check type_has_static_size(ccx, e_ty) {
2188             let e_sp = e.span;
2189             let llety = T_ptr(type_of(ccx, e_sp, e_ty));
2190             body = PointerCast(bcx, body, llety);
2191         }
2192         bcx = trans_expr_save_in(bcx, e, body);
2193         revoke_clean(bcx, box);
2194         ret store_in_dest(bcx, box, dest);
2195       }
2196       ast::uniq(_) {
2197         ret trans_uniq::trans_uniq(bcx, e, id, dest);
2198       }
2199       ast::deref. {
2200         bcx_ccx(bcx).sess.bug("deref expressions should have been \
2201                                translated using trans_lval(), not \
2202                                trans_unary()");
2203       }
2204     }
2205 }
2206
2207 fn trans_compare(cx: @block_ctxt, op: ast::binop, lhs: ValueRef,
2208                  _lhs_t: ty::t, rhs: ValueRef, rhs_t: ty::t) -> result {
2209     if ty::type_is_scalar(bcx_tcx(cx), rhs_t) {
2210       let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, op);
2211       ret rslt(rs.bcx, rs.val);
2212     }
2213
2214     // Determine the operation we need.
2215     let llop;
2216     alt op {
2217       ast::eq. | ast::ne. { llop = C_u8(abi::cmp_glue_op_eq); }
2218       ast::lt. | ast::ge. { llop = C_u8(abi::cmp_glue_op_lt); }
2219       ast::le. | ast::gt. { llop = C_u8(abi::cmp_glue_op_le); }
2220     }
2221
2222     let rs = call_cmp_glue(cx, lhs, rhs, rhs_t, llop);
2223
2224     // Invert the result if necessary.
2225     alt op {
2226       ast::eq. | ast::lt. | ast::le. { ret rslt(rs.bcx, rs.val); }
2227       ast::ne. | ast::ge. | ast::gt. {
2228         ret rslt(rs.bcx, Not(rs.bcx, rs.val));
2229       }
2230     }
2231 }
2232
2233 // Important to get types for both lhs and rhs, because one might be _|_
2234 // and the other not.
2235 fn trans_eager_binop(cx: @block_ctxt, op: ast::binop, lhs: ValueRef,
2236                      lhs_t: ty::t, rhs: ValueRef, rhs_t: ty::t, dest: dest)
2237     -> @block_ctxt {
2238     if dest == ignore { ret cx; }
2239     let intype = lhs_t;
2240     if ty::type_is_bot(bcx_tcx(cx), intype) { intype = rhs_t; }
2241     let is_float = ty::type_is_fp(bcx_tcx(cx), intype);
2242
2243     if op == ast::add && ty::type_is_sequence(bcx_tcx(cx), intype) {
2244         ret tvec::trans_add(cx, intype, lhs, rhs, dest);
2245     }
2246     let cx = cx, val = alt op {
2247       ast::add. {
2248         if is_float { FAdd(cx, lhs, rhs) }
2249         else { Add(cx, lhs, rhs) }
2250       }
2251       ast::sub. {
2252         if is_float { FSub(cx, lhs, rhs) }
2253         else { Sub(cx, lhs, rhs) }
2254       }
2255       ast::mul. {
2256         if is_float { FMul(cx, lhs, rhs) }
2257         else { Mul(cx, lhs, rhs) }
2258       }
2259       ast::div. {
2260         if is_float { FDiv(cx, lhs, rhs) }
2261         else if ty::type_is_signed(bcx_tcx(cx), intype) {
2262             SDiv(cx, lhs, rhs)
2263         } else { UDiv(cx, lhs, rhs) }
2264       }
2265       ast::rem. {
2266         if is_float { FRem(cx, lhs, rhs) }
2267         else if ty::type_is_signed(bcx_tcx(cx), intype) {
2268             SRem(cx, lhs, rhs)
2269         } else { URem(cx, lhs, rhs) }
2270       }
2271       ast::bitor. { Or(cx, lhs, rhs) }
2272       ast::bitand. { And(cx, lhs, rhs) }
2273       ast::bitxor. { Xor(cx, lhs, rhs) }
2274       ast::lsl. { Shl(cx, lhs, rhs) }
2275       ast::lsr. { LShr(cx, lhs, rhs) }
2276       ast::asr. { AShr(cx, lhs, rhs) }
2277       _ {
2278         let cmpr = trans_compare(cx, op, lhs, lhs_t, rhs, rhs_t);
2279         cx = cmpr.bcx;
2280         cmpr.val
2281       }
2282     };
2283     ret store_in_dest(cx, val, dest);
2284 }
2285
2286 fn trans_assign_op(bcx: @block_ctxt, op: ast::binop, dst: @ast::expr,
2287                    src: @ast::expr) -> @block_ctxt {
2288     let tcx = bcx_tcx(bcx);
2289     let t = ty::expr_ty(tcx, src);
2290     let lhs_res = trans_lval(bcx, dst);
2291     assert (lhs_res.kind == owned);
2292     // Special case for `+= [x]`
2293     alt ty::struct(tcx, t) {
2294       ty::ty_vec(_) {
2295         alt src.node {
2296           ast::expr_vec(args, _) {
2297             ret tvec::trans_append_literal(lhs_res.bcx,
2298                                            lhs_res.val, t, args);
2299           }
2300           _ { }
2301         }
2302       }
2303       _ { }
2304     }
2305     let {bcx, val: rhs_val} = trans_temp_expr(lhs_res.bcx, src);
2306     if ty::type_is_sequence(tcx, t) {
2307         alt op {
2308           ast::add. {
2309             ret tvec::trans_append(bcx, t, lhs_res.val, rhs_val);
2310           }
2311           _ { }
2312         }
2313     }
2314     ret trans_eager_binop(bcx, op, Load(bcx, lhs_res.val), t, rhs_val, t,
2315                           save_in(lhs_res.val));
2316 }
2317
2318 fn autoderef(cx: @block_ctxt, v: ValueRef, t: ty::t) -> result_t {
2319     let v1: ValueRef = v;
2320     let t1: ty::t = t;
2321     let ccx = bcx_ccx(cx);
2322     let sp = cx.sp;
2323     while true {
2324         alt ty::struct(ccx.tcx, t1) {
2325           ty::ty_box(mt) {
2326             let body = GEPi(cx, v1, [0, abi::box_rc_field_body]);
2327             t1 = mt.ty;
2328
2329             // Since we're changing levels of box indirection, we may have
2330             // to cast this pointer, since statically-sized tag types have
2331             // different types depending on whether they're behind a box
2332             // or not.
2333             if check type_has_static_size(ccx, t1) {
2334                 let llty = type_of(ccx, sp, t1);
2335                 v1 = PointerCast(cx, body, T_ptr(llty));
2336             } else { v1 = body; }
2337           }
2338           ty::ty_uniq(_) {
2339             check trans_uniq::type_is_unique_box(cx, t1);
2340             let derefed = trans_uniq::autoderef(cx, v1, t1);
2341             t1 = derefed.t;
2342             v1 = derefed.v;
2343           }
2344           ty::ty_res(did, inner, tps) {
2345             t1 = ty::substitute_type_params(ccx.tcx, tps, inner);
2346             v1 = GEPi(cx, v1, [0, 1]);
2347           }
2348           ty::ty_tag(did, tps) {
2349             let variants = ty::tag_variants(ccx.tcx, did);
2350             if vec::len(*variants) != 1u ||
2351                    vec::len(variants[0].args) != 1u {
2352                 break;
2353             }
2354             t1 =
2355                 ty::substitute_type_params(ccx.tcx, tps, variants[0].args[0]);
2356             if check type_has_static_size(ccx, t1) {
2357                 v1 = PointerCast(cx, v1, T_ptr(type_of(ccx, sp, t1)));
2358             } else { } // FIXME: typestate hack
2359           }
2360           _ { break; }
2361         }
2362         v1 = load_if_immediate(cx, v1, t1);
2363     }
2364     ret {bcx: cx, val: v1, ty: t1};
2365 }
2366
2367 fn trans_lazy_binop(bcx: @block_ctxt, op: ast::binop, a: @ast::expr,
2368                     b: @ast::expr, dest: dest) -> @block_ctxt {
2369     let is_and = alt op { ast::and. { true } ast::or. { false } };
2370     let lhs_res = trans_temp_expr(bcx, a);
2371     if lhs_res.bcx.unreachable { ret lhs_res.bcx; }
2372     let rhs_cx = new_scope_block_ctxt(lhs_res.bcx, "rhs");
2373     let rhs_res = trans_temp_expr(rhs_cx, b);
2374
2375     let lhs_past_cx = new_scope_block_ctxt(lhs_res.bcx, "lhs");
2376     // The following line ensures that any cleanups for rhs
2377     // are done within the block for rhs. This is necessary
2378     // because and/or are lazy. So the rhs may never execute,
2379     // and the cleanups can't be pushed into later code.
2380     let rhs_bcx = trans_block_cleanups(rhs_res.bcx, rhs_cx);
2381     if is_and {
2382         CondBr(lhs_res.bcx, lhs_res.val, rhs_cx.llbb, lhs_past_cx.llbb);
2383     } else {
2384         CondBr(lhs_res.bcx, lhs_res.val, lhs_past_cx.llbb, rhs_cx.llbb);
2385     }
2386
2387     let join_cx = new_sub_block_ctxt(bcx, "join");
2388     Br(lhs_past_cx, join_cx.llbb);
2389     if rhs_bcx.unreachable {
2390         ret store_in_dest(join_cx, C_bool(!is_and), dest);
2391     }
2392     Br(rhs_bcx, join_cx.llbb);
2393     let phi = Phi(join_cx, T_bool(), [C_bool(!is_and), rhs_res.val],
2394                   [lhs_past_cx.llbb, rhs_bcx.llbb]);
2395     ret store_in_dest(join_cx, phi, dest);
2396 }
2397
2398 fn trans_binary(cx: @block_ctxt, op: ast::binop, a: @ast::expr, b: @ast::expr,
2399                 dest: dest) -> @block_ctxt {
2400     // First couple cases are lazy:
2401     alt op {
2402       ast::and. | ast::or. {
2403         ret trans_lazy_binop(cx, op, a, b, dest);
2404       }
2405       _ {
2406         // Remaining cases are eager:
2407         let lhs = trans_temp_expr(cx, a);
2408         let rhs = trans_temp_expr(lhs.bcx, b);
2409         ret trans_eager_binop(rhs.bcx, op, lhs.val,
2410                               ty::expr_ty(bcx_tcx(cx), a), rhs.val,
2411                               ty::expr_ty(bcx_tcx(cx), b), dest);
2412       }
2413     }
2414 }
2415
2416 tag dest {
2417     by_val(@mutable ValueRef);
2418     save_in(ValueRef);
2419     ignore;
2420 }
2421
2422 fn empty_dest_cell() -> @mutable ValueRef {
2423     ret @mutable llvm::LLVMGetUndef(T_nil());
2424 }
2425
2426 fn dup_for_join(dest: dest) -> dest {
2427     alt dest {
2428       by_val(_) { by_val(empty_dest_cell()) }
2429       _ { dest }
2430     }
2431 }
2432
2433 fn join_returns(parent_cx: @block_ctxt, in_cxs: [@block_ctxt],
2434                 in_ds: [dest], out_dest: dest) -> @block_ctxt {
2435     let out = new_sub_block_ctxt(parent_cx, "join");
2436     let reachable = false, i = 0u, phi = none;
2437     for cx in in_cxs {
2438         if !cx.unreachable {
2439             Br(cx, out.llbb);
2440             reachable = true;
2441             alt in_ds[i] {
2442               by_val(cell) {
2443                 if option::is_none(phi) {
2444                     phi = some(EmptyPhi(out, val_ty(*cell)));
2445                 }
2446                 AddIncomingToPhi(option::get(phi), *cell, cx.llbb);
2447               }
2448               _ {}
2449             }
2450         }
2451         i += 1u;
2452     }
2453     if !reachable {
2454         Unreachable(out);
2455     } else {
2456         alt out_dest {
2457           by_val(cell) { *cell = option::get(phi); }
2458           _ {}
2459         }
2460     }
2461     ret out;
2462 }
2463
2464 // Used to put an immediate value in a dest.
2465 fn store_in_dest(bcx: @block_ctxt, val: ValueRef, dest: dest) -> @block_ctxt {
2466     alt dest {
2467       ignore. {}
2468       by_val(cell) { *cell = val; }
2469       save_in(addr) { Store(bcx, val, addr); }
2470     }
2471     ret bcx;
2472 }
2473
2474 fn get_dest_addr(dest: dest) -> ValueRef {
2475     alt dest { save_in(a) { a } }
2476 }
2477
2478 fn trans_if(cx: @block_ctxt, cond: @ast::expr, thn: ast::blk,
2479             els: option::t<@ast::expr>, dest: dest)
2480     -> @block_ctxt {
2481     let {bcx, val: cond_val} = trans_temp_expr(cx, cond);
2482
2483     let then_dest = dup_for_join(dest);
2484     let else_dest = dup_for_join(dest);
2485     let then_cx = new_scope_block_ctxt(bcx, "then");
2486     let else_cx = new_scope_block_ctxt(bcx, "else");
2487     CondBr(bcx, cond_val, then_cx.llbb, else_cx.llbb);
2488     then_cx = trans_block_dps(then_cx, thn, then_dest);
2489     // Calling trans_block directly instead of trans_expr
2490     // because trans_expr will create another scope block
2491     // context for the block, but we've already got the
2492     // 'else' context
2493     alt els {
2494       some(elexpr) {
2495         alt elexpr.node {
2496           ast::expr_if(_, _, _) {
2497             let elseif_blk = ast_util::block_from_expr(elexpr);
2498             else_cx = trans_block_dps(else_cx, elseif_blk, else_dest);
2499           }
2500           ast::expr_block(blk) {
2501             else_cx = trans_block_dps(else_cx, blk, else_dest);
2502           }
2503         }
2504       }
2505       _ {}
2506     }
2507     ret join_returns(cx, [then_cx, else_cx], [then_dest, else_dest], dest);
2508 }
2509
2510 fn trans_for(cx: @block_ctxt, local: @ast::local, seq: @ast::expr,
2511              body: ast::blk) -> @block_ctxt {
2512     fn inner(bcx: @block_ctxt, local: @ast::local, curr: ValueRef, t: ty::t,
2513              body: ast::blk, outer_next_cx: @block_ctxt) -> @block_ctxt {
2514         let next_cx = new_sub_block_ctxt(bcx, "next");
2515         let scope_cx =
2516             new_loop_scope_block_ctxt(bcx, option::some(next_cx),
2517                                       outer_next_cx, "for loop scope");
2518         Br(bcx, scope_cx.llbb);
2519         let curr = PointerCast(bcx, curr, T_ptr(type_of_or_i8(bcx, t)));
2520         let bcx = trans_alt::bind_irrefutable_pat(scope_cx, local.node.pat,
2521                                                   curr, false);
2522         bcx = trans_block_dps(bcx, body, ignore);
2523         Br(bcx, next_cx.llbb);
2524         ret next_cx;
2525     }
2526     let ccx = bcx_ccx(cx);
2527     let next_cx = new_sub_block_ctxt(cx, "next");
2528     let seq_ty = ty::expr_ty(bcx_tcx(cx), seq);
2529     let {bcx: bcx, val: seq} = trans_temp_expr(cx, seq);
2530     let seq = PointerCast(bcx, seq, T_ptr(ccx.opaque_vec_type));
2531     let fill = tvec::get_fill(bcx, seq);
2532     if ty::type_is_str(bcx_tcx(bcx), seq_ty) {
2533         fill = Sub(bcx, fill, C_int(ccx, 1));
2534     }
2535     let bcx = tvec::iter_vec_raw(bcx, seq, seq_ty, fill,
2536                                  bind inner(_, local, _, _, body, next_cx));
2537     Br(bcx, next_cx.llbb);
2538     ret next_cx;
2539 }
2540
2541 fn trans_while(cx: @block_ctxt, cond: @ast::expr, body: ast::blk)
2542     -> @block_ctxt {
2543     let next_cx = new_sub_block_ctxt(cx, "while next");
2544     let cond_cx =
2545         new_loop_scope_block_ctxt(cx, option::none::<@block_ctxt>, next_cx,
2546                                   "while cond");
2547     let body_cx = new_scope_block_ctxt(cond_cx, "while loop body");
2548     let body_end = trans_block(body_cx, body);
2549     let cond_res = trans_temp_expr(cond_cx, cond);
2550     Br(body_end, cond_cx.llbb);
2551     let cond_bcx = trans_block_cleanups(cond_res.bcx, cond_cx);
2552     CondBr(cond_bcx, cond_res.val, body_cx.llbb, next_cx.llbb);
2553     Br(cx, cond_cx.llbb);
2554     ret next_cx;
2555 }
2556
2557 fn trans_do_while(cx: @block_ctxt, body: ast::blk, cond: @ast::expr) ->
2558     @block_ctxt {
2559     let next_cx = new_sub_block_ctxt(cx, "next");
2560     let body_cx =
2561         new_loop_scope_block_ctxt(cx, option::none::<@block_ctxt>, next_cx,
2562                                   "do-while loop body");
2563     let body_end = trans_block(body_cx, body);
2564     let cond_cx = new_scope_block_ctxt(body_cx, "do-while cond");
2565     Br(body_end, cond_cx.llbb);
2566     let cond_res = trans_temp_expr(cond_cx, cond);
2567     let cond_bcx = trans_block_cleanups(cond_res.bcx, cond_cx);
2568     CondBr(cond_bcx, cond_res.val, body_cx.llbb, next_cx.llbb);
2569     Br(cx, body_cx.llbb);
2570     ret next_cx;
2571 }
2572
2573 type generic_info = {
2574     item_type: ty::t,
2575     static_tis: [option::t<@tydesc_info>],
2576     tydescs: [ValueRef],
2577     param_bounds: @[ty::param_bounds],
2578     origins: option::t<typeck::dict_res>
2579 };
2580
2581 tag lval_kind {
2582     temporary; //< Temporary value passed by value if of immediate type
2583     owned;     //< Non-temporary value passed by pointer
2584     owned_imm; //< Non-temporary value passed by value
2585 }
2586 type local_var_result = {val: ValueRef, kind: lval_kind};
2587 type lval_result = {bcx: @block_ctxt, val: ValueRef, kind: lval_kind};
2588 tag callee_env {
2589     null_env;
2590     is_closure;
2591     obj_env(ValueRef);
2592     dict_env(ValueRef, ValueRef);
2593 }
2594 type lval_maybe_callee = {bcx: @block_ctxt,
2595                           val: ValueRef,
2596                           kind: lval_kind,
2597                           env: callee_env,
2598                           generic: option::t<generic_info>};
2599
2600 fn null_env_ptr(bcx: @block_ctxt) -> ValueRef {
2601     C_null(T_opaque_cbox_ptr(bcx_ccx(bcx)))
2602 }
2603
2604 fn lval_from_local_var(bcx: @block_ctxt, r: local_var_result) -> lval_result {
2605     ret { bcx: bcx, val: r.val, kind: r.kind };
2606 }
2607
2608 fn lval_owned(bcx: @block_ctxt, val: ValueRef) -> lval_result {
2609     ret {bcx: bcx, val: val, kind: owned};
2610 }
2611 fn lval_temp(bcx: @block_ctxt, val: ValueRef) -> lval_result {
2612     ret {bcx: bcx, val: val, kind: temporary};
2613 }
2614
2615 fn lval_no_env(bcx: @block_ctxt, val: ValueRef, kind: lval_kind)
2616     -> lval_maybe_callee {
2617     ret {bcx: bcx, val: val, kind: kind, env: is_closure, generic: none};
2618 }
2619
2620 fn trans_external_path(cx: @block_ctxt, did: ast::def_id,
2621                        tpt: ty::ty_param_bounds_and_ty) -> ValueRef {
2622     let lcx = cx.fcx.lcx;
2623     let name = csearch::get_symbol(lcx.ccx.sess.get_cstore(), did);
2624     ret get_extern_const(lcx.ccx.externs, lcx.ccx.llmod, name,
2625                          type_of_ty_param_bounds_and_ty(lcx, cx.sp, tpt));
2626 }
2627
2628 fn lval_static_fn(bcx: @block_ctxt, fn_id: ast::def_id, id: ast::node_id)
2629     -> lval_maybe_callee {
2630     let ccx = bcx_ccx(bcx);
2631     let tpt = ty::lookup_item_type(ccx.tcx, fn_id);
2632     let val = if fn_id.crate == ast::local_crate {
2633         // Internal reference.
2634         assert (ccx.item_ids.contains_key(fn_id.node));
2635         ccx.item_ids.get(fn_id.node)
2636     } else {
2637         // External reference.
2638         trans_external_path(bcx, fn_id, tpt)
2639     };
2640     let tys = ty::node_id_to_type_params(ccx.tcx, id);
2641     let gen = none, bcx = bcx;
2642     if vec::len(tys) != 0u {
2643         let tydescs = [], tis = [];
2644         for t in tys {
2645             // TODO: Doesn't always escape.
2646             let ti = none;
2647             let td = get_tydesc(bcx, t, true, tps_normal, ti).result;
2648             tis += [ti];
2649             bcx = td.bcx;
2650             tydescs += [td.val];
2651         }
2652         gen = some({item_type: tpt.ty,
2653                     static_tis: tis,
2654                     tydescs: tydescs,
2655                     param_bounds: tpt.bounds,
2656                     origins: ccx.dict_map.find(id)});
2657     }
2658     ret {bcx: bcx, val: val, kind: owned, env: null_env, generic: gen};
2659 }
2660
2661 fn lookup_discriminant(lcx: @local_ctxt, vid: ast::def_id) -> ValueRef {
2662     let ccx = lcx.ccx;
2663     alt ccx.discrims.find(vid) {
2664       none. {
2665         // It's an external discriminant that we haven't seen yet.
2666         assert (vid.crate != ast::local_crate);
2667         let sym = csearch::get_symbol(lcx.ccx.sess.get_cstore(), vid);
2668         let gvar =
2669             str::as_buf(sym,
2670                         {|buf|
2671                             llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
2672                         });
2673         llvm::LLVMSetLinkage(gvar,
2674                              lib::llvm::LLVMExternalLinkage as llvm::Linkage);
2675         llvm::LLVMSetGlobalConstant(gvar, True);
2676         lcx.ccx.discrims.insert(vid, gvar);
2677         ret gvar;
2678       }
2679       some(llval) { ret llval; }
2680     }
2681 }
2682
2683 fn trans_local_var(cx: @block_ctxt, def: ast::def) -> local_var_result {
2684     fn take_local(table: hashmap<ast::node_id, local_val>,
2685                   id: ast::node_id) -> local_var_result {
2686         alt table.find(id) {
2687           some(local_mem(v)) { {val: v, kind: owned} }
2688           some(local_imm(v)) { {val: v, kind: owned_imm} }
2689         }
2690     }
2691     alt def {
2692       ast::def_upvar(did, _, _) {
2693         assert (cx.fcx.llupvars.contains_key(did.node));
2694         ret { val: cx.fcx.llupvars.get(did.node), kind: owned };
2695       }
2696       ast::def_arg(did, _) {
2697         ret take_local(cx.fcx.llargs, did.node);
2698       }
2699       ast::def_local(did, _) | ast::def_binding(did) {
2700         ret take_local(cx.fcx.lllocals, did.node);
2701       }
2702       ast::def_obj_field(did, _) {
2703         assert (cx.fcx.llobjfields.contains_key(did.node));
2704         ret { val: cx.fcx.llobjfields.get(did.node), kind: owned };
2705       }
2706       ast::def_self(did) {
2707         let slf = option::get(cx.fcx.llself);
2708         let ptr = PointerCast(cx, slf.v, T_ptr(type_of_or_i8(cx, slf.t)));
2709         ret {val: ptr, kind: owned};
2710       }
2711       _ {
2712         bcx_ccx(cx).sess.span_unimpl
2713             (cx.sp, "unsupported def type in trans_local_def");
2714       }
2715     }
2716 }
2717
2718 fn trans_path(cx: @block_ctxt, p: @ast::path, id: ast::node_id)
2719     -> lval_maybe_callee {
2720     ret trans_var(cx, p.span, bcx_tcx(cx).def_map.get(id), id);
2721 }
2722
2723 fn trans_var(cx: @block_ctxt, sp: span, def: ast::def, id: ast::node_id)
2724     -> lval_maybe_callee {
2725     let ccx = bcx_ccx(cx);
2726     alt def {
2727       ast::def_fn(did, _) | ast::def_native_fn(did, _) {
2728         ret lval_static_fn(cx, did, id);
2729       }
2730       ast::def_variant(tid, vid) {
2731         if vec::len(ty::tag_variant_with_id(ccx.tcx, tid, vid).args) > 0u {
2732             // N-ary variant.
2733             ret lval_static_fn(cx, vid, id);
2734         } else {
2735             // Nullary variant.
2736             let tag_ty = node_id_type(ccx, id);
2737             let alloc_result = alloc_ty(cx, tag_ty);
2738             let lltagblob = alloc_result.val;
2739             let lltagty = type_of_tag(ccx, sp, tid, tag_ty);
2740             let bcx = alloc_result.bcx;
2741             let lltagptr = PointerCast(bcx, lltagblob, T_ptr(lltagty));
2742             let lldiscrimptr = GEPi(bcx, lltagptr, [0, 0]);
2743             let d = if vec::len(*ty::tag_variants(ccx.tcx, tid)) != 1u {
2744                 let lldiscrim_gv = lookup_discriminant(bcx.fcx.lcx, vid);
2745                 let lldiscrim = Load(bcx, lldiscrim_gv);
2746                 lldiscrim
2747             } else { C_int(ccx, 0) };
2748             Store(bcx, d, lldiscrimptr);
2749             ret lval_no_env(bcx, lltagptr, temporary);
2750         }
2751       }
2752       ast::def_const(did) {
2753         if did.crate == ast::local_crate {
2754             assert (ccx.consts.contains_key(did.node));
2755             ret lval_no_env(cx, ccx.consts.get(did.node), owned);
2756         } else {
2757             let tp = ty::node_id_to_monotype(ccx.tcx, id);
2758             let val = trans_external_path(cx, did, {bounds: @[], ty: tp});
2759             ret lval_no_env(cx, load_if_immediate(cx, val, tp), owned_imm);
2760         }
2761       }
2762       _ {
2763         let loc = trans_local_var(cx, def);
2764         ret lval_no_env(cx, loc.val, loc.kind);
2765       }
2766     }
2767 }
2768
2769 fn trans_object_field(bcx: @block_ctxt, o: @ast::expr, field: ast::ident)
2770     -> {bcx: @block_ctxt, mthptr: ValueRef, objptr: ValueRef} {
2771     let {bcx, val} = trans_temp_expr(bcx, o);
2772     let {bcx, val, ty} = autoderef(bcx, val, ty::expr_ty(bcx_tcx(bcx), o));
2773     ret trans_object_field_inner(bcx, val, field, ty);
2774 }
2775
2776 fn trans_object_field_inner(bcx: @block_ctxt, o: ValueRef,
2777                             field: ast::ident, o_ty: ty::t)
2778     -> {bcx: @block_ctxt, mthptr: ValueRef, objptr: ValueRef} {
2779     let ccx = bcx_ccx(bcx), tcx = ccx.tcx;
2780     let mths = alt ty::struct(tcx, o_ty) { ty::ty_obj(ms) { ms } };
2781
2782     let ix = option::get(ty::method_idx(field, mths));
2783     let vtbl = Load(bcx, GEPi(bcx, o, [0, abi::obj_field_vtbl]));
2784     let vtbl_type = T_ptr(T_array(T_ptr(T_nil()), ix + 1u));
2785     vtbl = PointerCast(bcx, vtbl, vtbl_type);
2786
2787     let v = GEPi(bcx, vtbl, [0, ix as int]);
2788     let fn_ty: ty::t = ty::mk_fn(tcx, mths[ix].fty);
2789     let ret_ty = ty::ty_fn_ret(tcx, fn_ty);
2790     // FIXME: constrain ty_obj?
2791     let ll_fn_ty = type_of_fn(ccx, bcx.sp, true,
2792                               ty::ty_fn_args(tcx, fn_ty), ret_ty, []);
2793     v = Load(bcx, PointerCast(bcx, v, T_ptr(T_ptr(ll_fn_ty))));
2794     ret {bcx: bcx, mthptr: v, objptr: o};
2795 }
2796
2797
2798 fn trans_rec_field(bcx: @block_ctxt, base: @ast::expr,
2799                    field: ast::ident) -> lval_result {
2800     let {bcx, val} = trans_temp_expr(bcx, base);
2801     let {bcx, val, ty} = autoderef(bcx, val, ty::expr_ty(bcx_tcx(bcx), base));
2802     let fields = alt ty::struct(bcx_tcx(bcx), ty) { ty::ty_rec(fs) { fs } };
2803     let ix = option::get(ty::field_idx(field, fields));
2804     // Silly check
2805     check type_is_tup_like(bcx, ty);
2806     let {bcx, val} = GEP_tup_like(bcx, ty, val, [0, ix as int]);
2807     ret {bcx: bcx, val: val, kind: owned};
2808 }
2809
2810 fn trans_index(cx: @block_ctxt, sp: span, base: @ast::expr, idx: @ast::expr,
2811                id: ast::node_id) -> lval_result {
2812     // Is this an interior vector?
2813     let base_ty = ty::expr_ty(bcx_tcx(cx), base);
2814     let exp = trans_temp_expr(cx, base);
2815     let lv = autoderef(exp.bcx, exp.val, base_ty);
2816     let ix = trans_temp_expr(lv.bcx, idx);
2817     let v = lv.val;
2818     let bcx = ix.bcx;
2819     let ccx = bcx_ccx(cx);
2820
2821     // Cast to an LLVM integer. Rust is less strict than LLVM in this regard.
2822     let ix_val;
2823     let ix_size = llsize_of_real(bcx_ccx(cx), val_ty(ix.val));
2824     let int_size = llsize_of_real(bcx_ccx(cx), ccx.int_type);
2825     if ix_size < int_size {
2826         ix_val = ZExt(bcx, ix.val, ccx.int_type);
2827     } else if ix_size > int_size {
2828         ix_val = Trunc(bcx, ix.val, ccx.int_type);
2829     } else { ix_val = ix.val; }
2830
2831     let unit_ty = node_id_type(bcx_ccx(cx), id);
2832     let unit_sz = size_of(bcx, unit_ty);
2833     bcx = unit_sz.bcx;
2834     maybe_name_value(bcx_ccx(cx), unit_sz.val, "unit_sz");
2835     let scaled_ix = Mul(bcx, ix_val, unit_sz.val);
2836     maybe_name_value(bcx_ccx(cx), scaled_ix, "scaled_ix");
2837     let lim = tvec::get_fill(bcx, v);
2838     let body = tvec::get_dataptr(bcx, v, type_of_or_i8(bcx, unit_ty));
2839     let bounds_check = ICmp(bcx, lib::llvm::LLVMIntULT, scaled_ix, lim);
2840     let fail_cx = new_sub_block_ctxt(bcx, "fail");
2841     let next_cx = new_sub_block_ctxt(bcx, "next");
2842     let ncx = bcx_ccx(next_cx);
2843     CondBr(bcx, bounds_check, next_cx.llbb, fail_cx.llbb);
2844     // fail: bad bounds check.
2845
2846     trans_fail(fail_cx, some::<span>(sp), "bounds check");
2847     let elt =
2848         if check type_has_static_size(ncx, unit_ty) {
2849             let elt_1 = GEP(next_cx, body, [ix_val]);
2850             let llunitty = type_of(ncx, sp, unit_ty);
2851             PointerCast(next_cx, elt_1, T_ptr(llunitty))
2852         } else {
2853             body = PointerCast(next_cx, body, T_ptr(T_i8()));
2854             GEP(next_cx, body, [scaled_ix])
2855         };
2856
2857     ret lval_owned(next_cx, elt);
2858 }
2859
2860 fn expr_is_lval(bcx: @block_ctxt, e: @ast::expr) -> bool {
2861     let ccx = bcx_ccx(bcx);
2862     ty::expr_is_lval(ccx.method_map, ccx.tcx, e)
2863 }
2864
2865 fn trans_callee(bcx: @block_ctxt, e: @ast::expr) -> lval_maybe_callee {
2866     alt e.node {
2867       ast::expr_path(p) { ret trans_path(bcx, p, e.id); }
2868       ast::expr_field(base, ident, _) {
2869         // Lval means this is a record field, so not a method
2870         if !expr_is_lval(bcx, e) {
2871             alt bcx_ccx(bcx).method_map.find(e.id) {
2872               some(typeck::method_static(did)) { // An impl method
2873                 ret trans_impl::trans_static_callee(bcx, e, base, did);
2874               }
2875               some(typeck::method_param(iid, off, p, b)) {
2876                 ret trans_impl::trans_dict_callee(
2877                     bcx, e, base, iid, off, p, b);
2878               }
2879               none. { // An object method
2880                 let of = trans_object_field(bcx, base, ident);
2881                 ret {bcx: of.bcx, val: of.mthptr, kind: owned,
2882                      env: obj_env(of.objptr), generic: none};
2883               }
2884             }
2885         }
2886       }
2887       _ {}
2888     }
2889     let lv = trans_temp_lval(bcx, e);
2890     ret lval_no_env(lv.bcx, lv.val, lv.kind);
2891 }
2892
2893 // Use this when you know you are compiling an lval.
2894 // The additional bool returned indicates whether it's mem (that is
2895 // represented as an alloca or heap, hence needs a 'load' to be used as an
2896 // immediate).
2897 fn trans_lval(cx: @block_ctxt, e: @ast::expr) -> lval_result {
2898     alt e.node {
2899       ast::expr_path(p) {
2900         let v = trans_path(cx, p, e.id);
2901         ret lval_maybe_callee_to_lval(v, ty::expr_ty(bcx_tcx(cx), e));
2902       }
2903       ast::expr_field(base, ident, _) {
2904         ret trans_rec_field(cx, base, ident);
2905       }
2906       ast::expr_index(base, idx) {
2907         ret trans_index(cx, e.span, base, idx, e.id);
2908       }
2909       ast::expr_unary(ast::deref., base) {
2910         let ccx = bcx_ccx(cx);
2911         let sub = trans_temp_expr(cx, base);
2912         let t = ty::expr_ty(ccx.tcx, base);
2913         let val =
2914             alt ty::struct(ccx.tcx, t) {
2915               ty::ty_box(_) {
2916                 GEPi(sub.bcx, sub.val, [0, abi::box_rc_field_body])
2917               }
2918               ty::ty_res(_, _, _) {
2919                 GEPi(sub.bcx, sub.val, [0, 1])
2920               }
2921               ty::ty_tag(_, _) {
2922                 let ety = ty::expr_ty(ccx.tcx, e);
2923                 let sp = e.span;
2924                 let ellty =
2925                     if check type_has_static_size(ccx, ety) {
2926                         T_ptr(type_of(ccx, sp, ety))
2927                     } else { T_typaram_ptr(ccx.tn) };
2928                 PointerCast(sub.bcx, sub.val, ellty)
2929               }
2930               ty::ty_ptr(_) | ty::ty_uniq(_) { sub.val }
2931             };
2932         ret lval_owned(sub.bcx, val);
2933       }
2934       // This is a by-ref returning call. Regular calls are not lval
2935       ast::expr_call(f, args, _) {
2936         let cell = empty_dest_cell();
2937         let bcx = trans_call(cx, f, args, e.id, by_val(cell));
2938         ret lval_owned(bcx, *cell);
2939       }
2940       _ { bcx_ccx(cx).sess.span_bug(e.span, "non-lval in trans_lval"); }
2941     }
2942 }
2943
2944 fn maybe_add_env(bcx: @block_ctxt, c: lval_maybe_callee)
2945     -> (lval_kind, ValueRef) {
2946     alt c.env {
2947       is_closure. { (c.kind, c.val) }
2948       obj_env(_) | dict_env(_, _) {
2949         fail "Taking the value of a method does not work yet (issue #435)";
2950       }
2951       null_env. {
2952         let llfnty = llvm::LLVMGetElementType(val_ty(c.val));
2953         (temporary, create_real_fn_pair(bcx, llfnty, c.val,
2954                                         null_env_ptr(bcx)))
2955       }
2956     }
2957 }
2958
2959 fn lval_maybe_callee_to_lval(c: lval_maybe_callee, ty: ty::t) -> lval_result {
2960     alt c.generic {
2961       some(gi) {
2962         let n_args = vec::len(ty::ty_fn_args(bcx_tcx(c.bcx), ty));
2963         let args = vec::init_elt(none::<@ast::expr>, n_args);
2964         let space = alloc_ty(c.bcx, ty);
2965         let bcx = trans_closure::trans_bind_1(space.bcx, ty, c, args, ty,
2966                                               save_in(space.val));
2967         add_clean_temp(bcx, space.val, ty);
2968         ret {bcx: bcx, val: space.val, kind: temporary};
2969       }
2970       none. {
2971         let (kind, val) = maybe_add_env(c.bcx, c);
2972         ret {bcx: c.bcx, val: val, kind: kind};
2973       }
2974     }
2975 }
2976
2977 fn int_cast(bcx: @block_ctxt, lldsttype: TypeRef, llsrctype: TypeRef,
2978             llsrc: ValueRef, signed: bool) -> ValueRef {
2979     let srcsz = llvm::LLVMGetIntTypeWidth(llsrctype);
2980     let dstsz = llvm::LLVMGetIntTypeWidth(lldsttype);
2981     ret if dstsz == srcsz {
2982             BitCast(bcx, llsrc, lldsttype)
2983         } else if srcsz > dstsz {
2984             TruncOrBitCast(bcx, llsrc, lldsttype)
2985         } else if signed {
2986             SExtOrBitCast(bcx, llsrc, lldsttype)
2987         } else { ZExtOrBitCast(bcx, llsrc, lldsttype) };
2988 }
2989
2990 fn float_cast(bcx: @block_ctxt, lldsttype: TypeRef, llsrctype: TypeRef,
2991               llsrc: ValueRef) -> ValueRef {
2992     let srcsz = lib::llvm::float_width(llsrctype);
2993     let dstsz = lib::llvm::float_width(lldsttype);
2994     ret if dstsz > srcsz {
2995             FPExt(bcx, llsrc, lldsttype)
2996         } else if srcsz > dstsz {
2997             FPTrunc(bcx, llsrc, lldsttype)
2998         } else { llsrc };
2999 }
3000
3001 fn trans_cast(cx: @block_ctxt, e: @ast::expr, id: ast::node_id,
3002               dest: dest) -> @block_ctxt {
3003     let ccx = bcx_ccx(cx);
3004     let e_res = trans_temp_expr(cx, e);
3005     let ll_t_in = val_ty(e_res.val);
3006     let t_in = ty::expr_ty(ccx.tcx, e);
3007     let t_out = node_id_type(ccx, id);
3008     // Check should be avoidable because it's a cast.
3009     // FIXME: Constrain types so as to avoid this check.
3010     check (type_has_static_size(ccx, t_out));
3011     let ll_t_out = type_of(ccx, e.span, t_out);
3012
3013     tag kind { pointer; integral; float; other; }
3014     fn t_kind(tcx: ty::ctxt, t: ty::t) -> kind {
3015         ret if ty::type_is_fp(tcx, t) {
3016                 float
3017             } else if ty::type_is_native(tcx, t) ||
3018                       ty::type_is_unsafe_ptr(tcx, t) {
3019                 pointer
3020             } else if ty::type_is_integral(tcx, t) {
3021                 integral
3022             } else { other };
3023     }
3024     let k_in = t_kind(ccx.tcx, t_in);
3025     let k_out = t_kind(ccx.tcx, t_out);
3026     let s_in = k_in == integral && ty::type_is_signed(ccx.tcx, t_in);
3027
3028     let newval =
3029         alt {in: k_in, out: k_out} {
3030           {in: integral., out: integral.} {
3031             int_cast(e_res.bcx, ll_t_out, ll_t_in, e_res.val, s_in)
3032           }
3033           {in: float., out: float.} {
3034             float_cast(e_res.bcx, ll_t_out, ll_t_in, e_res.val)
3035           }
3036           {in: integral., out: float.} {
3037             if s_in {
3038                 SIToFP(e_res.bcx, e_res.val, ll_t_out)
3039             } else { UIToFP(e_res.bcx, e_res.val, ll_t_out) }
3040           }
3041           {in: float., out: integral.} {
3042             if ty::type_is_signed(ccx.tcx, t_out) {
3043                 FPToSI(e_res.bcx, e_res.val, ll_t_out)
3044             } else { FPToUI(e_res.bcx, e_res.val, ll_t_out) }
3045           }
3046           {in: integral., out: pointer.} {
3047             IntToPtr(e_res.bcx, e_res.val, ll_t_out)
3048           }
3049           {in: pointer., out: integral.} {
3050             PtrToInt(e_res.bcx, e_res.val, ll_t_out)
3051           }
3052           {in: pointer., out: pointer.} {
3053             PointerCast(e_res.bcx, e_res.val, ll_t_out)
3054           }
3055           _ { ccx.sess.bug("Translating unsupported cast.") }
3056         };
3057     ret store_in_dest(e_res.bcx, newval, dest);
3058 }
3059
3060 fn trans_arg_expr(cx: @block_ctxt, arg: ty::arg, lldestty0: TypeRef,
3061                   &to_zero: [{v: ValueRef, t: ty::t}],
3062                   &to_revoke: [{v: ValueRef, t: ty::t}], e: @ast::expr) ->
3063    result {
3064     let ccx = bcx_ccx(cx);
3065     let e_ty = ty::expr_ty(ccx.tcx, e);
3066     let is_bot = ty::type_is_bot(ccx.tcx, e_ty);
3067     let lv = trans_temp_lval(cx, e);
3068     let bcx = lv.bcx;
3069     let val = lv.val;
3070     if is_bot {
3071         // For values of type _|_, we generate an
3072         // "undef" value, as such a value should never
3073         // be inspected. It's important for the value
3074         // to have type lldestty0 (the callee's expected type).
3075         val = llvm::LLVMGetUndef(lldestty0);
3076     } else if arg.mode == ast::by_ref || arg.mode == ast::by_val {
3077         let copied = false, imm = ty::type_is_immediate(ccx.tcx, e_ty);
3078         if arg.mode == ast::by_ref && lv.kind != owned && imm {
3079             val = do_spill_noroot(bcx, val);
3080             copied = true;
3081         }
3082         if ccx.copy_map.contains_key(e.id) && lv.kind != temporary {
3083             if !copied {
3084                 let alloc = alloc_ty(bcx, e_ty);
3085                 bcx = copy_val(alloc.bcx, INIT, alloc.val,
3086                                load_if_immediate(alloc.bcx, val, e_ty), e_ty);
3087                 val = alloc.val;
3088             } else { bcx = take_ty(bcx, val, e_ty); }
3089             add_clean(bcx, val, e_ty);
3090         }
3091         if arg.mode == ast::by_val && (lv.kind == owned || !imm) {
3092             val = Load(bcx, val);
3093         }
3094     } else if arg.mode == ast::by_copy {
3095         let {bcx: cx, val: alloc} = alloc_ty(bcx, e_ty);
3096         let last_use = ccx.last_uses.contains_key(e.id);
3097         bcx = cx;
3098         if lv.kind == temporary { revoke_clean(bcx, val); }
3099         if lv.kind == owned || !ty::type_is_immediate(ccx.tcx, e_ty) {
3100             bcx = memmove_ty(bcx, alloc, val, e_ty);
3101             if last_use && ty::type_needs_drop(ccx.tcx, e_ty) {
3102                 bcx = zero_alloca(bcx, val, e_ty);
3103             }
3104         } else { Store(bcx, val, alloc); }
3105         val = alloc;
3106         if lv.kind != temporary && !last_use {
3107             bcx = take_ty(bcx, val, e_ty);
3108         }
3109     } else if ty::type_is_immediate(ccx.tcx, e_ty) && lv.kind != owned {
3110         let r = do_spill(bcx, val, e_ty);
3111         val = r.val;
3112         bcx = r.bcx;
3113     }
3114
3115     if !is_bot && ty::type_contains_params(ccx.tcx, arg.ty) {
3116         let lldestty = lldestty0;
3117         val = PointerCast(bcx, val, lldestty);
3118     }
3119
3120     // Collect arg for later if it happens to be one we've moving out.
3121     if arg.mode == ast::by_move {
3122         if lv.kind == owned {
3123             // Use actual ty, not declared ty -- anything else doesn't make
3124             // sense if declared ty is a ty param
3125             to_zero += [{v: lv.val, t: e_ty}];
3126         } else { to_revoke += [{v: lv.val, t: e_ty}]; }
3127     }
3128     ret rslt(bcx, val);
3129 }
3130
3131
3132 // NB: must keep 4 fns in sync:
3133 //
3134 //  - type_of_fn
3135 //  - create_llargs_for_fn_args.
3136 //  - new_fn_ctxt
3137 //  - trans_args
3138 fn trans_args(cx: @block_ctxt, llenv: ValueRef,
3139               gen: option::t<generic_info>, es: [@ast::expr], fn_ty: ty::t,
3140               dest: dest)
3141    -> {bcx: @block_ctxt,
3142        args: [ValueRef],
3143        retslot: ValueRef,
3144        to_zero: [{v: ValueRef, t: ty::t}],
3145        to_revoke: [{v: ValueRef, t: ty::t}]} {
3146
3147     let args: [ty::arg] = ty::ty_fn_args(bcx_tcx(cx), fn_ty);
3148     let llargs: [ValueRef] = [];
3149     let lltydescs: [ValueRef] = [];
3150     let to_zero = [];
3151     let to_revoke = [];
3152
3153     let ccx = bcx_ccx(cx);
3154     let tcx = ccx.tcx;
3155     let bcx = cx;
3156
3157     let retty = ty::ty_fn_ret(tcx, fn_ty), full_retty = retty;
3158     alt gen {
3159       some(g) {
3160         lazily_emit_all_generic_info_tydesc_glues(cx, g);
3161         let i = 0u, n_orig = 0u;
3162         for param in *g.param_bounds {
3163             lltydescs += [g.tydescs[i]];
3164             for bound in *param {
3165                 alt bound {
3166                   ty::bound_iface(_) {
3167                     let res = trans_impl::get_dict(
3168                         bcx, option::get(g.origins)[n_orig]);
3169                     lltydescs += [res.val];
3170                     bcx = res.bcx;
3171                     n_orig += 1u;
3172                   }
3173                   _ {}
3174                 }
3175             }
3176             i += 1u;
3177         }
3178         args = ty::ty_fn_args(tcx, g.item_type);
3179         retty = ty::ty_fn_ret(tcx, g.item_type);
3180       }
3181       _ { }
3182     }
3183     // Arg 0: Output pointer.
3184     let llretslot = alt dest {
3185       ignore. {
3186         if ty::type_is_nil(tcx, retty) {
3187             llvm::LLVMGetUndef(T_ptr(T_nil()))
3188         } else {
3189             let {bcx: cx, val} = alloc_ty(bcx, full_retty);
3190             bcx = cx;
3191             val
3192         }
3193       }
3194       save_in(dst) { dst }
3195       by_val(_) {
3196           let {bcx: cx, val} = alloc_ty(bcx, full_retty);
3197           bcx = cx;
3198           val
3199       }
3200     };
3201
3202     if ty::type_contains_params(tcx, retty) {
3203         // It's possible that the callee has some generic-ness somewhere in
3204         // its return value -- say a method signature within an obj or a fn
3205         // type deep in a structure -- which the caller has a concrete view
3206         // of. If so, cast the caller's view of the restlot to the callee's
3207         // view, for the sake of making a type-compatible call.
3208         check non_ty_var(ccx, retty);
3209         let llretty = T_ptr(type_of_inner(ccx, bcx.sp, retty));
3210         llargs += [PointerCast(cx, llretslot, llretty)];
3211     } else { llargs += [llretslot]; }
3212
3213     // Arg 1: Env (closure-bindings / self-obj)
3214     llargs += [llenv];
3215
3216     // Args >2: ty_params ...
3217     llargs += lltydescs;
3218
3219     // ... then explicit args.
3220
3221     // First we figure out the caller's view of the types of the arguments.
3222     // This will be needed if this is a generic call, because the callee has
3223     // to cast her view of the arguments to the caller's view.
3224     let arg_tys = type_of_explicit_args(ccx, cx.sp, args);
3225     let i = 0u;
3226     for e: @ast::expr in es {
3227         let r = trans_arg_expr(bcx, args[i], arg_tys[i], to_zero, to_revoke,
3228                                e);
3229         bcx = r.bcx;
3230         llargs += [r.val];
3231         i += 1u;
3232     }
3233     ret {bcx: bcx,
3234          args: llargs,
3235          retslot: llretslot,
3236          to_zero: to_zero,
3237          to_revoke: to_revoke};
3238 }
3239
3240 fn trans_call(in_cx: @block_ctxt, f: @ast::expr,
3241               args: [@ast::expr], id: ast::node_id, dest: dest)
3242     -> @block_ctxt {
3243     // NB: 'f' isn't necessarily a function; it might be an entire self-call
3244     // expression because of the hack that allows us to process self-calls
3245     // with trans_call.
3246     let tcx = bcx_tcx(in_cx);
3247     let fn_expr_ty = ty::expr_ty(tcx, f);
3248
3249     let cx = new_scope_block_ctxt(in_cx, "call");
3250     Br(in_cx, cx.llbb);
3251     let f_res = trans_callee(cx, f);
3252     let bcx = f_res.bcx;
3253
3254     let faddr = f_res.val;
3255     let llenv, dict_param = none;
3256     alt f_res.env {
3257       null_env. {
3258         llenv = llvm::LLVMGetUndef(T_opaque_cbox_ptr(bcx_ccx(cx)));
3259       }
3260       obj_env(e) { llenv = e; }
3261       dict_env(dict, e) { llenv = e; dict_param = some(dict); }
3262       is_closure. {
3263         // It's a closure. Have to fetch the elements
3264         if f_res.kind == owned {
3265             faddr = load_if_immediate(bcx, faddr, fn_expr_ty);
3266         }
3267         let pair = faddr;
3268         faddr = GEPi(bcx, pair, [0, abi::fn_field_code]);
3269         faddr = Load(bcx, faddr);
3270         let llclosure = GEPi(bcx, pair, [0, abi::fn_field_box]);
3271         llenv = Load(bcx, llclosure);
3272       }
3273     }
3274
3275     let ret_ty = ty::node_id_to_type(tcx, id);
3276     let args_res =
3277         trans_args(bcx, llenv, f_res.generic, args, fn_expr_ty, dest);
3278     bcx = args_res.bcx;
3279     let llargs = args_res.args;
3280     option::may(dict_param) {|dict| llargs = [dict] + llargs}
3281     let llretslot = args_res.retslot;
3282
3283     /* If the block is terminated,
3284        then one or more of the args has
3285        type _|_. Since that means it diverges, the code
3286        for the call itself is unreachable. */
3287     bcx = invoke_full(bcx, faddr, llargs, args_res.to_zero,
3288                       args_res.to_revoke);
3289     alt dest {
3290       ignore. {
3291         if llvm::LLVMIsUndef(llretslot) != lib::llvm::True {
3292             bcx = drop_ty(bcx, llretslot, ret_ty);
3293         }
3294       }
3295       save_in(_) { } // Already saved by callee
3296       by_val(cell) {
3297         *cell = Load(bcx, llretslot);
3298       }
3299     }
3300     // Forget about anything we moved out.
3301     bcx = zero_and_revoke(bcx, args_res.to_zero, args_res.to_revoke);
3302
3303     bcx = trans_block_cleanups(bcx, cx);
3304     let next_cx = new_sub_block_ctxt(in_cx, "next");
3305     if bcx.unreachable || ty::type_is_bot(tcx, ret_ty) {
3306         Unreachable(next_cx);
3307     }
3308     Br(bcx, next_cx.llbb);
3309     ret next_cx;
3310 }
3311
3312 fn zero_and_revoke(bcx: @block_ctxt,
3313                    to_zero: [{v: ValueRef, t: ty::t}],
3314                    to_revoke: [{v: ValueRef, t: ty::t}]) -> @block_ctxt {
3315     let bcx = bcx;
3316     for {v, t} in to_zero {
3317         bcx = zero_alloca(bcx, v, t);
3318     }
3319     for {v, _} in to_revoke { revoke_clean(bcx, v); }
3320     ret bcx;
3321 }
3322
3323 fn invoke(bcx: @block_ctxt, llfn: ValueRef,
3324           llargs: [ValueRef]) -> @block_ctxt {
3325     ret invoke_(bcx, llfn, llargs, [], [], Invoke);
3326 }
3327
3328 fn invoke_full(bcx: @block_ctxt, llfn: ValueRef, llargs: [ValueRef],
3329                to_zero: [{v: ValueRef, t: ty::t}],
3330                to_revoke: [{v: ValueRef, t: ty::t}]) -> @block_ctxt {
3331     ret invoke_(bcx, llfn, llargs, to_zero, to_revoke, Invoke);
3332 }
3333
3334 fn invoke_(bcx: @block_ctxt, llfn: ValueRef, llargs: [ValueRef],
3335            to_zero: [{v: ValueRef, t: ty::t}],
3336            to_revoke: [{v: ValueRef, t: ty::t}],
3337            invoker: fn(@block_ctxt, ValueRef, [ValueRef],
3338                        BasicBlockRef, BasicBlockRef)) -> @block_ctxt {
3339     // FIXME: May be worth turning this into a plain call when there are no
3340     // cleanups to run
3341     if bcx.unreachable { ret bcx; }
3342     let normal_bcx = new_sub_block_ctxt(bcx, "normal return");
3343     invoker(bcx, llfn, llargs, normal_bcx.llbb,
3344             get_landing_pad(bcx, to_zero, to_revoke));
3345     ret normal_bcx;
3346 }
3347
3348 fn get_landing_pad(bcx: @block_ctxt,
3349                    to_zero: [{v: ValueRef, t: ty::t}],
3350                    to_revoke: [{v: ValueRef, t: ty::t}]
3351                   ) -> BasicBlockRef {
3352     let have_zero_or_revoke = vec::is_not_empty(to_zero)
3353         || vec::is_not_empty(to_revoke);
3354     let scope_bcx = find_scope_for_lpad(bcx, have_zero_or_revoke);
3355     if scope_bcx.lpad_dirty || have_zero_or_revoke {
3356         let unwind_bcx = new_sub_block_ctxt(bcx, "unwind");
3357         trans_landing_pad(unwind_bcx, to_zero, to_revoke);
3358         scope_bcx.lpad = some(unwind_bcx.llbb);
3359         scope_bcx.lpad_dirty = have_zero_or_revoke;
3360     }
3361     assert option::is_some(scope_bcx.lpad);
3362     ret option::get(scope_bcx.lpad);
3363
3364     fn find_scope_for_lpad(bcx: @block_ctxt,
3365                            have_zero_or_revoke: bool) -> @block_ctxt {
3366         let scope_bcx = bcx;
3367         while true {
3368             scope_bcx = find_scope_cx(scope_bcx);
3369             if vec::is_not_empty(scope_bcx.cleanups)
3370                 || have_zero_or_revoke {
3371                 ret scope_bcx;
3372             } else {
3373                 scope_bcx = alt scope_bcx.parent {
3374                   parent_some(b) { b }
3375                   parent_none. {
3376                     ret scope_bcx;
3377                   }
3378                 };
3379             }
3380         }
3381         fail;
3382     }
3383 }
3384
3385 fn trans_landing_pad(bcx: @block_ctxt,
3386                      to_zero: [{v: ValueRef, t: ty::t}],
3387                      to_revoke: [{v: ValueRef, t: ty::t}]) -> BasicBlockRef {
3388     // The landing pad return type (the type being propagated). Not sure what
3389     // this represents but it's determined by the personality function and
3390     // this is what the EH proposal example uses.
3391     let llretty = T_struct([T_ptr(T_i8()), T_i32()]);
3392     // The exception handling personality function. This is the C++
3393     // personality function __gxx_personality_v0, wrapped in our naming
3394     // convention.
3395     let personality = bcx_ccx(bcx).upcalls.rust_personality;
3396     // The only landing pad clause will be 'cleanup'
3397     let clauses = 1u;
3398     let llpad = LandingPad(bcx, llretty, personality, clauses);
3399     // The landing pad result is used both for modifying the landing pad
3400     // in the C API and as the exception value
3401     let llretval = llpad;
3402     // The landing pad block is a cleanup
3403     SetCleanup(bcx, llpad);
3404
3405     // Because we may have unwound across a stack boundary, we must call into
3406     // the runtime to figure out which stack segment we are on and place the
3407     // stack limit back into the TLS.
3408     Call(bcx, bcx_ccx(bcx).upcalls.reset_stack_limit, []);
3409
3410     // FIXME: This seems like a very naive and redundant way to generate the
3411     // landing pads, as we're re-generating all in-scope cleanups for each
3412     // function call. Probably good optimization opportunities here.
3413     let bcx = zero_and_revoke(bcx, to_zero, to_revoke);
3414     let scope_cx = bcx;
3415     while true {
3416         scope_cx = find_scope_cx(scope_cx);
3417         bcx = trans_block_cleanups(bcx, scope_cx);
3418         scope_cx = alt scope_cx.parent {
3419           parent_some(b) { b }
3420           parent_none. { break; }
3421         };
3422     }
3423
3424     // Continue unwinding
3425     Resume(bcx, llretval);
3426     ret bcx.llbb;
3427 }
3428
3429 fn trans_tup(bcx: @block_ctxt, elts: [@ast::expr], id: ast::node_id,
3430              dest: dest) -> @block_ctxt {
3431     let t = node_id_type(bcx.fcx.lcx.ccx, id);
3432     let bcx = bcx;
3433     let addr = alt dest {
3434       ignore. {
3435         for ex in elts { bcx = trans_expr(bcx, ex, ignore); }
3436         ret bcx;
3437       }
3438       save_in(pos) { pos }
3439     };
3440     let temp_cleanups = [], i = 0;
3441     for e in elts {
3442         let dst = GEP_tup_like_1(bcx, t, addr, [0, i]);
3443         let e_ty = ty::expr_ty(bcx_tcx(bcx), e);
3444         bcx = trans_expr_save_in(dst.bcx, e, dst.val);
3445         add_clean_temp_mem(bcx, dst.val, e_ty);
3446         temp_cleanups += [dst.val];
3447         i += 1;
3448     }
3449     for cleanup in temp_cleanups { revoke_clean(bcx, cleanup); }
3450     ret bcx;
3451 }
3452
3453 fn trans_rec(bcx: @block_ctxt, fields: [ast::field],
3454              base: option::t<@ast::expr>, id: ast::node_id,
3455              dest: dest) -> @block_ctxt {
3456     let t = node_id_type(bcx_ccx(bcx), id);
3457     let bcx = bcx;
3458     let addr = alt dest {
3459       ignore. {
3460         for fld in fields {
3461             bcx = trans_expr(bcx, fld.node.expr, ignore);
3462         }
3463         ret bcx;
3464       }
3465       save_in(pos) { pos }
3466     };
3467
3468     let ty_fields = alt ty::struct(bcx_tcx(bcx), t) { ty::ty_rec(f) { f } };
3469     let temp_cleanups = [];
3470     for fld in fields {
3471         let ix = option::get(vec::position_pred(ty_fields, {|ft|
3472             str::eq(fld.node.ident, ft.ident)
3473         }));
3474         let dst = GEP_tup_like_1(bcx, t, addr, [0, ix as int]);
3475         bcx = trans_expr_save_in(dst.bcx, fld.node.expr, dst.val);
3476         add_clean_temp_mem(bcx, dst.val, ty_fields[ix].mt.ty);
3477         temp_cleanups += [dst.val];
3478     }
3479     alt base {
3480       some(bexp) {
3481         let {bcx: cx, val: base_val} = trans_temp_expr(bcx, bexp), i = 0;
3482         bcx = cx;
3483         // Copy over inherited fields
3484         for tf in ty_fields {
3485             if !vec::any(fields, {|f| str::eq(f.node.ident, tf.ident)}) {
3486                 let dst = GEP_tup_like_1(bcx, t, addr, [0, i]);
3487                 let base = GEP_tup_like_1(bcx, t, base_val, [0, i]);
3488                 let val = load_if_immediate(base.bcx, base.val, tf.mt.ty);
3489                 bcx = copy_val(base.bcx, INIT, dst.val, val, tf.mt.ty);
3490             }
3491             i += 1;
3492         }
3493       }
3494       none. {}
3495     };
3496
3497     // Now revoke the cleanups as we pass responsibility for the data
3498     // structure on to the caller
3499     for cleanup in temp_cleanups { revoke_clean(bcx, cleanup); }
3500     ret bcx;
3501 }
3502
3503 // Store the result of an expression in the given memory location, ensuring
3504 // that nil or bot expressions get ignore rather than save_in as destination.
3505 fn trans_expr_save_in(bcx: @block_ctxt, e: @ast::expr, dest: ValueRef)
3506     -> @block_ctxt {
3507     let tcx = bcx_tcx(bcx), t = ty::expr_ty(tcx, e);
3508     let do_ignore = ty::type_is_bot(tcx, t) || ty::type_is_nil(tcx, t);
3509     ret trans_expr(bcx, e, do_ignore ? ignore : save_in(dest));
3510 }
3511
3512 // Call this to compile an expression that you need as an intermediate value,
3513 // and you want to know whether you're dealing with an lval or not (the kind
3514 // field in the returned struct). For non-intermediates, use trans_expr or
3515 // trans_expr_save_in. For intermediates where you don't care about lval-ness,
3516 // use trans_temp_expr.
3517 fn trans_temp_lval(bcx: @block_ctxt, e: @ast::expr) -> lval_result {
3518     let bcx = bcx;
3519     if expr_is_lval(bcx, e) {
3520         ret trans_lval(bcx, e);
3521     } else {
3522         let tcx = bcx_tcx(bcx);
3523         let ty = ty::expr_ty(tcx, e);
3524         if ty::type_is_nil(tcx, ty) || ty::type_is_bot(tcx, ty) {
3525             bcx = trans_expr(bcx, e, ignore);
3526             ret {bcx: bcx, val: C_nil(), kind: temporary};
3527         } else if ty::type_is_immediate(bcx_tcx(bcx), ty) {
3528             let cell = empty_dest_cell();
3529             bcx = trans_expr(bcx, e, by_val(cell));
3530             add_clean_temp(bcx, *cell, ty);
3531             ret {bcx: bcx, val: *cell, kind: temporary};
3532         } else {
3533             let {bcx, val: scratch} = alloc_ty(bcx, ty);
3534             bcx = trans_expr_save_in(bcx, e, scratch);
3535             add_clean_temp(bcx, scratch, ty);
3536             ret {bcx: bcx, val: scratch, kind: temporary};
3537         }
3538     }
3539 }
3540
3541 // Use only for intermediate values. See trans_expr and trans_expr_save_in for
3542 // expressions that must 'end up somewhere' (or get ignored).
3543 fn trans_temp_expr(bcx: @block_ctxt, e: @ast::expr) -> result {
3544     let {bcx, val, kind} = trans_temp_lval(bcx, e);
3545     if kind == owned {
3546         val = load_if_immediate(bcx, val, ty::expr_ty(bcx_tcx(bcx), e));
3547     }
3548     ret {bcx: bcx, val: val};
3549 }
3550
3551 // Translate an expression, with the dest argument deciding what happens with
3552 // the result. Invariants:
3553 // - exprs returning nil or bot always get dest=ignore
3554 // - exprs with non-immediate type never get dest=by_val
3555 fn trans_expr(bcx: @block_ctxt, e: @ast::expr, dest: dest) -> @block_ctxt {
3556     let tcx = bcx_tcx(bcx);
3557     debuginfo::update_source_pos(bcx, e.span);
3558
3559     if expr_is_lval(bcx, e) {
3560         ret lval_to_dps(bcx, e, dest);
3561     }
3562
3563     alt e.node {
3564       ast::expr_if(cond, thn, els) | ast::expr_if_check(cond, thn, els) {
3565         ret trans_if(bcx, cond, thn, els, dest);
3566       }
3567       ast::expr_ternary(_, _, _) {
3568         ret trans_expr(bcx, ast_util::ternary_to_if(e), dest);
3569       }
3570       ast::expr_alt(expr, arms) {
3571         ret trans_alt::trans_alt(bcx, expr, arms, dest);
3572       }
3573       ast::expr_block(blk) {
3574         let sub_cx = new_scope_block_ctxt(bcx, "block-expr body");
3575         Br(bcx, sub_cx.llbb);
3576         sub_cx = trans_block_dps(sub_cx, blk, dest);
3577         let next_cx = new_sub_block_ctxt(bcx, "next");
3578         Br(sub_cx, next_cx.llbb);
3579         if sub_cx.unreachable { Unreachable(next_cx); }
3580         ret next_cx;
3581       }
3582       ast::expr_rec(args, base) {
3583         ret trans_rec(bcx, args, base, e.id, dest);
3584       }
3585       ast::expr_tup(args) { ret trans_tup(bcx, args, e.id, dest); }
3586       ast::expr_lit(lit) { ret trans_lit(bcx, *lit, dest); }
3587       ast::expr_vec(args, _) { ret tvec::trans_vec(bcx, args, e.id, dest); }
3588       ast::expr_binary(op, x, y) { ret trans_binary(bcx, op, x, y, dest); }
3589       ast::expr_unary(op, x) {
3590         assert op != ast::deref; // lvals are handled above
3591         ret trans_unary(bcx, op, x, e.id, dest);
3592       }
3593       ast::expr_fn(proto, decl, body, cap_clause) {
3594         ret trans_closure::trans_expr_fn(
3595             bcx, proto, decl, body, e.span, e.id, *cap_clause, dest);
3596       }
3597       ast::expr_fn_block(decl, body) {
3598         alt ty::struct(tcx, ty::expr_ty(tcx, e)) {
3599           ty::ty_fn({proto, _}) {
3600             #debug("translating fn_block %s with type %s",
3601                    expr_to_str(e), ty_to_str(tcx, ty::expr_ty(tcx, e)));
3602             let cap_clause = { copies: [], moves: [] };
3603             ret trans_closure::trans_expr_fn(
3604                 bcx, proto, decl, body, e.span, e.id, cap_clause, dest);
3605           }
3606           _ {
3607             fail "Type of fn block is not a function!";
3608           }
3609         }
3610       }
3611       ast::expr_bind(f, args) {
3612         ret trans_closure::trans_bind(
3613             bcx, f, args, e.id, dest);
3614       }
3615       ast::expr_copy(a) {
3616         if !expr_is_lval(bcx, a) {
3617             ret trans_expr(bcx, a, dest);
3618         }
3619         else { ret lval_to_dps(bcx, a, dest); }
3620       }
3621       ast::expr_cast(val, _) { ret trans_cast(bcx, val, e.id, dest); }
3622       ast::expr_anon_obj(anon_obj) {
3623         ret trans_anon_obj(bcx, e.span, anon_obj, e.id, dest);
3624       }
3625       ast::expr_call(f, args, _) {
3626         ret trans_call(bcx, f, args, e.id, dest);
3627       }
3628       ast::expr_field(_, _, _) {
3629         fail "Taking the value of a method does not work yet (issue #435)";
3630       }
3631
3632       // These return nothing
3633       ast::expr_break. {
3634         assert dest == ignore;
3635         ret trans_break(e.span, bcx);
3636       }
3637       ast::expr_cont. {
3638         assert dest == ignore;
3639         ret trans_cont(e.span, bcx);
3640       }
3641       ast::expr_ret(ex) {
3642         assert dest == ignore;
3643         ret trans_ret(bcx, ex);
3644       }
3645       ast::expr_be(ex) {
3646         // Ideally, the expr_be tag would have a precondition
3647         // that is_call_expr(ex) -- but we don't support that
3648         // yet
3649         // FIXME
3650         check (ast_util::is_call_expr(ex));
3651         ret trans_be(bcx, ex);
3652       }
3653       ast::expr_fail(expr) {
3654         assert dest == ignore;
3655         ret trans_fail_expr(bcx, some(e.span), expr);
3656       }
3657       ast::expr_log(_, lvl, a) {
3658         assert dest == ignore;
3659         ret trans_log(lvl, bcx, a);
3660       }
3661       ast::expr_assert(a) {
3662         assert dest == ignore;
3663         ret trans_check_expr(bcx, a, "Assertion");
3664       }
3665       ast::expr_check(ast::checked_expr., a) {
3666         assert dest == ignore;
3667         ret trans_check_expr(bcx, a, "Predicate");
3668       }
3669       ast::expr_check(ast::claimed_expr., a) {
3670         assert dest == ignore;
3671         /* Claims are turned on and off by a global variable
3672            that the RTS sets. This case generates code to
3673            check the value of that variable, doing nothing
3674            if it's set to false and acting like a check
3675            otherwise. */
3676         let c =
3677             get_extern_const(bcx_ccx(bcx).externs, bcx_ccx(bcx).llmod,
3678                              "check_claims", T_bool());
3679         let cond = Load(bcx, c);
3680
3681         let then_cx = new_scope_block_ctxt(bcx, "claim_then");
3682         let check_cx = trans_check_expr(then_cx, a, "Claim");
3683         let next_cx = new_sub_block_ctxt(bcx, "join");
3684
3685         CondBr(bcx, cond, then_cx.llbb, next_cx.llbb);
3686         Br(check_cx, next_cx.llbb);
3687         ret next_cx;
3688       }
3689       ast::expr_for(decl, seq, body) {
3690         assert dest == ignore;
3691         ret trans_for(bcx, decl, seq, body);
3692       }
3693       ast::expr_while(cond, body) {
3694         assert dest == ignore;
3695         ret trans_while(bcx, cond, body);
3696       }
3697       ast::expr_do_while(body, cond) {
3698         assert dest == ignore;
3699         ret trans_do_while(bcx, body, cond);
3700       }
3701       ast::expr_assign(dst, src) {
3702         assert dest == ignore;
3703         let src_r = trans_temp_lval(bcx, src);
3704         let {bcx, val: addr, kind} = trans_lval(src_r.bcx, dst);
3705         assert kind == owned;
3706         ret store_temp_expr(bcx, DROP_EXISTING, addr, src_r,
3707                             ty::expr_ty(bcx_tcx(bcx), src),
3708                             bcx_ccx(bcx).last_uses.contains_key(src.id));
3709       }
3710       ast::expr_move(dst, src) {
3711         // FIXME: calculate copy init-ness in typestate.
3712         assert dest == ignore;
3713         let src_r = trans_temp_lval(bcx, src);
3714         let {bcx, val: addr, kind} = trans_lval(src_r.bcx, dst);
3715         assert kind == owned;
3716         ret move_val(bcx, DROP_EXISTING, addr, src_r,
3717                      ty::expr_ty(bcx_tcx(bcx), src));
3718       }
3719       ast::expr_swap(dst, src) {
3720         assert dest == ignore;
3721         let lhs_res = trans_lval(bcx, dst);
3722         assert lhs_res.kind == owned;
3723         let rhs_res = trans_lval(lhs_res.bcx, src);
3724         let t = ty::expr_ty(tcx, src);
3725         let {bcx: bcx, val: tmp_alloc} = alloc_ty(rhs_res.bcx, t);
3726         // Swap through a temporary.
3727         bcx = move_val(bcx, INIT, tmp_alloc, lhs_res, t);
3728         bcx = move_val(bcx, INIT, lhs_res.val, rhs_res, t);
3729         ret move_val(bcx, INIT, rhs_res.val, lval_owned(bcx, tmp_alloc), t);
3730       }
3731       ast::expr_assign_op(op, dst, src) {
3732         assert dest == ignore;
3733         ret trans_assign_op(bcx, op, dst, src);
3734       }
3735     }
3736 }
3737
3738 fn lval_to_dps(bcx: @block_ctxt, e: @ast::expr, dest: dest) -> @block_ctxt {
3739     let lv = trans_lval(bcx, e), ccx = bcx_ccx(bcx);
3740     let {bcx, val, kind} = lv;
3741     let last_use = kind == owned && ccx.last_uses.contains_key(e.id);
3742     let ty = ty::expr_ty(ccx.tcx, e);
3743     alt dest {
3744       by_val(cell) {
3745         if kind == temporary {
3746             revoke_clean(bcx, val);
3747             *cell = val;
3748         } else if last_use {
3749             *cell = Load(bcx, val);
3750             if ty::type_needs_drop(ccx.tcx, ty) {
3751                 bcx = zero_alloca(bcx, val, ty);
3752             }
3753         } else {
3754             if kind == owned { val = Load(bcx, val); }
3755             let {bcx: cx, val} = take_ty_immediate(bcx, val, ty);
3756             *cell = val;
3757             bcx = cx;
3758         }
3759       }
3760       save_in(loc) {
3761         bcx = store_temp_expr(bcx, INIT, loc, lv, ty, last_use);
3762       }
3763       ignore. {}
3764     }
3765     ret bcx;
3766 }
3767
3768 fn do_spill(cx: @block_ctxt, v: ValueRef, t: ty::t) -> result {
3769     // We have a value but we have to spill it, and root it, to pass by alias.
3770     let bcx = cx;
3771
3772     if ty::type_is_bot(bcx_tcx(bcx), t) {
3773         ret rslt(bcx, C_null(T_ptr(T_i8())));
3774     }
3775
3776     let r = alloc_ty(bcx, t);
3777     bcx = r.bcx;
3778     let llptr = r.val;
3779
3780     Store(bcx, v, llptr);
3781
3782     ret rslt(bcx, llptr);
3783 }
3784
3785 // Since this function does *not* root, it is the caller's responsibility to
3786 // ensure that the referent is pointed to by a root.
3787 fn do_spill_noroot(cx: @block_ctxt, v: ValueRef) -> ValueRef {
3788     let llptr = alloca(cx, val_ty(v));
3789     Store(cx, v, llptr);
3790     ret llptr;
3791 }
3792
3793 fn spill_if_immediate(cx: @block_ctxt, v: ValueRef, t: ty::t) -> result {
3794     if ty::type_is_immediate(bcx_tcx(cx), t) { ret do_spill(cx, v, t); }
3795     ret rslt(cx, v);
3796 }
3797
3798 fn load_if_immediate(cx: @block_ctxt, v: ValueRef, t: ty::t) -> ValueRef {
3799     if ty::type_is_immediate(bcx_tcx(cx), t) { ret Load(cx, v); }
3800     ret v;
3801 }
3802
3803 fn trans_log(lvl: @ast::expr, cx: @block_ctxt, e: @ast::expr) -> @block_ctxt {
3804     let ccx = bcx_ccx(cx);
3805     let lcx = cx.fcx.lcx;
3806     let modname = str::connect(lcx.module_path, "::");
3807     let global = if lcx.ccx.module_data.contains_key(modname) {
3808         lcx.ccx.module_data.get(modname)
3809     } else {
3810         let s = link::mangle_internal_name_by_path_and_seq(
3811             lcx.ccx, lcx.module_path, "loglevel");
3812         let global = str::as_buf(s, {|buf|
3813             llvm::LLVMAddGlobal(lcx.ccx.llmod, T_i32(), buf)
3814         });
3815         llvm::LLVMSetGlobalConstant(global, False);
3816         llvm::LLVMSetInitializer(global, C_null(T_i32()));
3817         llvm::LLVMSetLinkage(global,
3818                              lib::llvm::LLVMInternalLinkage as llvm::Linkage);
3819         lcx.ccx.module_data.insert(modname, global);
3820         global
3821     };
3822     let level_cx = new_scope_block_ctxt(cx, "level");
3823     let log_cx = new_scope_block_ctxt(cx, "log");
3824     let after_cx = new_sub_block_ctxt(cx, "after");
3825     let load = Load(cx, global);
3826
3827     Br(cx, level_cx.llbb);
3828     let level_res = trans_temp_expr(level_cx, lvl);
3829     let test = ICmp(level_res.bcx, lib::llvm::LLVMIntUGE,
3830                     load, level_res.val);
3831
3832     CondBr(level_res.bcx, test, log_cx.llbb, after_cx.llbb);
3833     let sub = trans_temp_expr(log_cx, e);
3834     let e_ty = ty::expr_ty(bcx_tcx(cx), e);
3835     let log_bcx = sub.bcx;
3836
3837     let ti = none::<@tydesc_info>;
3838     let r = get_tydesc(log_bcx, e_ty, false, tps_normal, ti).result;
3839     log_bcx = r.bcx;
3840     let lltydesc = r.val;
3841
3842     // Call the polymorphic log function.
3843     r = spill_if_immediate(log_bcx, sub.val, e_ty);
3844     log_bcx = r.bcx;
3845     let llvalptr = r.val;
3846     let llval_i8 = PointerCast(log_bcx, llvalptr, T_ptr(T_i8()));
3847
3848     Call(log_bcx, ccx.upcalls.log_type,
3849          [lltydesc, llval_i8, level_res.val]);
3850
3851     log_bcx = trans_block_cleanups(log_bcx, log_cx);
3852     Br(log_bcx, after_cx.llbb);
3853     ret trans_block_cleanups(after_cx, level_cx);
3854 }
3855
3856 fn trans_check_expr(cx: @block_ctxt, e: @ast::expr, s: str) -> @block_ctxt {
3857     let cond_res = trans_temp_expr(cx, e);
3858     let expr_str = s + " " + expr_to_str(e) + " failed";
3859     let fail_cx = new_sub_block_ctxt(cx, "fail");
3860     trans_fail(fail_cx, some::<span>(e.span), expr_str);
3861     let next_cx = new_sub_block_ctxt(cx, "next");
3862     CondBr(cond_res.bcx, cond_res.val, next_cx.llbb, fail_cx.llbb);
3863     ret next_cx;
3864 }
3865
3866 fn trans_fail_expr(bcx: @block_ctxt, sp_opt: option::t<span>,
3867                    fail_expr: option::t<@ast::expr>) -> @block_ctxt {
3868     let bcx = bcx;
3869     alt fail_expr {
3870       some(expr) {
3871         let tcx = bcx_tcx(bcx);
3872         let expr_res = trans_temp_expr(bcx, expr);
3873         let e_ty = ty::expr_ty(tcx, expr);
3874         bcx = expr_res.bcx;
3875
3876         if ty::type_is_str(tcx, e_ty) {
3877             let data = tvec::get_dataptr(
3878                 bcx, expr_res.val, type_of_or_i8(
3879                     bcx, ty::mk_mach_uint(tcx, ast::ty_u8)));
3880             ret trans_fail_value(bcx, sp_opt, data);
3881         } else if bcx.unreachable {
3882             ret bcx;
3883         } else {
3884             bcx_ccx(bcx).sess.span_bug(
3885                 expr.span, "fail called with unsupported type " +
3886                 ty_to_str(tcx, e_ty));
3887         }
3888       }
3889       _ { ret trans_fail(bcx, sp_opt, "explicit failure"); }
3890     }
3891 }
3892
3893 fn trans_fail(bcx: @block_ctxt, sp_opt: option::t<span>, fail_str: str) ->
3894     @block_ctxt {
3895     let V_fail_str = C_cstr(bcx_ccx(bcx), fail_str);
3896     ret trans_fail_value(bcx, sp_opt, V_fail_str);
3897 }
3898
3899 fn trans_fail_value(bcx: @block_ctxt, sp_opt: option::t<span>,
3900                     V_fail_str: ValueRef) -> @block_ctxt {
3901     let ccx = bcx_ccx(bcx);
3902     let V_filename;
3903     let V_line;
3904     alt sp_opt {
3905       some(sp) {
3906         let loc = bcx_ccx(bcx).sess.lookup_pos(sp.lo);
3907         V_filename = C_cstr(bcx_ccx(bcx), loc.filename);
3908         V_line = loc.line as int;
3909       }
3910       none. { V_filename = C_cstr(bcx_ccx(bcx), "<runtime>"); V_line = 0; }
3911     }
3912     let V_str = PointerCast(bcx, V_fail_str, T_ptr(T_i8()));
3913     V_filename = PointerCast(bcx, V_filename, T_ptr(T_i8()));
3914     let args = [V_str, V_filename, C_int(ccx, V_line)];
3915     let bcx = invoke(bcx, bcx_ccx(bcx).upcalls._fail, args);
3916     Unreachable(bcx);
3917     ret bcx;
3918 }
3919
3920 fn trans_break_cont(sp: span, bcx: @block_ctxt, to_end: bool)
3921     -> @block_ctxt {
3922     // Locate closest loop block, outputting cleanup as we go.
3923     let cleanup_cx = bcx, bcx = bcx;
3924     while true {
3925         bcx = trans_block_cleanups(bcx, cleanup_cx);
3926         alt copy cleanup_cx.kind {
3927           LOOP_SCOPE_BLOCK(_cont, _break) {
3928             if to_end {
3929                 Br(bcx, _break.llbb);
3930             } else {
3931                 alt _cont {
3932                   option::some(_cont) { Br(bcx, _cont.llbb); }
3933                   _ { Br(bcx, cleanup_cx.llbb); }
3934                 }
3935             }
3936             Unreachable(bcx);
3937             ret bcx;
3938           }
3939           _ {
3940             alt cleanup_cx.parent {
3941               parent_some(cx) { cleanup_cx = cx; }
3942               parent_none. {
3943                 bcx_ccx(bcx).sess.span_fatal
3944                     (sp, if to_end { "Break" } else { "Cont" } +
3945                      " outside a loop");
3946               }
3947             }
3948           }
3949         }
3950     }
3951     // If we get here without returning, it's a bug
3952     bcx_ccx(bcx).sess.bug("in trans::trans_break_cont()");
3953 }
3954
3955 fn trans_break(sp: span, cx: @block_ctxt) -> @block_ctxt {
3956     ret trans_break_cont(sp, cx, true);
3957 }
3958
3959 fn trans_cont(sp: span, cx: @block_ctxt) -> @block_ctxt {
3960     ret trans_break_cont(sp, cx, false);
3961 }
3962
3963 fn trans_ret(bcx: @block_ctxt, e: option::t<@ast::expr>) -> @block_ctxt {
3964     let cleanup_cx = bcx, bcx = bcx;
3965     alt e {
3966       some(x) { bcx = trans_expr_save_in(bcx, x, bcx.fcx.llretptr); }
3967       _ {}
3968     }
3969     // run all cleanups and back out.
3970
3971     let more_cleanups: bool = true;
3972     while more_cleanups {
3973         bcx = trans_block_cleanups(bcx, cleanup_cx);
3974         alt cleanup_cx.parent {
3975           parent_some(b) { cleanup_cx = b; }
3976           parent_none. { more_cleanups = false; }
3977         }
3978     }
3979     build_return(bcx);
3980     Unreachable(bcx);
3981     ret bcx;
3982 }
3983
3984 fn build_return(bcx: @block_ctxt) { Br(bcx, bcx_fcx(bcx).llreturn); }
3985
3986 // fn trans_be(cx: &@block_ctxt, e: &@ast::expr) -> result {
3987 fn trans_be(cx: @block_ctxt, e: @ast::expr) : ast_util::is_call_expr(e) ->
3988    @block_ctxt {
3989     // FIXME: Turn this into a real tail call once
3990     // calling convention issues are settled
3991     ret trans_ret(cx, some(e));
3992 }
3993
3994 fn init_local(bcx: @block_ctxt, local: @ast::local) -> @block_ctxt {
3995     let ty = node_id_type(bcx_ccx(bcx), local.node.id);
3996     let llptr = alt bcx.fcx.lllocals.find(local.node.id) {
3997       some(local_mem(v)) { v }
3998       // This is a local that is kept immediate
3999       none. {
4000         let initexpr = alt local.node.init { some({expr, _}) { expr } };
4001         let {bcx, val, kind} = trans_temp_lval(bcx, initexpr);
4002         if kind != temporary {
4003             if kind == owned { val = Load(bcx, val); }
4004             let rs = take_ty_immediate(bcx, val, ty);
4005             bcx = rs.bcx; val = rs.val;
4006             add_clean_temp(bcx, val, ty);
4007         }
4008         bcx.fcx.lllocals.insert(local.node.pat.id, local_imm(val));
4009         ret bcx;
4010       }
4011     };
4012
4013     let bcx = bcx;
4014     alt local.node.init {
4015       some(init) {
4016         if init.op == ast::init_assign || !expr_is_lval(bcx, init.expr) {
4017             bcx = trans_expr_save_in(bcx, init.expr, llptr);
4018         } else { // This is a move from an lval, must perform an actual move
4019             let sub = trans_lval(bcx, init.expr);
4020             bcx = move_val(sub.bcx, INIT, llptr, sub, ty);
4021         }
4022       }
4023       _ { bcx = zero_alloca(bcx, llptr, ty); }
4024     }
4025     // Make a note to drop this slot on the way out.
4026     add_clean(bcx, llptr, ty);
4027     ret trans_alt::bind_irrefutable_pat(bcx, local.node.pat, llptr, false);
4028 }
4029
4030 fn init_ref_local(bcx: @block_ctxt, local: @ast::local) -> @block_ctxt {
4031     let init_expr = option::get(local.node.init).expr;
4032     let {bcx, val, kind} = trans_lval(bcx, init_expr);
4033     alt kind {
4034       owned_imm. { val = do_spill_noroot(bcx, val); }
4035       owned. {}
4036     }
4037     ret trans_alt::bind_irrefutable_pat(bcx, local.node.pat, val, false);
4038 }
4039
4040 fn zero_alloca(cx: @block_ctxt, llptr: ValueRef, t: ty::t)
4041     -> @block_ctxt {
4042     let bcx = cx;
4043     let ccx = bcx_ccx(cx);
4044     if check type_has_static_size(ccx, t) {
4045         let sp = cx.sp;
4046         let llty = type_of(ccx, sp, t);
4047         Store(bcx, C_null(llty), llptr);
4048     } else {
4049         let llsz = size_of(bcx, t);
4050         // FIXME passing in the align here is correct, but causes issue #843
4051         // let llalign = align_of(llsz.bcx, t);
4052         bcx = call_bzero(llsz.bcx, llptr, llsz.val, C_int(ccx, 0)).bcx;
4053     }
4054     ret bcx;
4055 }
4056
4057 fn trans_stmt(cx: @block_ctxt, s: ast::stmt) -> @block_ctxt {
4058     // FIXME Fill in cx.sp
4059
4060     if (!bcx_ccx(cx).sess.get_opts().no_asm_comments) {
4061         add_span_comment(cx, s.span, stmt_to_str(s));
4062     }
4063
4064     let bcx = cx;
4065     debuginfo::update_source_pos(cx, s.span);
4066
4067     alt s.node {
4068       ast::stmt_expr(e, _) | ast::stmt_semi(e, _) {
4069         bcx = trans_expr(cx, e, ignore);
4070       }
4071       ast::stmt_decl(d, _) {
4072         alt d.node {
4073           ast::decl_local(locals) {
4074             for (style, local) in locals {
4075                 if style == ast::let_copy {
4076                     bcx = init_local(bcx, local);
4077                 } else {
4078                     bcx = init_ref_local(bcx, local);
4079                 }
4080                 if bcx_ccx(cx).sess.get_opts().extra_debuginfo {
4081                     debuginfo::create_local_var(bcx, local);
4082                 }
4083             }
4084           }
4085           ast::decl_item(i) { trans_item(cx.fcx.lcx, *i); }
4086         }
4087       }
4088       _ { bcx_ccx(cx).sess.unimpl("stmt variant"); }
4089     }
4090
4091     ret bcx;
4092 }
4093
4094 // You probably don't want to use this one. See the
4095 // next three functions instead.
4096 fn new_block_ctxt(cx: @fn_ctxt, parent: block_parent, kind: block_kind,
4097                   name: str) -> @block_ctxt {
4098     let s = "";
4099     if cx.lcx.ccx.sess.get_opts().save_temps ||
4100            cx.lcx.ccx.sess.get_opts().debuginfo {
4101         s = cx.lcx.ccx.names.next(name);
4102     }
4103     let llbb: BasicBlockRef =
4104         str::as_buf(s, {|buf| llvm::LLVMAppendBasicBlock(cx.llfn, buf) });
4105     let bcx = @{llbb: llbb,
4106                 mutable terminated: false,
4107                 mutable unreachable: false,
4108                 parent: parent,
4109                 kind: kind,
4110                 mutable cleanups: [],
4111                 mutable lpad_dirty: true,
4112                 mutable lpad: option::none,
4113                 sp: cx.sp,
4114                 fcx: cx};
4115     alt parent {
4116       parent_some(cx) {
4117         if cx.unreachable { Unreachable(bcx); }
4118       }
4119       _ {}
4120     }
4121     ret bcx;
4122 }
4123
4124
4125 // Use this when you're at the top block of a function or the like.
4126 fn new_top_block_ctxt(fcx: @fn_ctxt) -> @block_ctxt {
4127     ret new_block_ctxt(fcx, parent_none, SCOPE_BLOCK, "function top level");
4128 }
4129
4130
4131 // Use this when you're at a curly-brace or similar lexical scope.
4132 fn new_scope_block_ctxt(bcx: @block_ctxt, n: str) -> @block_ctxt {
4133     ret new_block_ctxt(bcx.fcx, parent_some(bcx), SCOPE_BLOCK, n);
4134 }
4135
4136 fn new_loop_scope_block_ctxt(bcx: @block_ctxt, _cont: option::t<@block_ctxt>,
4137                              _break: @block_ctxt, n: str) -> @block_ctxt {
4138     ret new_block_ctxt(bcx.fcx, parent_some(bcx),
4139                        LOOP_SCOPE_BLOCK(_cont, _break), n);
4140 }
4141
4142
4143 // Use this when you're making a general CFG BB within a scope.
4144 fn new_sub_block_ctxt(bcx: @block_ctxt, n: str) -> @block_ctxt {
4145     ret new_block_ctxt(bcx.fcx, parent_some(bcx), NON_SCOPE_BLOCK, n);
4146 }
4147
4148 fn new_raw_block_ctxt(fcx: @fn_ctxt, llbb: BasicBlockRef) -> @block_ctxt {
4149     ret @{llbb: llbb,
4150           mutable terminated: false,
4151           mutable unreachable: false,
4152           parent: parent_none,
4153           kind: NON_SCOPE_BLOCK,
4154           mutable cleanups: [],
4155           mutable lpad_dirty: true,
4156           mutable lpad: option::none,
4157           sp: fcx.sp,
4158           fcx: fcx};
4159 }
4160
4161
4162 // trans_block_cleanups: Go through all the cleanups attached to this
4163 // block_ctxt and execute them.
4164 //
4165 // When translating a block that introdces new variables during its scope, we
4166 // need to make sure those variables go out of scope when the block ends.  We
4167 // do that by running a 'cleanup' function for each variable.
4168 // trans_block_cleanups runs all the cleanup functions for the block.
4169 fn trans_block_cleanups(bcx: @block_ctxt, cleanup_cx: @block_ctxt) ->
4170    @block_ctxt {
4171     if bcx.unreachable { ret bcx; }
4172     if cleanup_cx.kind == NON_SCOPE_BLOCK {
4173         assert (vec::len::<cleanup>(cleanup_cx.cleanups) == 0u);
4174     }
4175     let i = vec::len::<cleanup>(cleanup_cx.cleanups), bcx = bcx;
4176     while i > 0u {
4177         i -= 1u;
4178         let c = cleanup_cx.cleanups[i];
4179         alt c {
4180           clean(cfn) { bcx = cfn(bcx); }
4181           clean_temp(_, cfn) { bcx = cfn(bcx); }
4182         }
4183     }
4184     ret bcx;
4185 }
4186
4187 fn trans_fn_cleanups(fcx: @fn_ctxt, cx: @block_ctxt) {
4188     alt fcx.llobstacktoken {
4189       some(lltoken_) {
4190         let lltoken = lltoken_; // satisfy alias checker
4191         Call(cx, fcx_ccx(fcx).upcalls.dynastack_free, [lltoken]);
4192       }
4193       none. {/* nothing to do */ }
4194     }
4195 }
4196
4197 fn block_locals(b: ast::blk, it: block(@ast::local)) {
4198     for s: @ast::stmt in b.node.stmts {
4199         alt s.node {
4200           ast::stmt_decl(d, _) {
4201             alt d.node {
4202               ast::decl_local(locals) {
4203                 for (style, local) in locals {
4204                     if style == ast::let_copy { it(local); }
4205                 }
4206               }
4207               _ {/* fall through */ }
4208             }
4209           }
4210           _ {/* fall through */ }
4211         }
4212     }
4213 }
4214
4215 fn llstaticallocas_block_ctxt(fcx: @fn_ctxt) -> @block_ctxt {
4216     ret @{llbb: fcx.llstaticallocas,
4217           mutable terminated: false,
4218           mutable unreachable: false,
4219           parent: parent_none,
4220           kind: SCOPE_BLOCK,
4221           mutable cleanups: [],
4222           mutable lpad_dirty: true,
4223           mutable lpad: option::none,
4224           sp: fcx.sp,
4225           fcx: fcx};
4226 }
4227
4228 fn llderivedtydescs_block_ctxt(fcx: @fn_ctxt) -> @block_ctxt {
4229     ret @{llbb: fcx.llderivedtydescs,
4230           mutable terminated: false,
4231           mutable unreachable: false,
4232           parent: parent_none,
4233           kind: SCOPE_BLOCK,
4234           mutable cleanups: [],
4235           mutable lpad_dirty: true,
4236           mutable lpad: option::none,
4237           sp: fcx.sp,
4238           fcx: fcx};
4239 }
4240
4241
4242 fn alloc_ty(cx: @block_ctxt, t: ty::t) -> result {
4243     let bcx = cx;
4244     let ccx = bcx_ccx(cx);
4245     let val =
4246         if check type_has_static_size(ccx, t) {
4247             let sp = cx.sp;
4248             alloca(bcx, type_of(ccx, sp, t))
4249         } else {
4250             // NB: we have to run this particular 'size_of' in a
4251             // block_ctxt built on the llderivedtydescs block for the fn,
4252             // so that the size dominates the array_alloca that
4253             // comes next.
4254
4255             let n = size_of(llderivedtydescs_block_ctxt(bcx.fcx), t);
4256             bcx.fcx.llderivedtydescs = n.bcx.llbb;
4257             dynastack_alloca(bcx, T_i8(), n.val, t)
4258         };
4259
4260     // NB: since we've pushed all size calculations in this
4261     // function up to the alloca block, we actually return the
4262     // block passed into us unmodified; it doesn't really
4263     // have to be passed-and-returned here, but it fits
4264     // past caller conventions and may well make sense again,
4265     // so we leave it as-is.
4266
4267     if bcx_tcx(cx).sess.get_opts().do_gc {
4268         bcx = gc::add_gc_root(bcx, val, t);
4269     }
4270
4271     ret rslt(cx, val);
4272 }
4273
4274 fn alloc_local(cx: @block_ctxt, local: @ast::local) -> @block_ctxt {
4275     let t = node_id_type(bcx_ccx(cx), local.node.id);
4276     let is_simple = alt local.node.pat.node {
4277       ast::pat_bind(_, none.) { true } _ { false }
4278     };
4279     // Do not allocate space for locals that can be kept immediate.
4280     let ccx = bcx_ccx(cx);
4281     if is_simple && !ccx.mut_map.contains_key(local.node.pat.id) &&
4282        !ccx.last_uses.contains_key(local.node.pat.id) &&
4283        ty::type_is_immediate(ccx.tcx, t) {
4284         alt local.node.init {
4285           some({op: ast::init_assign., _}) { ret cx; }
4286           _ {}
4287         }
4288     }
4289     let r = alloc_ty(cx, t);
4290     alt local.node.pat.node {
4291       ast::pat_bind(ident, none.) {
4292         if bcx_ccx(cx).sess.get_opts().debuginfo {
4293             let _: () = str::as_buf(ident, {|buf|
4294                 llvm::LLVMSetValueName(r.val, buf)
4295             });
4296         }
4297       }
4298       _ { }
4299     }
4300     cx.fcx.lllocals.insert(local.node.id, local_mem(r.val));
4301     ret r.bcx;
4302 }
4303
4304 fn trans_block(bcx: @block_ctxt, b: ast::blk) -> @block_ctxt {
4305     trans_block_dps(bcx, b, ignore)
4306 }
4307
4308 fn trans_block_dps(bcx: @block_ctxt, b: ast::blk, dest: dest)
4309     -> @block_ctxt {
4310     let bcx = bcx;
4311     block_locals(b) {|local| bcx = alloc_local(bcx, local); };
4312     for s: @ast::stmt in b.node.stmts {
4313         debuginfo::update_source_pos(bcx, b.span);
4314         bcx = trans_stmt(bcx, *s);
4315     }
4316     alt b.node.expr {
4317       some(e) {
4318         let bt = ty::type_is_bot(bcx_tcx(bcx), ty::expr_ty(bcx_tcx(bcx), e));
4319         debuginfo::update_source_pos(bcx, e.span);
4320         bcx = trans_expr(bcx, e, bt ? ignore : dest);
4321       }
4322       _ { assert dest == ignore || bcx.unreachable; }
4323     }
4324     let rv = trans_block_cleanups(bcx, find_scope_cx(bcx));
4325     ret rv;
4326 }
4327
4328 fn new_local_ctxt(ccx: @crate_ctxt) -> @local_ctxt {
4329     let pth: [str] = [];
4330     ret @{path: pth,
4331           module_path: [ccx.link_meta.name],
4332           obj_typarams: [],
4333           obj_fields: [],
4334           ccx: ccx};
4335 }
4336
4337
4338 // Creates the standard quartet of basic blocks: static allocas, copy args,
4339 // derived tydescs, and dynamic allocas.
4340 fn mk_standard_basic_blocks(llfn: ValueRef) ->
4341    {sa: BasicBlockRef,
4342     ca: BasicBlockRef,
4343     dt: BasicBlockRef,
4344     da: BasicBlockRef,
4345     rt: BasicBlockRef} {
4346     ret {sa:
4347              str::as_buf("static_allocas",
4348                          {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4349          ca:
4350              str::as_buf("load_env",
4351                          {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4352          dt:
4353              str::as_buf("derived_tydescs",
4354                          {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4355          da:
4356              str::as_buf("dynamic_allocas",
4357                          {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4358          rt:
4359              str::as_buf("return",
4360                          {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) })};
4361 }
4362
4363
4364 // NB: must keep 4 fns in sync:
4365 //
4366 //  - type_of_fn
4367 //  - create_llargs_for_fn_args.
4368 //  - new_fn_ctxt
4369 //  - trans_args
4370 fn new_fn_ctxt_w_id(cx: @local_ctxt, sp: span, llfndecl: ValueRef,
4371                     id: ast::node_id, rstyle: ast::ret_style)
4372     -> @fn_ctxt {
4373     let llbbs = mk_standard_basic_blocks(llfndecl);
4374     ret @{llfn: llfndecl,
4375           llenv: llvm::LLVMGetParam(llfndecl, 1u),
4376           llretptr: llvm::LLVMGetParam(llfndecl, 0u),
4377           mutable llstaticallocas: llbbs.sa,
4378           mutable llloadenv: llbbs.ca,
4379           mutable llderivedtydescs_first: llbbs.dt,
4380           mutable llderivedtydescs: llbbs.dt,
4381           mutable lldynamicallocas: llbbs.da,
4382           mutable llreturn: llbbs.rt,
4383           mutable llobstacktoken: none::<ValueRef>,
4384           mutable llself: none::<val_self_pair>,
4385           llargs: new_int_hash::<local_val>(),
4386           llobjfields: new_int_hash::<ValueRef>(),
4387           lllocals: new_int_hash::<local_val>(),
4388           llupvars: new_int_hash::<ValueRef>(),
4389           mutable lltyparams: [],
4390           derived_tydescs: ty::new_ty_hash(),
4391           id: id,
4392           ret_style: rstyle,
4393           sp: sp,
4394           lcx: cx};
4395 }
4396
4397 fn new_fn_ctxt(cx: @local_ctxt, sp: span, llfndecl: ValueRef) -> @fn_ctxt {
4398     ret new_fn_ctxt_w_id(cx, sp, llfndecl, -1, ast::return_val);
4399 }
4400
4401 // NB: must keep 4 fns in sync:
4402 //
4403 //  - type_of_fn
4404 //  - create_llargs_for_fn_args.
4405 //  - new_fn_ctxt
4406 //  - trans_args
4407
4408 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
4409 // allocas created for them.
4410 //
4411 // When we translate a function, we need to map its incoming arguments to the
4412 // spaces that have been created for them (by code in the llallocas field of
4413 // the function's fn_ctxt).  create_llargs_for_fn_args populates the llargs
4414 // field of the fn_ctxt with
4415 fn create_llargs_for_fn_args(cx: @fn_ctxt, ty_self: self_arg,
4416                              args: [ast::arg], ty_params: [ast::ty_param]) {
4417     // Skip the implicit arguments 0, and 1.  TODO: Pull out 2u and define
4418     // it as a constant, since we're using it in several places in trans this
4419     // way.
4420     let arg_n = 2u;
4421     alt ty_self {
4422       obj_self(tt) | impl_self(tt) {
4423         cx.llself = some({v: cx.llenv, t: tt});
4424       }
4425       no_self. {}
4426     }
4427     alt ty_self {
4428       obj_self(_) {}
4429       _ {
4430         for tp in ty_params {
4431             let lltydesc = llvm::LLVMGetParam(cx.llfn, arg_n), dicts = none;
4432             arg_n += 1u;
4433             for bound in *fcx_tcx(cx).ty_param_bounds.get(tp.id) {
4434                 alt bound {
4435                   ty::bound_iface(_) {
4436                     let dict = llvm::LLVMGetParam(cx.llfn, arg_n);
4437                     arg_n += 1u;
4438                     dicts = some(alt dicts {
4439                       none. { [dict] }
4440                       some(ds) { ds + [dict] }
4441                     });
4442                   }
4443                   _ {}
4444                 }
4445             }
4446             cx.lltyparams += [{desc: lltydesc, dicts: dicts}];
4447         }
4448       }
4449     }
4450
4451     // Populate the llargs field of the function context with the ValueRefs
4452     // that we get from llvm::LLVMGetParam for each argument.
4453     for arg: ast::arg in args {
4454         let llarg = llvm::LLVMGetParam(cx.llfn, arg_n);
4455         assert (llarg as int != 0);
4456         // Note that this uses local_mem even for things passed by value.
4457         // copy_args_to_allocas will overwrite the table entry with local_imm
4458         // before it's actually used.
4459         cx.llargs.insert(arg.id, local_mem(llarg));
4460         arg_n += 1u;
4461     }
4462 }
4463
4464 fn copy_args_to_allocas(fcx: @fn_ctxt, bcx: @block_ctxt, args: [ast::arg],
4465                         arg_tys: [ty::arg]) -> @block_ctxt {
4466     if fcx_ccx(fcx).sess.get_opts().extra_debuginfo {
4467         llvm::LLVMAddAttribute(llvm::LLVMGetFirstParam(fcx.llfn),
4468                                lib::llvm::LLVMStructRetAttribute as
4469                                    lib::llvm::llvm::Attribute);
4470     }
4471     let arg_n: uint = 0u, bcx = bcx;
4472     for arg in arg_tys {
4473         let id = args[arg_n].id;
4474         let argval = alt fcx.llargs.get(id) { local_mem(v) { v } };
4475         alt arg.mode {
4476           ast::by_mut_ref. { }
4477           ast::by_move. | ast::by_copy. { add_clean(bcx, argval, arg.ty); }
4478           ast::by_val. {
4479             if !ty::type_is_immediate(bcx_tcx(bcx), arg.ty) {
4480                 let {bcx: cx, val: alloc} = alloc_ty(bcx, arg.ty);
4481                 bcx = cx;
4482                 Store(bcx, argval, alloc);
4483                 fcx.llargs.insert(id, local_mem(alloc));
4484             } else {
4485                 fcx.llargs.insert(id, local_imm(argval));
4486             }
4487           }
4488           ast::by_ref. {}
4489         }
4490         if fcx_ccx(fcx).sess.get_opts().extra_debuginfo {
4491             debuginfo::create_arg(bcx, args[arg_n]);
4492         }
4493         arg_n += 1u;
4494     }
4495     ret bcx;
4496 }
4497
4498 fn arg_tys_of_fn(ccx: @crate_ctxt, id: ast::node_id) -> [ty::arg] {
4499     alt ty::struct(ccx.tcx, ty::node_id_to_type(ccx.tcx, id)) {
4500       ty::ty_fn({inputs, _}) { inputs }
4501     }
4502 }
4503
4504 fn populate_fn_ctxt_from_llself(fcx: @fn_ctxt, llself: val_self_pair) {
4505     let ccx = fcx_ccx(fcx);
4506     let bcx = llstaticallocas_block_ctxt(fcx);
4507     let field_tys: [ty::t] = [];
4508     for f: ast::obj_field in bcx.fcx.lcx.obj_fields {
4509         field_tys += [node_id_type(ccx, f.id)];
4510     }
4511     // Synthesize a tuple type for the fields so that GEP_tup_like() can work
4512     // its magic.
4513
4514     let fields_tup_ty = ty::mk_tup(fcx.lcx.ccx.tcx, field_tys);
4515     let n_typarams = vec::len::<ast::ty_param>(bcx.fcx.lcx.obj_typarams);
4516     let llobj_box_ty: TypeRef = T_obj_ptr(ccx, n_typarams);
4517     let box_cell = GEPi(bcx, llself.v, [0, abi::obj_field_box]);
4518     let box_ptr = Load(bcx, box_cell);
4519     box_ptr = PointerCast(bcx, box_ptr, llobj_box_ty);
4520     let obj_typarams =
4521         GEPi(bcx, box_ptr, [0, abi::box_rc_field_body,
4522                             abi::obj_body_elt_typarams]);
4523
4524     // The object fields immediately follow the type parameters, so we skip
4525     // over them to get the pointer.
4526     let obj_fields =
4527         PointerCast(bcx, GEPi(bcx, obj_typarams, [1]),
4528                     T_ptr(type_of_or_i8(bcx, fields_tup_ty)));
4529
4530     let i: int = 0;
4531     for p: ast::ty_param in fcx.lcx.obj_typarams {
4532         let lltyparam: ValueRef =
4533             GEPi(bcx, obj_typarams, [0, i]);
4534         lltyparam = Load(bcx, lltyparam);
4535         fcx.lltyparams += [{desc: lltyparam, dicts: none}];
4536         i += 1;
4537     }
4538     i = 0;
4539     for f: ast::obj_field in fcx.lcx.obj_fields {
4540         // FIXME: silly check
4541         check type_is_tup_like(bcx, fields_tup_ty);
4542         let rslt = GEP_tup_like(bcx, fields_tup_ty, obj_fields, [0, i]);
4543         bcx = llstaticallocas_block_ctxt(fcx);
4544         let llfield = rslt.val;
4545         fcx.llobjfields.insert(f.id, llfield);
4546         i += 1;
4547     }
4548     fcx.llstaticallocas = bcx.llbb;
4549 }
4550
4551
4552 // Ties up the llstaticallocas -> llloadenv -> llderivedtydescs ->
4553 // lldynamicallocas -> lltop edges, and builds the return block.
4554 fn finish_fn(fcx: @fn_ctxt, lltop: BasicBlockRef) {
4555     Br(new_raw_block_ctxt(fcx, fcx.llstaticallocas), fcx.llloadenv);
4556     Br(new_raw_block_ctxt(fcx, fcx.llloadenv), fcx.llderivedtydescs_first);
4557     Br(new_raw_block_ctxt(fcx, fcx.llderivedtydescs), fcx.lldynamicallocas);
4558     Br(new_raw_block_ctxt(fcx, fcx.lldynamicallocas), lltop);
4559
4560     let ret_cx = new_raw_block_ctxt(fcx, fcx.llreturn);
4561     trans_fn_cleanups(fcx, ret_cx);
4562     RetVoid(ret_cx);
4563 }
4564
4565 tag self_arg { obj_self(ty::t); impl_self(ty::t); no_self; }
4566
4567 // trans_closure: Builds an LLVM function out of a source function.
4568 // If the function closes over its environment a closure will be
4569 // returned.
4570 fn trans_closure(cx: @local_ctxt, sp: span, decl: ast::fn_decl,
4571                  body: ast::blk, llfndecl: ValueRef,
4572                  ty_self: self_arg, ty_params: [ast::ty_param],
4573                  id: ast::node_id, maybe_load_env: block(@fn_ctxt)) {
4574     set_uwtable(llfndecl);
4575
4576     // Set up arguments to the function.
4577     let fcx = new_fn_ctxt_w_id(cx, sp, llfndecl, id, decl.cf);
4578     create_llargs_for_fn_args(fcx, ty_self, decl.inputs, ty_params);
4579     alt ty_self {
4580       obj_self(_) {
4581           populate_fn_ctxt_from_llself(fcx, option::get(fcx.llself));
4582       }
4583       _ { }
4584     }
4585
4586     // Create the first basic block in the function and keep a handle on it to
4587     //  pass to finish_fn later.
4588     let bcx = new_top_block_ctxt(fcx);
4589     let lltop = bcx.llbb;
4590     let block_ty = node_id_type(cx.ccx, body.node.id);
4591
4592     let arg_tys = arg_tys_of_fn(fcx.lcx.ccx, id);
4593     bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, arg_tys);
4594
4595     maybe_load_env(fcx);
4596
4597     // This call to trans_block is the place where we bridge between
4598     // translation calls that don't have a return value (trans_crate,
4599     // trans_mod, trans_item, trans_obj, et cetera) and those that do
4600     // (trans_block, trans_expr, et cetera).
4601     if ty::type_is_bot(cx.ccx.tcx, block_ty) ||
4602        ty::type_is_nil(cx.ccx.tcx, block_ty) ||
4603        option::is_none(body.node.expr) {
4604         bcx = trans_block_dps(bcx, body, ignore);
4605     } else if ty::type_is_immediate(cx.ccx.tcx, block_ty) {
4606         let cell = empty_dest_cell();
4607         bcx = trans_block_dps(bcx, body, by_val(cell));
4608         Store(bcx, *cell, fcx.llretptr);
4609     } else {
4610         bcx = trans_block_dps(bcx, body, save_in(fcx.llretptr));
4611     }
4612
4613     // FIXME: until LLVM has a unit type, we are moving around
4614     // C_nil values rather than their void type.
4615     if !bcx.unreachable { build_return(bcx); }
4616     // Insert the mandatory first few basic blocks before lltop.
4617     finish_fn(fcx, lltop);
4618 }
4619
4620 // trans_fn: creates an LLVM function corresponding to a source language
4621 // function.
4622 fn trans_fn(cx: @local_ctxt, sp: span, decl: ast::fn_decl, body: ast::blk,
4623             llfndecl: ValueRef, ty_self: self_arg, ty_params: [ast::ty_param],
4624             id: ast::node_id) {
4625     let do_time = cx.ccx.sess.get_opts().stats;
4626     let start = do_time ? time::get_time() : {sec: 0u32, usec: 0u32};
4627     let fcx = option::none;
4628     trans_closure(cx, sp, decl, body, llfndecl, ty_self, ty_params, id,
4629                   {|new_fcx| fcx = option::some(new_fcx);});
4630     if cx.ccx.sess.get_opts().extra_debuginfo {
4631         debuginfo::create_function(option::get(fcx));
4632     }
4633     if do_time {
4634         let end = time::get_time();
4635         log_fn_time(cx.ccx, str::connect(cx.path, "::"), start, end);
4636     }
4637 }
4638
4639 fn trans_res_ctor(cx: @local_ctxt, sp: span, dtor: ast::fn_decl,
4640                   ctor_id: ast::node_id, ty_params: [ast::ty_param]) {
4641     let ccx = cx.ccx;
4642
4643     // Create a function for the constructor
4644     let llctor_decl;
4645     alt ccx.item_ids.find(ctor_id) {
4646       some(x) { llctor_decl = x; }
4647       _ { ccx.sess.span_fatal(sp, "unbound ctor_id in trans_res_ctor"); }
4648     }
4649     let fcx = new_fn_ctxt(cx, sp, llctor_decl);
4650     let ret_t = ty::ret_ty_of_fn(cx.ccx.tcx, ctor_id);
4651     create_llargs_for_fn_args(fcx, no_self, dtor.inputs, ty_params);
4652     let bcx = new_top_block_ctxt(fcx);
4653     let lltop = bcx.llbb;
4654     let arg_t = arg_tys_of_fn(ccx, ctor_id)[0].ty;
4655     let tup_t = ty::mk_tup(ccx.tcx, [ty::mk_int(ccx.tcx), arg_t]);
4656     let arg = alt fcx.llargs.find(dtor.inputs[0].id) {
4657       some(local_mem(x)) { x }
4658     };
4659     let llretptr = fcx.llretptr;
4660     if ty::type_has_dynamic_size(ccx.tcx, ret_t) {
4661         let llret_t = T_ptr(T_struct([ccx.int_type, llvm::LLVMTypeOf(arg)]));
4662         llretptr = BitCast(bcx, llretptr, llret_t);
4663     }
4664
4665     // FIXME: silly checks
4666     check type_is_tup_like(bcx, tup_t);
4667     let {bcx, val: dst} = GEP_tup_like(bcx, tup_t, llretptr, [0, 1]);
4668     bcx = memmove_ty(bcx, dst, arg, arg_t);
4669     check type_is_tup_like(bcx, tup_t);
4670     let flag = GEP_tup_like(bcx, tup_t, llretptr, [0, 0]);
4671     bcx = flag.bcx;
4672     // FIXME #1184: Resource flag is larger than necessary
4673     let one = C_int(ccx, 1);
4674     Store(bcx, one, flag.val);
4675     build_return(bcx);
4676     finish_fn(fcx, lltop);
4677 }
4678
4679
4680 fn trans_tag_variant(cx: @local_ctxt, tag_id: ast::node_id,
4681                      variant: ast::variant, index: int, is_degen: bool,
4682                      ty_params: [ast::ty_param]) {
4683     let ccx = cx.ccx;
4684
4685     if vec::len::<ast::variant_arg>(variant.node.args) == 0u {
4686         ret; // nullary constructors are just constants
4687
4688     }
4689     // Translate variant arguments to function arguments.
4690
4691     let fn_args: [ast::arg] = [];
4692     let i = 0u;
4693     for varg: ast::variant_arg in variant.node.args {
4694         fn_args +=
4695             [{mode: ast::by_copy,
4696               ty: varg.ty,
4697               ident: "arg" + uint::to_str(i, 10u),
4698               id: varg.id}];
4699     }
4700     assert (ccx.item_ids.contains_key(variant.node.id));
4701     let llfndecl: ValueRef;
4702     alt ccx.item_ids.find(variant.node.id) {
4703       some(x) { llfndecl = x; }
4704       _ {
4705         ccx.sess.span_fatal(variant.span,
4706                                "unbound variant id in trans_tag_variant");
4707       }
4708     }
4709     let fcx = new_fn_ctxt(cx, variant.span, llfndecl);
4710     create_llargs_for_fn_args(fcx, no_self, fn_args, ty_params);
4711     let ty_param_substs: [ty::t] = [];
4712     i = 0u;
4713     for tp: ast::ty_param in ty_params {
4714         ty_param_substs += [ty::mk_param(ccx.tcx, i,
4715                                          ast_util::local_def(tp.id))];
4716         i += 1u;
4717     }
4718     let arg_tys = arg_tys_of_fn(ccx, variant.node.id);
4719     let bcx = new_top_block_ctxt(fcx);
4720     let lltop = bcx.llbb;
4721     bcx = copy_args_to_allocas(fcx, bcx, fn_args, arg_tys);
4722
4723     // Cast the tag to a type we can GEP into.
4724     let llblobptr =
4725         if is_degen {
4726             fcx.llretptr
4727         } else {
4728             let lltagptr =
4729                 PointerCast(bcx, fcx.llretptr, T_opaque_tag_ptr(ccx));
4730             let lldiscrimptr = GEPi(bcx, lltagptr, [0, 0]);
4731             Store(bcx, C_int(ccx, index), lldiscrimptr);
4732             GEPi(bcx, lltagptr, [0, 1])
4733         };
4734     i = 0u;
4735     let t_id = ast_util::local_def(tag_id);
4736     let v_id = ast_util::local_def(variant.node.id);
4737     for va: ast::variant_arg in variant.node.args {
4738         check (valid_variant_index(i, bcx, t_id, v_id));
4739         let rslt = GEP_tag(bcx, llblobptr, t_id, v_id, ty_param_substs, i);
4740         bcx = rslt.bcx;
4741         let lldestptr = rslt.val;
4742         // If this argument to this function is a tag, it'll have come in to
4743         // this function as an opaque blob due to the way that type_of()
4744         // works. So we have to cast to the destination's view of the type.
4745         let llarg = alt fcx.llargs.find(va.id) { some(local_mem(x)) { x } };
4746         let arg_ty = arg_tys[i].ty;
4747         if ty::type_contains_params(bcx_tcx(bcx), arg_ty) {
4748             lldestptr = PointerCast(bcx, lldestptr, val_ty(llarg));
4749         }
4750         bcx = memmove_ty(bcx, lldestptr, llarg, arg_ty);
4751         i += 1u;
4752     }
4753     build_return(bcx);
4754     finish_fn(fcx, lltop);
4755 }
4756
4757
4758 // FIXME: this should do some structural hash-consing to avoid
4759 // duplicate constants. I think. Maybe LLVM has a magical mode
4760 // that does so later on?
4761 fn trans_const_expr(cx: @crate_ctxt, e: @ast::expr) -> ValueRef {
4762     alt e.node {
4763       ast::expr_lit(lit) { ret trans_crate_lit(cx, *lit); }
4764       ast::expr_binary(b, e1, e2) {
4765         let te1 = trans_const_expr(cx, e1);
4766         let te2 = trans_const_expr(cx, e2);
4767         /* Neither type is bottom, and we expect them to be unified already,
4768          * so the following is safe. */
4769         let ty = ty::expr_ty(ccx_tcx(cx), e1);
4770         let is_float = ty::type_is_fp(ccx_tcx(cx), ty);
4771         let signed = ty::type_is_signed(ccx_tcx(cx), ty);
4772         ret alt b {
4773           ast::add.    {
4774             if is_float { llvm::LLVMConstFAdd(te1, te2) }
4775             else        { llvm::LLVMConstAdd(te1, te2) }
4776           }
4777           ast::sub.    {
4778             if is_float { llvm::LLVMConstFSub(te1, te2) }
4779             else        { llvm::LLVMConstSub(te1, te2) }
4780           }
4781           ast::mul.    {
4782             if is_float { llvm::LLVMConstFMul(te1, te2) }
4783             else        { llvm::LLVMConstMul(te1, te2) }
4784           }
4785           ast::div.    {
4786             if is_float    { llvm::LLVMConstFDiv(te1, te2) }
4787             else if signed { llvm::LLVMConstSDiv(te1, te2) }
4788             else           { llvm::LLVMConstUDiv(te1, te2) }
4789           }
4790           ast::rem.    {
4791             if is_float    { llvm::LLVMConstFRem(te1, te2) }
4792             else if signed { llvm::LLVMConstSRem(te1, te2) }
4793             else           { llvm::LLVMConstURem(te1, te2) }
4794           }
4795           ast::and.    |
4796           ast::or.     { cx.sess.span_unimpl(e.span, "binop logic"); }
4797           ast::bitxor. { llvm::LLVMConstXor(te1, te2) }
4798           ast::bitand. { llvm::LLVMConstAnd(te1, te2) }
4799           ast::bitor.  { llvm::LLVMConstOr(te1, te2) }
4800           ast::lsl.    { llvm::LLVMConstShl(te1, te2) }
4801           ast::lsr.    { llvm::LLVMConstLShr(te1, te2) }
4802           ast::asr.    { llvm::LLVMConstAShr(te1, te2) }
4803           ast::eq.     |
4804           ast::lt.     |
4805           ast::le.     |
4806           ast::ne.     |
4807           ast::ge.     |
4808           ast::gt.     { cx.sess.span_unimpl(e.span, "binop comparator"); }
4809         }
4810       }
4811       ast::expr_unary(u, e) {
4812         let te = trans_const_expr(cx, e);
4813         let ty = ty::expr_ty(ccx_tcx(cx), e);
4814         let is_float = ty::type_is_fp(ccx_tcx(cx), ty);
4815         ret alt u {
4816           ast::box(_)  |
4817           ast::uniq(_) |
4818           ast::deref.  { cx.sess.span_bug(e.span,
4819                            "bad unop type in trans_const_expr"); }
4820           ast::not.    { llvm::LLVMConstNot(te) }
4821           ast::neg.    {
4822             if is_float { llvm::LLVMConstFNeg(te) }
4823             else        { llvm::LLVMConstNeg(te) }
4824           }
4825         }
4826       }
4827       _ { cx.sess.span_bug(e.span,
4828             "bad constant expression type in trans_const_expr"); }
4829     }
4830 }
4831
4832 fn trans_const(cx: @crate_ctxt, e: @ast::expr, id: ast::node_id) {
4833     let v = trans_const_expr(cx, e);
4834
4835     // The scalars come back as 1st class LLVM vals
4836     // which we have to stick into global constants.
4837
4838     alt cx.consts.find(id) {
4839       some(g) {
4840         llvm::LLVMSetInitializer(g, v);
4841         llvm::LLVMSetGlobalConstant(g, True);
4842       }
4843       _ { cx.sess.span_fatal(e.span, "Unbound const in trans_const"); }
4844     }
4845 }
4846
4847 type c_stack_tys = {
4848     arg_tys: [TypeRef],
4849     ret_ty: TypeRef,
4850     ret_def: bool,
4851     base_fn_ty: TypeRef,
4852     bundle_ty: TypeRef,
4853     shim_fn_ty: TypeRef
4854 };
4855
4856 fn c_stack_tys(ccx: @crate_ctxt,
4857                sp: span,
4858                id: ast::node_id) -> @c_stack_tys {
4859     alt ty::struct(ccx.tcx, ty::node_id_to_type(ccx.tcx, id)) {
4860       ty::ty_native_fn(arg_tys, ret_ty) {
4861         let tcx = ccx.tcx;
4862         let llargtys = type_of_explicit_args(ccx, sp, arg_tys);
4863         check non_ty_var(ccx, ret_ty); // NDM does this truly hold?
4864         let llretty = type_of_inner(ccx, sp, ret_ty);
4865         let bundle_ty = T_struct(llargtys + [T_ptr(llretty)]);
4866         ret @{
4867             arg_tys: llargtys,
4868             ret_ty: llretty,
4869             ret_def: !ty::type_is_bot(tcx, ret_ty) &&
4870                 !ty::type_is_nil(tcx, ret_ty),
4871             base_fn_ty: T_fn(llargtys, llretty),
4872             bundle_ty: bundle_ty,
4873             shim_fn_ty: T_fn([T_ptr(bundle_ty)], T_void())
4874         };
4875       }
4876
4877       _ {
4878         ccx.sess.span_fatal(
4879             sp,
4880             "Non-function type for native fn");
4881       }
4882     }
4883 }
4884
4885 // For each native function F, we generate a wrapper function W and a shim
4886 // function S that all work together.  The wrapper function W is the function
4887 // that other rust code actually invokes.  Its job is to marshall the
4888 // arguments into a struct.  It then uses a small bit of assembly to switch
4889 // over to the C stack and invoke the shim function.  The shim function S then
4890 // unpacks the arguments from the struct and invokes the actual function F
4891 // according to its specified calling convention.
4892 //
4893 // Example: Given a native c-stack function F(x: X, y: Y) -> Z,
4894 // we generate a wrapper function W that looks like:
4895 //
4896 //    void W(Z* dest, void *env, X x, Y y) {
4897 //        struct { X x; Y y; Z *z; } args = { x, y, z };
4898 //        call_on_c_stack_shim(S, &args);
4899 //    }
4900 //
4901 // The shim function S then looks something like:
4902 //
4903 //     void S(struct { X x; Y y; Z *z; } *args) {
4904 //         *args->z = F(args->x, args->y);
4905 //     }
4906 //
4907 // However, if the return type of F is dynamically sized or of aggregate type,
4908 // the shim function looks like:
4909 //
4910 //     void S(struct { X x; Y y; Z *z; } *args) {
4911 //         F(args->z, args->x, args->y);
4912 //     }
4913 //
4914 // Note: on i386, the layout of the args struct is generally the same as the
4915 // desired layout of the arguments on the C stack.  Therefore, we could use
4916 // upcall_alloc_c_stack() to allocate the `args` structure and switch the
4917 // stack pointer appropriately to avoid a round of copies.  (In fact, the shim
4918 // function itself is unnecessary). We used to do this, in fact, and will
4919 // perhaps do so in the future.
4920 fn trans_native_mod(lcx: @local_ctxt, native_mod: ast::native_mod,
4921                     abi: ast::native_abi) {
4922     fn build_shim_fn(lcx: @local_ctxt,
4923                      native_item: @ast::native_item,
4924                      tys: @c_stack_tys,
4925                      cc: uint) -> ValueRef {
4926         let lname = link_name(native_item);
4927         let ccx = lcx_ccx(lcx);
4928         let span = native_item.span;
4929
4930         // Declare the "prototype" for the base function F:
4931         let llbasefn = decl_fn(ccx.llmod, lname, cc, tys.base_fn_ty);
4932
4933         // Create the shim function:
4934         let shim_name = lname + "__c_stack_shim";
4935         let llshimfn = decl_internal_cdecl_fn(
4936             ccx.llmod, shim_name, tys.shim_fn_ty);
4937
4938         // Declare the body of the shim function:
4939         let fcx = new_fn_ctxt(lcx, span, llshimfn);
4940         let bcx = new_top_block_ctxt(fcx);
4941         let lltop = bcx.llbb;
4942         let llargbundle = llvm::LLVMGetParam(llshimfn, 0u);
4943         let i = 0u, n = vec::len(tys.arg_tys);
4944         let llargvals = [];
4945         while i < n {
4946             let llargval = load_inbounds(bcx, llargbundle, [0, i as int]);
4947             llargvals += [llargval];
4948             i += 1u;
4949         }
4950
4951         // Create the call itself and store the return value:
4952         let llretval = CallWithConv(bcx, llbasefn, llargvals, cc); // r
4953         if tys.ret_def {
4954             // R** llretptr = &args->r;
4955             let llretptr = GEPi(bcx, llargbundle, [0, n as int]);
4956             // R* llretloc = *llretptr; /* (args->r) */
4957             let llretloc = Load(bcx, llretptr);
4958             // *args->r = r;
4959             Store(bcx, llretval, llretloc);
4960         }
4961
4962         // Finish up:
4963         build_return(bcx);
4964         finish_fn(fcx, lltop);
4965
4966         ret llshimfn;
4967     }
4968
4969     fn build_wrap_fn(lcx: @local_ctxt,
4970                      native_item: @ast::native_item,
4971                      tys: @c_stack_tys,
4972                      num_tps: uint,
4973                      llshimfn: ValueRef,
4974                      llwrapfn: ValueRef) {
4975         let span = native_item.span;
4976         let ccx = lcx_ccx(lcx);
4977         let fcx = new_fn_ctxt(lcx, span, llwrapfn);
4978         let bcx = new_top_block_ctxt(fcx);
4979         let lltop = bcx.llbb;
4980
4981         // Allocate the struct and write the arguments into it.
4982         let llargbundle = alloca(bcx, tys.bundle_ty);
4983         let i = 0u, n = vec::len(tys.arg_tys);
4984         let implicit_args = 2u + num_tps; // ret + env
4985         while i < n {
4986             let llargval = llvm::LLVMGetParam(llwrapfn, i + implicit_args);
4987             store_inbounds(bcx, llargval, llargbundle, [0, i as int]);
4988             i += 1u;
4989         }
4990         let llretptr = llvm::LLVMGetParam(llwrapfn, 0u);
4991         store_inbounds(bcx, llretptr, llargbundle, [0, n as int]);
4992
4993         // Create call itself.
4994         let call_shim_on_c_stack = ccx.upcalls.call_shim_on_c_stack;
4995         let llshimfnptr = PointerCast(bcx, llshimfn, T_ptr(T_i8()));
4996         let llrawargbundle = PointerCast(bcx, llargbundle, T_ptr(T_i8()));
4997         Call(bcx, call_shim_on_c_stack, [llrawargbundle, llshimfnptr]);
4998         build_return(bcx);
4999         finish_fn(fcx, lltop);
5000     }
5001
5002     let ccx = lcx_ccx(lcx);
5003     let cc: uint = lib::llvm::LLVMCCallConv;
5004     alt abi {
5005       ast::native_abi_rust_intrinsic. { ret; }
5006       ast::native_abi_cdecl. { cc = lib::llvm::LLVMCCallConv; }
5007       ast::native_abi_stdcall. { cc = lib::llvm::LLVMX86StdcallCallConv; }
5008     }
5009
5010     for native_item in native_mod.items {
5011       alt native_item.node {
5012         ast::native_item_ty. {}
5013         ast::native_item_fn(fn_decl, tps) {
5014           let span = native_item.span;
5015           let id = native_item.id;
5016           let tys = c_stack_tys(ccx, span, id);
5017           alt ccx.item_ids.find(id) {
5018             some(llwrapfn) {
5019               let llshimfn = build_shim_fn(lcx, native_item, tys, cc);
5020               build_wrap_fn(lcx, native_item, tys,
5021                             vec::len(tps), llshimfn, llwrapfn);
5022             }
5023
5024             none. {
5025               ccx.sess.span_fatal(
5026                   native_item.span,
5027                   "unbound function item in trans_native_mod");
5028             }
5029           }
5030         }
5031       }
5032     }
5033 }
5034
5035 fn trans_item(cx: @local_ctxt, item: ast::item) {
5036     alt item.node {
5037       ast::item_fn(decl, tps, body) {
5038         let sub_cx = extend_path(cx, item.ident);
5039         alt cx.ccx.item_ids.find(item.id) {
5040           some(llfndecl) {
5041             trans_fn(sub_cx, item.span, decl, body, llfndecl, no_self, tps,
5042                      item.id);
5043           }
5044           _ {
5045             cx.ccx.sess.span_fatal(item.span,
5046                                    "unbound function item in trans_item");
5047           }
5048         }
5049       }
5050       ast::item_obj(ob, tps, ctor_id) {
5051         let sub_cx =
5052             @{obj_typarams: tps, obj_fields: ob.fields
5053                  with *extend_path(cx, item.ident)};
5054         trans_obj(sub_cx, item.span, ob, ctor_id, tps);
5055       }
5056       ast::item_impl(tps, _, _, ms) {
5057         trans_impl::trans_impl(cx, item.ident, ms, item.id, tps);
5058       }
5059       ast::item_res(decl, tps, body, dtor_id, ctor_id) {
5060         trans_res_ctor(cx, item.span, decl, ctor_id, tps);
5061
5062         // Create a function for the destructor
5063         alt cx.ccx.item_ids.find(item.id) {
5064           some(lldtor_decl) {
5065             trans_fn(cx, item.span, decl, body, lldtor_decl, no_self,
5066                      tps, dtor_id);
5067           }
5068           _ {
5069             cx.ccx.sess.span_fatal(item.span, "unbound dtor in trans_item");
5070           }
5071         }
5072       }
5073       ast::item_mod(m) {
5074         let sub_cx =
5075             @{path: cx.path + [item.ident],
5076               module_path: cx.module_path + [item.ident] with *cx};
5077         trans_mod(sub_cx, m);
5078       }
5079       ast::item_tag(variants, tps) {
5080         let sub_cx = extend_path(cx, item.ident);
5081         let degen = vec::len(variants) == 1u;
5082         let i = 0;
5083         for variant: ast::variant in variants {
5084             trans_tag_variant(sub_cx, item.id, variant, i, degen, tps);
5085             i += 1;
5086         }
5087       }
5088       ast::item_const(_, expr) { trans_const(cx.ccx, expr, item.id); }
5089       ast::item_native_mod(native_mod) {
5090         let abi = alt attr::native_abi(item.attrs) {
5091           either::right(abi_) { abi_ }
5092           either::left(msg) { cx.ccx.sess.span_fatal(item.span, msg) }
5093         };
5094         trans_native_mod(cx, native_mod, abi);
5095       }
5096       _ {/* fall through */ }
5097     }
5098 }
5099
5100 // Translate a module.  Doing this amounts to translating the items in the
5101 // module; there ends up being no artifact (aside from linkage names) of
5102 // separate modules in the compiled program.  That's because modules exist
5103 // only as a convenience for humans working with the code, to organize names
5104 // and control visibility.
5105 fn trans_mod(cx: @local_ctxt, m: ast::_mod) {
5106     for item: @ast::item in m.items { trans_item(cx, *item); }
5107 }
5108
5109 fn get_pair_fn_ty(llpairty: TypeRef) -> TypeRef {
5110     // Bit of a kludge: pick the fn typeref out of the pair.
5111
5112     ret struct_elt(llpairty, 0u);
5113 }
5114
5115 fn register_fn(ccx: @crate_ctxt, sp: span, path: [str], flav: str,
5116                ty_params: [ast::ty_param], node_id: ast::node_id) {
5117     // FIXME: pull this out
5118     let t = node_id_type(ccx, node_id);
5119     check returns_non_ty_var(ccx, t);
5120     register_fn_full(ccx, sp, path, flav, ty_params, node_id, t);
5121 }
5122
5123 fn param_bounds(ccx: @crate_ctxt, tp: ast::ty_param) -> ty::param_bounds {
5124     ccx.tcx.ty_param_bounds.get(tp.id)
5125 }
5126
5127 fn register_fn_full(ccx: @crate_ctxt, sp: span, path: [str], _flav: str,
5128                     tps: [ast::ty_param], node_id: ast::node_id,
5129                     node_type: ty::t)
5130     : returns_non_ty_var(ccx, node_type) {
5131     let path = path;
5132     let llfty = type_of_fn_from_ty(ccx, sp, node_type,
5133                                    vec::map(tps, {|p| param_bounds(ccx, p)}));
5134     let ps: str = mangle_exported_name(ccx, path, node_type);
5135     let llfn: ValueRef = decl_cdecl_fn(ccx.llmod, ps, llfty);
5136     ccx.item_ids.insert(node_id, llfn);
5137     ccx.item_symbols.insert(node_id, ps);
5138
5139     let is_main: bool = is_main_name(path) && !ccx.sess.building_library();
5140     if is_main { create_main_wrapper(ccx, sp, llfn, node_type); }
5141 }
5142
5143 // Create a _rust_main(args: [str]) function which will be called from the
5144 // runtime rust_start function
5145 fn create_main_wrapper(ccx: @crate_ctxt, sp: span, main_llfn: ValueRef,
5146                        main_node_type: ty::t) {
5147
5148     if ccx.main_fn != none::<ValueRef> {
5149         ccx.sess.span_fatal(sp, "multiple 'main' functions");
5150     }
5151
5152     let main_takes_argv =
5153         alt ty::struct(ccx.tcx, main_node_type) {
5154           ty::ty_fn({inputs, _}) { vec::len(inputs) != 0u }
5155         };
5156
5157     let llfn = create_main(ccx, sp, main_llfn, main_takes_argv);
5158     ccx.main_fn = some(llfn);
5159     create_entry_fn(ccx, llfn);
5160
5161     fn create_main(ccx: @crate_ctxt, sp: span, main_llfn: ValueRef,
5162                    takes_argv: bool) -> ValueRef {
5163         let unit_ty = ty::mk_str(ccx.tcx);
5164         let vecarg_ty: ty::arg =
5165             {mode: ast::by_val,
5166              ty: ty::mk_vec(ccx.tcx, {ty: unit_ty, mut: ast::imm})};
5167         // FIXME: mk_nil should have a postcondition
5168         let nt = ty::mk_nil(ccx.tcx);
5169         let llfty = type_of_fn(ccx, sp, false, [vecarg_ty], nt, []);
5170         let llfdecl = decl_fn(ccx.llmod, "_rust_main",
5171                               lib::llvm::LLVMCCallConv, llfty);
5172
5173         let fcx = new_fn_ctxt(new_local_ctxt(ccx), sp, llfdecl);
5174
5175         let bcx = new_top_block_ctxt(fcx);
5176         let lltop = bcx.llbb;
5177
5178         let lloutputarg = llvm::LLVMGetParam(llfdecl, 0u);
5179         let llenvarg = llvm::LLVMGetParam(llfdecl, 1u);
5180         let args = [lloutputarg, llenvarg];
5181         if takes_argv { args += [llvm::LLVMGetParam(llfdecl, 2u)]; }
5182         Call(bcx, main_llfn, args);
5183         build_return(bcx);
5184
5185         finish_fn(fcx, lltop);
5186
5187         ret llfdecl;
5188     }
5189
5190     fn create_entry_fn(ccx: @crate_ctxt, rust_main: ValueRef) {
5191         #[cfg(target_os = "win32")]
5192         fn main_name() -> str { ret "WinMain@16"; }
5193         #[cfg(target_os = "macos")]
5194         fn main_name() -> str { ret "main"; }
5195         #[cfg(target_os = "linux")]
5196         fn main_name() -> str { ret "main"; }
5197         #[cfg(target_os = "freebsd")]
5198         fn main_name() -> str { ret "main"; }
5199         let llfty = T_fn([ccx.int_type, ccx.int_type], ccx.int_type);
5200         let llfn = decl_cdecl_fn(ccx.llmod, main_name(), llfty);
5201         let llbb = str::as_buf("top", {|buf|
5202             llvm::LLVMAppendBasicBlock(llfn, buf)
5203         });
5204         let bld = *ccx.builder;
5205         llvm::LLVMPositionBuilderAtEnd(bld, llbb);
5206         let crate_map = ccx.crate_map;
5207         let start_ty = T_fn([val_ty(rust_main), ccx.int_type, ccx.int_type,
5208                              val_ty(crate_map)], ccx.int_type);
5209         let start = str::as_buf("rust_start", {|buf|
5210             llvm::LLVMAddGlobal(ccx.llmod, start_ty, buf)
5211         });
5212         let args = [rust_main, llvm::LLVMGetParam(llfn, 0u),
5213                     llvm::LLVMGetParam(llfn, 1u), crate_map];
5214         let result = unsafe {
5215             llvm::LLVMBuildCall(bld, start, vec::to_ptr(args),
5216                                 vec::len(args), noname())
5217         };
5218         llvm::LLVMBuildRet(bld, result);
5219     }
5220 }
5221
5222 // Create a /real/ closure: this is like create_fn_pair, but creates a
5223 // a fn value on the stack with a specified environment (which need not be
5224 // on the stack).
5225 fn create_real_fn_pair(cx: @block_ctxt, llfnty: TypeRef, llfn: ValueRef,
5226                        llenvptr: ValueRef) -> ValueRef {
5227     let lcx = cx.fcx.lcx;
5228
5229     let pair = alloca(cx, T_fn_pair(lcx.ccx, llfnty));
5230     fill_fn_pair(cx, pair, llfn, llenvptr);
5231     ret pair;
5232 }
5233
5234 fn fill_fn_pair(bcx: @block_ctxt, pair: ValueRef, llfn: ValueRef,
5235                 llenvptr: ValueRef) {
5236     let ccx = bcx_ccx(bcx);
5237     let code_cell = GEPi(bcx, pair, [0, abi::fn_field_code]);
5238     Store(bcx, llfn, code_cell);
5239     let env_cell = GEPi(bcx, pair, [0, abi::fn_field_box]);
5240     let llenvblobptr =
5241         PointerCast(bcx, llenvptr, T_opaque_cbox_ptr(ccx));
5242     Store(bcx, llenvblobptr, env_cell);
5243 }
5244
5245 // Returns the number of type parameters that the given native function has.
5246 fn native_fn_ty_param_count(cx: @crate_ctxt, id: ast::node_id) -> uint {
5247     let count;
5248     let native_item =
5249         alt cx.ast_map.find(id) { some(ast_map::node_native_item(i)) { i } };
5250     alt native_item.node {
5251       ast::native_item_ty. {
5252         cx.sess.bug("register_native_fn(): native fn isn't \
5253                         actually a fn");
5254       }
5255       ast::native_item_fn(_, tps) {
5256         count = vec::len::<ast::ty_param>(tps);
5257       }
5258     }
5259     ret count;
5260 }
5261
5262 fn native_fn_wrapper_type(cx: @crate_ctxt, sp: span,
5263                           param_bounds: [ty::param_bounds],
5264                           x: ty::t) -> TypeRef {
5265     alt ty::struct(cx.tcx, x) {
5266       ty::ty_native_fn(args, out) {
5267         ret type_of_fn(cx, sp, false, args, out, param_bounds);
5268       }
5269     }
5270 }
5271
5272 fn raw_native_fn_type(ccx: @crate_ctxt, sp: span, args: [ty::arg],
5273                       ret_ty: ty::t) -> TypeRef {
5274     check type_has_static_size(ccx, ret_ty);
5275     ret T_fn(type_of_explicit_args(ccx, sp, args), type_of(ccx, sp, ret_ty));
5276 }
5277
5278 fn link_name(i: @ast::native_item) -> str {
5279     alt attr::get_meta_item_value_str_by_name(i.attrs, "link_name") {
5280       none. { ret i.ident; }
5281       option::some(ln) { ret ln; }
5282     }
5283 }
5284
5285 fn collect_native_item(ccx: @crate_ctxt,
5286                        abi: @mutable option::t<ast::native_abi>,
5287                        i: @ast::native_item,
5288                        &&pt: [str],
5289                        _v: vt<[str]>) {
5290     alt i.node {
5291       ast::native_item_fn(_, tps) {
5292         let sp = i.span;
5293         let id = i.id;
5294         let node_type = node_id_type(ccx, id);
5295         let fn_abi =
5296             alt attr::get_meta_item_value_str_by_name(i.attrs, "abi") {
5297             option::none. {
5298                 // if abi isn't specified for this function, inherit from
5299                   // its enclosing native module
5300                   option::get(*abi)
5301               }
5302                 _ {
5303                     alt attr::native_abi(i.attrs) {
5304                       either::right(abi_) { abi_ }
5305                       either::left(msg) { ccx.sess.span_fatal(i.span, msg) }
5306                     }
5307                 }
5308             };
5309         alt fn_abi {
5310           ast::native_abi_rust_intrinsic. {
5311             // For intrinsics: link the function directly to the intrinsic
5312             // function itself.
5313             let fn_type = type_of_fn_from_ty(
5314                 ccx, sp, node_type,
5315                 vec::map(tps, {|p| param_bounds(ccx, p)}));
5316             let ri_name = "rust_intrinsic_" + link_name(i);
5317             let llnativefn = get_extern_fn(
5318                 ccx.externs, ccx.llmod, ri_name,
5319                 lib::llvm::LLVMCCallConv, fn_type);
5320             ccx.item_ids.insert(id, llnativefn);
5321             ccx.item_symbols.insert(id, ri_name);
5322           }
5323
5324           ast::native_abi_cdecl. | ast::native_abi_stdcall. {
5325             // For true external functions: create a rust wrapper
5326             // and link to that.  The rust wrapper will handle
5327             // switching to the C stack.
5328             let new_pt = pt + [i.ident];
5329             register_fn(ccx, i.span, new_pt, "native fn", tps, i.id);
5330           }
5331         }
5332       }
5333       _ { }
5334     }
5335 }
5336
5337 fn collect_item(ccx: @crate_ctxt, abi: @mutable option::t<ast::native_abi>,
5338                 i: @ast::item, &&pt: [str], v: vt<[str]>) {
5339     let new_pt = pt + [i.ident];
5340     alt i.node {
5341       ast::item_const(_, _) {
5342         let typ = node_id_type(ccx, i.id);
5343         let s =
5344             mangle_exported_name(ccx, pt + [i.ident],
5345                                  node_id_type(ccx, i.id));
5346         // FIXME: Could follow from a constraint on types of const
5347         // items
5348         let g = str::as_buf(s, {|buf|
5349             check (type_has_static_size(ccx, typ));
5350             llvm::LLVMAddGlobal(ccx.llmod, type_of(ccx, i.span, typ), buf)
5351         });
5352         ccx.item_symbols.insert(i.id, s);
5353         ccx.consts.insert(i.id, g);
5354       }
5355       ast::item_native_mod(native_mod) {
5356         // Propagate the native ABI down to collect_native_item(),
5357         alt attr::native_abi(i.attrs) {
5358           either::left(msg) { ccx.sess.span_fatal(i.span, msg); }
5359           either::right(abi_) {
5360             *abi = option::some(abi_);
5361           }
5362         }
5363       }
5364       ast::item_fn(_, tps, _) {
5365         register_fn(ccx, i.span, new_pt, "fn", tps, i.id);
5366       }
5367       ast::item_obj(ob, tps, ctor_id) {
5368         register_fn(ccx, i.span, new_pt, "obj_ctor", tps, ctor_id);
5369       }
5370       ast::item_impl(tps, _, _, methods) {
5371         let name = i.ident + int::str(i.id);
5372         for m in methods {
5373             register_fn(ccx, i.span, pt + [name, m.ident],
5374                         "impl_method", tps + m.tps, m.id);
5375         }
5376       }
5377       ast::item_res(_, tps, _, dtor_id, ctor_id) {
5378         register_fn(ccx, i.span, new_pt, "res_ctor", tps, ctor_id);
5379         // Note that the destructor is associated with the item's id, not
5380         // the dtor_id. This is a bit counter-intuitive, but simplifies
5381         // ty_res, which would have to carry around two def_ids otherwise
5382         // -- one to identify the type, and one to find the dtor symbol.
5383         let t = node_id_type(ccx, dtor_id);
5384         // FIXME: how to get rid of this check?
5385         check returns_non_ty_var(ccx, t);
5386         register_fn_full(ccx, i.span, new_pt, "res_dtor", tps, i.id, t);
5387       }
5388       ast::item_tag(variants, tps) {
5389         for variant in variants {
5390             if vec::len(variant.node.args) != 0u {
5391                 register_fn(ccx, i.span, new_pt + [variant.node.name],
5392                             "tag", tps, variant.node.id);
5393             }
5394         }
5395       }
5396       _ { }
5397     }
5398     visit::visit_item(i, new_pt, v);
5399 }
5400
5401 fn collect_items(ccx: @crate_ctxt, crate: @ast::crate) {
5402     let abi = @mutable none::<ast::native_abi>;
5403     visit::visit_crate(*crate, [], visit::mk_vt(@{
5404         visit_native_item: bind collect_native_item(ccx, abi, _, _, _),
5405         visit_item: bind collect_item(ccx, abi, _, _, _)
5406         with *visit::default_visitor()
5407     }));
5408 }
5409
5410 // The constant translation pass.
5411 fn trans_constant(ccx: @crate_ctxt, it: @ast::item, &&pt: [str],
5412                   v: vt<[str]>) {
5413     let new_pt = pt + [it.ident];
5414     visit::visit_item(it, new_pt, v);
5415     alt it.node {
5416       ast::item_tag(variants, _) {
5417         let i = 0u;
5418         for variant in variants {
5419             let p = new_pt + [variant.node.name, "discrim"];
5420             let s = mangle_exported_name(ccx, p, ty::mk_int(ccx.tcx));
5421             let discrim_gvar = str::as_buf(s, {|buf|
5422                 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
5423             });
5424             llvm::LLVMSetInitializer(discrim_gvar, C_int(ccx, i as int));
5425             llvm::LLVMSetGlobalConstant(discrim_gvar, True);
5426             ccx.discrims.insert(
5427                 ast_util::local_def(variant.node.id), discrim_gvar);
5428             ccx.discrim_symbols.insert(variant.node.id, s);
5429             i += 1u;
5430         }
5431       }
5432       ast::item_impl(tps, some(@{node: ast::ty_path(_, id), _}), _, ms) {
5433         let i_did = ast_util::def_id_of_def(ccx.tcx.def_map.get(id));
5434         let ty = ty::lookup_item_type(ccx.tcx, i_did).ty;
5435         let new_pt = pt + [it.ident + int::str(it.id), "wrap"];
5436         let extra_tps = vec::map(tps, {|p| param_bounds(ccx, p)});
5437         let tbl = C_struct(vec::map(*ty::iface_methods(ccx.tcx, i_did), {|im|
5438             alt vec::find(ms, {|m| m.ident == im.ident}) {
5439               some(m) {
5440                 trans_impl::trans_wrapper(ccx, new_pt, extra_tps, m)
5441               }
5442             }
5443         }));
5444         let s = mangle_exported_name(ccx, new_pt + ["!vtable"], ty);
5445         let vt_gvar = str::as_buf(s, {|buf|
5446             llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl), buf)
5447         });
5448         llvm::LLVMSetInitializer(vt_gvar, tbl);
5449         llvm::LLVMSetGlobalConstant(vt_gvar, True);
5450         ccx.item_ids.insert(it.id, vt_gvar);
5451         ccx.item_symbols.insert(it.id, s);
5452       }
5453       _ { }
5454     }
5455 }
5456
5457 fn trans_constants(ccx: @crate_ctxt, crate: @ast::crate) {
5458     let visitor =
5459         @{visit_item: bind trans_constant(ccx, _, _, _)
5460              with *visit::default_visitor()};
5461     visit::visit_crate(*crate, [], visit::mk_vt(visitor));
5462 }
5463
5464 fn vp2i(cx: @block_ctxt, v: ValueRef) -> ValueRef {
5465     let ccx = bcx_ccx(cx);
5466     ret PtrToInt(cx, v, ccx.int_type);
5467 }
5468
5469 fn p2i(ccx: @crate_ctxt, v: ValueRef) -> ValueRef {
5470     ret llvm::LLVMConstPtrToInt(v, ccx.int_type);
5471 }
5472
5473 fn declare_intrinsics(llmod: ModuleRef) -> hashmap<str, ValueRef> {
5474     let T_memmove32_args: [TypeRef] =
5475         [T_ptr(T_i8()), T_ptr(T_i8()), T_i32(), T_i32(), T_i1()];
5476     let T_memmove64_args: [TypeRef] =
5477         [T_ptr(T_i8()), T_ptr(T_i8()), T_i64(), T_i32(), T_i1()];
5478     let T_memset32_args: [TypeRef] =
5479         [T_ptr(T_i8()), T_i8(), T_i32(), T_i32(), T_i1()];
5480     let T_memset64_args: [TypeRef] =
5481         [T_ptr(T_i8()), T_i8(), T_i64(), T_i32(), T_i1()];
5482     let T_trap_args: [TypeRef] = [];
5483     let gcroot =
5484         decl_cdecl_fn(llmod, "llvm.gcroot",
5485                       T_fn([T_ptr(T_ptr(T_i8())), T_ptr(T_i8())], T_void()));
5486     let gcread =
5487         decl_cdecl_fn(llmod, "llvm.gcread",
5488                       T_fn([T_ptr(T_i8()), T_ptr(T_ptr(T_i8()))], T_void()));
5489     let memmove32 =
5490         decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i32",
5491                       T_fn(T_memmove32_args, T_void()));
5492     let memmove64 =
5493         decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i64",
5494                       T_fn(T_memmove64_args, T_void()));
5495     let memset32 =
5496         decl_cdecl_fn(llmod, "llvm.memset.p0i8.i32",
5497                       T_fn(T_memset32_args, T_void()));
5498     let memset64 =
5499         decl_cdecl_fn(llmod, "llvm.memset.p0i8.i64",
5500                       T_fn(T_memset64_args, T_void()));
5501     let trap = decl_cdecl_fn(llmod, "llvm.trap", T_fn(T_trap_args, T_void()));
5502     let intrinsics = new_str_hash::<ValueRef>();
5503     intrinsics.insert("llvm.gcroot", gcroot);
5504     intrinsics.insert("llvm.gcread", gcread);
5505     intrinsics.insert("llvm.memmove.p0i8.p0i8.i32", memmove32);
5506     intrinsics.insert("llvm.memmove.p0i8.p0i8.i64", memmove64);
5507     intrinsics.insert("llvm.memset.p0i8.i32", memset32);
5508     intrinsics.insert("llvm.memset.p0i8.i64", memset64);
5509     intrinsics.insert("llvm.trap", trap);
5510     ret intrinsics;
5511 }
5512
5513 fn declare_dbg_intrinsics(llmod: ModuleRef,
5514                           intrinsics: hashmap<str, ValueRef>) {
5515     let declare =
5516         decl_cdecl_fn(llmod, "llvm.dbg.declare",
5517                       T_fn([T_metadata(), T_metadata()], T_void()));
5518     let value =
5519         decl_cdecl_fn(llmod, "llvm.dbg.value",
5520                       T_fn([T_metadata(), T_i64(), T_metadata()], T_void()));
5521     intrinsics.insert("llvm.dbg.declare", declare);
5522     intrinsics.insert("llvm.dbg.value", value);
5523 }
5524
5525 fn trap(bcx: @block_ctxt) {
5526     let v: [ValueRef] = [];
5527     alt bcx_ccx(bcx).intrinsics.find("llvm.trap") {
5528       some(x) { Call(bcx, x, v); }
5529       _ { bcx_ccx(bcx).sess.bug("unbound llvm.trap in trap"); }
5530     }
5531 }
5532
5533 fn create_module_map(ccx: @crate_ctxt) -> ValueRef {
5534     let elttype = T_struct([ccx.int_type, ccx.int_type]);
5535     let maptype = T_array(elttype, ccx.module_data.size() + 1u);
5536     let map =
5537         str::as_buf("_rust_mod_map",
5538                     {|buf| llvm::LLVMAddGlobal(ccx.llmod, maptype, buf) });
5539     llvm::LLVMSetLinkage(map,
5540                          lib::llvm::LLVMInternalLinkage as llvm::Linkage);
5541     let elts: [ValueRef] = [];
5542     ccx.module_data.items {|key, val|
5543         let elt = C_struct([p2i(ccx, C_cstr(ccx, key)),
5544                             p2i(ccx, val)]);
5545         elts += [elt];
5546     };
5547     let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
5548     elts += [term];
5549     llvm::LLVMSetInitializer(map, C_array(elttype, elts));
5550     ret map;
5551 }
5552
5553
5554 fn decl_crate_map(sess: session::session, mapname: str,
5555                   llmod: ModuleRef) -> ValueRef {
5556     let targ_cfg = sess.get_targ_cfg();
5557     let int_type = T_int(targ_cfg);
5558     let n_subcrates = 1;
5559     let cstore = sess.get_cstore();
5560     while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
5561     let mapname = sess.building_library() ? mapname : "toplevel";
5562     let sym_name = "_rust_crate_map_" + mapname;
5563     let arrtype = T_array(int_type, n_subcrates as uint);
5564     let maptype = T_struct([int_type, arrtype]);
5565     let map = str::as_buf(sym_name, {|buf|
5566         llvm::LLVMAddGlobal(llmod, maptype, buf)
5567     });
5568     llvm::LLVMSetLinkage(map, lib::llvm::LLVMExternalLinkage
5569                          as llvm::Linkage);
5570     ret map;
5571 }
5572
5573 // FIXME use hashed metadata instead of crate names once we have that
5574 fn fill_crate_map(ccx: @crate_ctxt, map: ValueRef) {
5575     let subcrates: [ValueRef] = [];
5576     let i = 1;
5577     let cstore = ccx.sess.get_cstore();
5578     while cstore::have_crate_data(cstore, i) {
5579         let nm = "_rust_crate_map_" + cstore::get_crate_data(cstore, i).name;
5580         let cr = str::as_buf(nm, {|buf|
5581             llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
5582         });
5583         subcrates += [p2i(ccx, cr)];
5584         i += 1;
5585     }
5586     subcrates += [C_int(ccx, 0)];
5587     llvm::LLVMSetInitializer(map, C_struct(
5588         [p2i(ccx, create_module_map(ccx)),
5589          C_array(ccx.int_type, subcrates)]));
5590 }
5591
5592 fn write_metadata(cx: @crate_ctxt, crate: @ast::crate) {
5593     if !cx.sess.building_library() { ret; }
5594     let llmeta = C_postr(metadata::encoder::encode_metadata(cx, crate));
5595     let llconst = trans_common::C_struct([llmeta]);
5596     let llglobal =
5597         str::as_buf("rust_metadata",
5598                     {|buf|
5599                         llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst), buf)
5600                     });
5601     llvm::LLVMSetInitializer(llglobal, llconst);
5602     let _: () =
5603         str::as_buf(cx.sess.get_targ_cfg().target_strs.meta_sect_name,
5604                     {|buf| llvm::LLVMSetSection(llglobal, buf) });
5605     llvm::LLVMSetLinkage(llglobal,
5606                          lib::llvm::LLVMInternalLinkage as llvm::Linkage);
5607
5608     let t_ptr_i8 = T_ptr(T_i8());
5609     llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8);
5610     let llvm_used =
5611         str::as_buf("llvm.used",
5612                     {|buf|
5613                         llvm::LLVMAddGlobal(cx.llmod, T_array(t_ptr_i8, 1u),
5614                                             buf)
5615                     });
5616     llvm::LLVMSetLinkage(llvm_used,
5617                          lib::llvm::LLVMAppendingLinkage as llvm::Linkage);
5618     llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
5619 }
5620
5621 // Writes the current ABI version into the crate.
5622 fn write_abi_version(ccx: @crate_ctxt) {
5623     shape::mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version),
5624                      false);
5625 }
5626
5627 fn trans_crate(sess: session::session, crate: @ast::crate, tcx: ty::ctxt,
5628                output: str, emap: resolve::exp_map, amap: ast_map::map,
5629                mut_map: mut::mut_map, copy_map: alias::copy_map,
5630                last_uses: last_use::last_uses, method_map: typeck::method_map,
5631                dict_map: typeck::dict_map)
5632     -> (ModuleRef, link::link_meta) {
5633     let sha = std::sha1::mk_sha1();
5634     let link_meta = link::build_link_meta(sess, *crate, output, sha);
5635
5636     // Append ".rc" to crate name as LLVM module identifier.
5637     //
5638     // LLVM code generator emits a ".file filename" directive
5639     // for ELF backends. Value of the "filename" is set as the
5640     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
5641     // crashes if the module identifer is same as other symbols
5642     // such as a function name in the module.
5643     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
5644     let llmod_id = link_meta.name + ".rc";
5645
5646     let llmod = str::as_buf(llmod_id, {|buf|
5647         llvm::LLVMModuleCreateWithNameInContext
5648             (buf, llvm::LLVMGetGlobalContext())
5649     });
5650     let data_layout = sess.get_targ_cfg().target_strs.data_layout;
5651     let targ_triple = sess.get_targ_cfg().target_strs.target_triple;
5652     let _: () =
5653         str::as_buf(data_layout,
5654                     {|buf| llvm::LLVMSetDataLayout(llmod, buf) });
5655     let _: () =
5656         str::as_buf(targ_triple,
5657                     {|buf| llvm::LLVMSetTarget(llmod, buf) });
5658     let targ_cfg = sess.get_targ_cfg();
5659     let td = mk_target_data(sess.get_targ_cfg().target_strs.data_layout);
5660     let tn = mk_type_names();
5661     let intrinsics = declare_intrinsics(llmod);
5662     if sess.get_opts().extra_debuginfo {
5663         declare_dbg_intrinsics(llmod, intrinsics);
5664     }
5665     let int_type = T_int(targ_cfg);
5666     let float_type = T_float(targ_cfg);
5667     let task_type = T_task(targ_cfg);
5668     let taskptr_type = T_ptr(task_type);
5669     tn.associate("taskptr", taskptr_type);
5670     let tydesc_type = T_tydesc(targ_cfg);
5671     tn.associate("tydesc", tydesc_type);
5672     let crate_map = decl_crate_map(sess, link_meta.name, llmod);
5673     let dbg_cx = if sess.get_opts().debuginfo {
5674         option::some(@{llmetadata: map::new_int_hash(),
5675                        names: namegen(0)})
5676     } else {
5677         option::none
5678     };
5679     let ccx =
5680         @{sess: sess,
5681           llmod: llmod,
5682           td: td,
5683           tn: tn,
5684           externs: new_str_hash::<ValueRef>(),
5685           intrinsics: intrinsics,
5686           item_ids: new_int_hash::<ValueRef>(),
5687           ast_map: amap,
5688           exp_map: emap,
5689           item_symbols: new_int_hash::<str>(),
5690           mutable main_fn: none::<ValueRef>,
5691           link_meta: link_meta,
5692           tag_sizes: ty::new_ty_hash(),
5693           discrims: ast_util::new_def_id_hash::<ValueRef>(),
5694           discrim_symbols: new_int_hash::<str>(),
5695           consts: new_int_hash::<ValueRef>(),
5696           tydescs: ty::new_ty_hash(),
5697           dicts: map::mk_hashmap(hash_dict_id, {|a, b| a == b}),
5698           module_data: new_str_hash::<ValueRef>(),
5699           lltypes: ty::new_ty_hash(),
5700           names: namegen(0),
5701           sha: sha,
5702           type_sha1s: ty::new_ty_hash(),
5703           type_short_names: ty::new_ty_hash(),
5704           tcx: tcx,
5705           mut_map: mut_map,
5706           copy_map: copy_map,
5707           last_uses: last_uses,
5708           method_map: method_map,
5709           dict_map: dict_map,
5710           stats:
5711               {mutable n_static_tydescs: 0u,
5712                mutable n_derived_tydescs: 0u,
5713                mutable n_glues_created: 0u,
5714                mutable n_null_glues: 0u,
5715                mutable n_real_glues: 0u,
5716                fn_times: @mutable []},
5717           upcalls:
5718               upcall::declare_upcalls(targ_cfg, tn, tydesc_type,
5719                                       llmod),
5720           rust_object_type: T_rust_object(),
5721           tydesc_type: tydesc_type,
5722           int_type: int_type,
5723           float_type: float_type,
5724           task_type: task_type,
5725           opaque_vec_type: T_opaque_vec(targ_cfg),
5726           builder: BuilderRef_res(llvm::LLVMCreateBuilder()),
5727           shape_cx: shape::mk_ctxt(llmod),
5728           gc_cx: gc::mk_ctxt(),
5729           crate_map: crate_map,
5730           dbg_cx: dbg_cx};
5731     let cx = new_local_ctxt(ccx);
5732     collect_items(ccx, crate);
5733     trans_constants(ccx, crate);
5734     trans_mod(cx, crate.node.module);
5735     fill_crate_map(ccx, crate_map);
5736     emit_tydescs(ccx);
5737     shape::gen_shape_tables(ccx);
5738     write_abi_version(ccx);
5739
5740     // Translate the metadata.
5741     write_metadata(cx.ccx, crate);
5742     if ccx.sess.get_opts().stats {
5743         #error("--- trans stats ---");
5744         #error("n_static_tydescs: %u", ccx.stats.n_static_tydescs);
5745         #error("n_derived_tydescs: %u", ccx.stats.n_derived_tydescs);
5746         #error("n_glues_created: %u", ccx.stats.n_glues_created);
5747         #error("n_null_glues: %u", ccx.stats.n_null_glues);
5748         #error("n_real_glues: %u", ccx.stats.n_real_glues);
5749
5750         for timing: {ident: str, time: int} in *ccx.stats.fn_times {
5751             #error("time: %s took %d ms", timing.ident, timing.time);
5752         }
5753     }
5754     ret (llmod, link_meta);
5755 }
5756 //
5757 // Local Variables:
5758 // mode: rust
5759 // fill-column: 78;
5760 // indent-tabs-mode: nil
5761 // c-basic-offset: 4
5762 // buffer-file-coding-system: utf-8-unix
5763 // End:
5764 //