1 // trans.rs: Translate the completed AST to the LLVM IR.
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.
8 // Hopefully useful general knowledge about trans:
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.
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;
22 import middle::{ty, gc, resolve, debuginfo};
23 import middle::freevars::*;
24 import back::{link, abi, upcall};
25 import syntax::{ast, ast_util, codemap};
27 import syntax::codemap::span;
28 import syntax::print::pprust::{expr_to_str, stmt_to_str};
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};
42 import trans_common::*;
43 import trans_build::*;
45 import trans_objects::{trans_anon_obj, trans_obj};
46 import tvec = trans_vec;
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)
54 fn type_of(cx: @crate_ctxt, sp: span, t: ty::t) : type_has_static_size(cx, t)
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)
62 fn type_of_explicit_args(cx: @crate_ctxt, sp: span, inputs: [ty::arg]) ->
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)];
77 // NB: must keep 4 fns in sync:
80 // - create_llargs_for_fn_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] = [];
87 // Arg 0: Output pointer.
88 check non_ty_var(cx, output);
89 let out_ty = T_ptr(type_of_inner(cx, sp, output));
92 // Arg 1: Env (closure-bindings / self-obj)
94 atys += [T_ptr(cx.rust_object_type)];
96 atys += [T_opaque_boxed_closure_ptr(cx)];
99 // Args >2: ty params, if not acquired via capture...
101 for bounds in params {
102 atys += [T_ptr(cx.tydesc_type)];
103 for bound in *bounds {
105 ty::bound_iface(_) { atys += [T_ptr(T_dict())]; }
111 // ... then explicit args.
112 atys += type_of_explicit_args(cx, sp, inputs);
113 ret T_fn(atys, llvm::LLVMVoidType());
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
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);
127 fn type_of_inner(cx: @crate_ctxt, sp: span, t: ty::t)
128 : non_ty_var(cx, t) -> TypeRef {
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() }
136 T_nil() /* ...I guess? */
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) }
146 check non_ty_var(cx, mt_ty);
147 T_ptr(T_box(cx, type_of_inner(cx, sp, mt_ty))) }
150 check non_ty_var(cx, mt_ty);
151 T_ptr(type_of_inner(cx, sp, mt_ty)) }
154 if ty::type_has_dynamic_size(cx.tcx, mt_ty) {
155 T_ptr(cx.opaque_vec_type)
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))) }
163 check non_ty_var(cx, mt_ty);
164 T_ptr(type_of_inner(cx, sp, mt_ty)) }
166 let tys: [TypeRef] = [];
167 for f: ty::field in fields {
169 check non_ty_var(cx, mt_ty);
170 tys += [type_of_inner(cx, sp, mt_ty)];
175 T_fn_pair(cx, type_of_fn_from_ty(cx, sp, t, []))
177 ty::ty_native_fn(args, out) {
178 let nft = native_fn_wrapper_type(cx, sp, [], t);
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)]);
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
193 std::util::unreachable()
195 ty::ty_param(_, _) { T_typaram(cx.tn) }
196 ty::ty_send_type. | ty::ty_type. { T_ptr(cx.tydesc_type) }
200 check non_ty_var(cx, elt);
201 tys += [type_of_inner(cx, sp, elt)];
205 ty::ty_opaque_closure. {
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)
214 fail "type_of_inner not implemented for this kind of type";
217 cx.lltypes.insert(t, llty);
221 fn type_of_tag(cx: @crate_ctxt, sp: span, did: ast::def_id, t: ty::t)
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) }
231 if degen { T_struct([T_tag_variant(cx)]) }
232 else { T_opaque_tag(cx) }
236 fn type_of_ty_param_bounds_and_ty(lcx: @local_ctxt, sp: span,
237 tpt: ty::ty_param_bounds_and_ty) -> TypeRef {
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);
248 // FIXME: could have a precondition on tpt, but that
249 // doesn't work right now because one predicate can't imply
251 check (type_has_static_size(cx, t));
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) {
259 type_of(ccx, sp, typ)
264 // Name sanitation. LLVM will happily accept identifiers with weird names, but
266 fn sanitize(s: str) -> str {
275 if c == '{' as u8 || c == '(' as u8 {
278 if c != 10u8 && c != '}' as u8 && c != ')' as u8 &&
279 c != ' ' as u8 && c != '\t' as u8 && c != ';' as u8
282 result += str::unsafe_from_bytes(v);
292 fn log_fn_time(ccx: @crate_ctxt, name: str, start: time::timeval,
293 end: time::timeval) {
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}];
301 fn decl_fn(llmod: ModuleRef, name: str, cc: uint, llty: TypeRef) -> ValueRef {
303 str::as_buf(name, {|buf|
304 llvm::LLVMGetOrInsertFunction(llmod, buf, llty) });
305 llvm::LLVMSetFunctionCallConv(llfn, cc);
309 fn decl_cdecl_fn(llmod: ModuleRef, name: str, llty: TypeRef) -> ValueRef {
310 ret decl_fn(llmod, name, lib::llvm::LLVMCCallConv, llty);
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) ->
318 let llfn = decl_cdecl_fn(llmod, name, llty);
319 llvm::LLVMSetLinkage(llfn,
320 lib::llvm::LLVMInternalLinkage as llvm::Linkage);
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);
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);
340 fn get_simple_extern_fn(cx: @block_ctxt,
341 externs: hashmap<str, ValueRef>,
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);
351 fn trans_native_call(cx: @block_ctxt, externs: hashmap<str, ValueRef>,
352 llmod: ModuleRef, name: str, args: [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)];
361 ret Call(cx, llnative, call_args);
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)]);
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()))]);
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);
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);
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));
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);
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);
407 fn llsize_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
408 ret llvm::LLVMConstIntCast(lib::llvm::llvm::LLVMSizeOf(t), cx.int_type,
412 fn llalign_of(cx: @crate_ctxt, t: TypeRef) -> ValueRef {
413 ret llvm::LLVMConstIntCast(lib::llvm::llvm::LLVMAlignOf(t), cx.int_type,
417 fn size_of(cx: @block_ctxt, t: ty::t) -> result {
418 size_of_(cx, t, align_total)
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) {
430 rslt(cx, llsize_of(bcx_ccx(cx), type_of(ccx, sp, t)))
431 } else { dynamic_size_of(cx, t, mode) }
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) {
438 rslt(cx, llalign_of(bcx_ccx(cx), type_of(ccx, sp, t)))
439 } else { dynamic_align_of(cx, t) }
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);
447 fn dynastack_alloca(cx: @block_ctxt, t: TypeRef, n: ValueRef, ty: ty::t) ->
449 if cx.unreachable { ret llvm::LLVMGetUndef(t); }
451 let dy_cx = new_raw_block_ctxt(cx.fcx, cx.fcx.lldynamicallocas);
452 alt bcx_fcx(cx).llobstacktoken {
454 bcx_fcx(cx).llobstacktoken =
455 some(mk_obstack_token(bcx_ccx(cx), cx.fcx));
457 some(_) {/* no-op */ }
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)),
466 let lltydesc = get_tydesc(cx, ty, false, tps_normal, ti).result.val;
468 let llresult = Call(dy_cx, dynastack_alloc, [llsz, lltydesc]);
469 ret PointerCast(dy_cx, llresult, T_ptr(t));
472 fn mk_obstack_token(ccx: @crate_ctxt, fcx: @fn_ctxt) ->
474 let cx = new_raw_block_ctxt(fcx, fcx.lldynamicallocas);
475 ret Call(cx, ccx.upcalls.dynastack_mark, []);
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
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)); }
488 ret ty::mk_imm_uniq(ccx.tcx, ty::mk_nil(ccx.tcx));
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))]);
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))]);
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)]);
508 ret ty::fold_ty(ccx.tcx, ty::fm_general(bind simplifier(ccx, _)), typ);
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).
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.
526 tup_ty = ty::substitute_type_params(cx.tcx, subtys, tup_ty);
527 // Here we possibly do a recursive call.
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; }
536 cx.tag_sizes.insert(t, max_size);
540 cx.tcx.sess.span_fatal(sp, "non-tag passed to static_size_of_tag()");
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 {
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.
557 let off = C_int(bcx_ccx(cx), 0);
558 let max_align = C_int(bcx_ccx(cx), 1);
560 for e: ty::t in elts {
561 let elt_align = align_of(bcx, e);
563 let elt_size = size_of(bcx, e);
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);
571 align_to(bcx, off, max_align)
574 let {bcx, val: align} = align_of(bcx, t);
575 align_to(bcx, off, align)
580 alt ty::struct(bcx_tcx(cx), t) {
582 let szptr = field_of_tydesc(cx, t, false, abi::tydesc_field_size);
583 ret rslt(szptr.bcx, Load(szptr.bcx, szptr.val));
586 let tys: [ty::t] = [];
587 for f: ty::field in flds { tys += [f.mt.ty]; }
588 ret align_elements(cx, tys, mode);
592 for tp in elts { tys += [tp]; }
593 ret align_elements(cx, tys, mode);
595 ty::ty_tag(tid, tps) {
597 let ccx = bcx_ccx(bcx);
598 // Compute max(variant sizes).
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.
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);
612 let rslt = align_elements(bcx, tys, mode);
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);
618 let max_size_val = Load(bcx, max_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);
628 fn dynamic_align_of(cx: @block_ctxt, t: ty::t) -> result {
629 // FIXME: Typestate constraint that shows this alt is
631 alt ty::struct(bcx_tcx(cx), t) {
633 let aptr = field_of_tydesc(cx, t, false, abi::tydesc_field_align);
634 ret rslt(aptr.bcx, Load(aptr.bcx, aptr.val));
637 let a = C_int(bcx_ccx(cx), 1);
639 for f: ty::field in flds {
640 let align = align_of(bcx, f.mt.ty);
642 a = umax(bcx, a, align.val);
647 ret rslt(cx, C_int(bcx_ccx(cx), 1)); // FIXME: stub
650 let a = C_int(bcx_ccx(cx), 1);
653 let align = align_of(bcx, e);
655 a = umax(bcx, a, align.val);
662 // Increment a pointer by a given amount and then cast it to be a pointer
664 fn bump_ptr(bcx: @block_ctxt, t: ty::t, base: ValueRef, sz: ValueRef) ->
666 let raw = PointerCast(bcx, base, T_ptr(T_i8()));
667 let bumped = GEP(bcx, raw, [sz]);
668 let ccx = bcx_ccx(bcx);
669 if check type_has_static_size(ccx, t) {
671 let typ = T_ptr(type_of(ccx, sp, t));
672 PointerCast(bcx, bumped, typ)
676 // GEP_tup_like is a pain to use if you always have to precede it with a
678 fn GEP_tup_like_1(cx: @block_ctxt, t: ty::t, base: ValueRef, ixs: [int])
680 check type_is_tup_like(cx, t);
681 ret GEP_tup_like(cx, t, base, ixs);
684 // Replacement for the LLVM 'GEP' instruction when field-indexing into a
685 // tuple-like structure (tup, rec) with a static index. This one is driven off
686 // ty::struct and knows what to do when it runs into a ty_param stuck in the
687 // middle of the thing it's GEP'ing into. Much like size_of and align_of,
689 fn GEP_tup_like(cx: @block_ctxt, t: ty::t, base: ValueRef, ixs: [int])
690 : type_is_tup_like(cx, t) -> result {
691 // It might be a static-known type. Handle this.
692 if !ty::type_has_dynamic_size(bcx_tcx(cx), t) {
693 ret rslt(cx, GEPi(cx, base, ixs));
695 // It is a dynamic-containing type that, if we convert directly to an LLVM
696 // TypeRef, will be all wrong; there's no proper LLVM type to represent
697 // it, and the lowering function will stick in i8* values for each
698 // ty_param, which is not right; the ty_params are all of some dynamic
701 // What we must do instead is sadder. We must look through the indices
702 // manually and split the input type into a prefix and a target. We then
703 // measure the prefix size, bump the input pointer by that amount, and
704 // cast to a pointer-to-target type.
706 // Given a type, an index vector and an element number N in that vector,
707 // calculate index X and the type that results by taking the first X-1
708 // elements of the type and splitting the Xth off. Return the prefix as
709 // well as the innermost Xth type.
711 fn split_type(ccx: @crate_ctxt, t: ty::t, ixs: [int], n: uint) ->
712 {prefix: [ty::t], target: ty::t} {
713 let len: uint = vec::len::<int>(ixs);
714 // We don't support 0-index or 1-index GEPs: The former is nonsense
715 // and the latter would only be meaningful if we supported non-0
716 // values for the 0th index (we don't).
720 // Since we're starting from a value that's a pointer to a
721 // *single* structure, the first index (in GEP-ese) should just be
722 // 0, to yield the pointee.
724 assert (ixs[n] == 0);
725 ret split_type(ccx, t, ixs, n + 1u);
728 let ix: int = ixs[n];
729 let prefix: [ty::t] = [];
732 prefix += [ty::get_element_type(ccx.tcx, t, i as uint)];
735 let selected = ty::get_element_type(ccx.tcx, t, i as uint);
737 // We are at the innermost index.
739 ret {prefix: prefix, target: selected};
741 // Not the innermost index; call self recursively to dig deeper.
742 // Once we get an inner result, append it current prefix and
745 let inner = split_type(ccx, selected, ixs, n + 1u);
746 prefix += inner.prefix;
747 ret {prefix: prefix with inner};
750 // We make a fake prefix tuple-type here; luckily for measuring sizes
751 // the tuple parens are associative so it doesn't matter that we've
752 // flattened the incoming structure.
754 let s = split_type(bcx_ccx(cx), t, ixs, 0u);
757 for typ: ty::t in s.prefix { args += [typ]; }
758 let prefix_ty = ty::mk_tup(bcx_tcx(cx), args);
761 let sz = size_of_(bcx, prefix_ty, align_next(s.target));
762 ret rslt(sz.bcx, bump_ptr(sz.bcx, s.target, base, sz.val));
766 // Replacement for the LLVM 'GEP' instruction when field indexing into a tag.
767 // This function uses GEP_tup_like() above and automatically performs casts as
768 // appropriate. @llblobptr is the data part of a tag value; its actual type is
769 // meaningless, as it will be cast away.
770 fn GEP_tag(cx: @block_ctxt, llblobptr: ValueRef, tag_id: ast::def_id,
771 variant_id: ast::def_id, ty_substs: [ty::t],
772 ix: uint) : valid_variant_index(ix, cx, tag_id, variant_id) ->
774 let variant = ty::tag_variant_with_id(bcx_tcx(cx), tag_id, variant_id);
775 // Synthesize a tuple type so that GEP_tup_like() can work its magic.
776 // Separately, store the type of the element we're interested in.
778 let arg_tys = variant.args;
780 let true_arg_tys: [ty::t] = [];
781 for aty: ty::t in arg_tys {
782 let arg_ty = ty::substitute_type_params(bcx_tcx(cx), ty_substs, aty);
783 true_arg_tys += [arg_ty];
786 // We know that ix < len(variant.args) -- so
787 // it's safe to do this. (Would be nice to have
788 // typestate guarantee that a dynamic bounds check
789 // error can't happen here, but that's in the future.)
790 let elem_ty = true_arg_tys[ix];
792 let tup_ty = ty::mk_tup(bcx_tcx(cx), true_arg_tys);
793 // Cast the blob pointer to the appropriate type, if we need to (i.e. if
794 // the blob pointer isn't dynamically sized).
796 let llunionptr: ValueRef;
798 let ccx = bcx_ccx(cx);
799 if check type_has_static_size(ccx, tup_ty) {
800 let llty = type_of(ccx, sp, tup_ty);
801 llunionptr = TruncOrBitCast(cx, llblobptr, T_ptr(llty));
802 } else { llunionptr = llblobptr; }
804 // Do the GEP_tup_like().
805 // Silly check -- postcondition on mk_tup?
806 check type_is_tup_like(cx, tup_ty);
807 let rs = GEP_tup_like(cx, tup_ty, llunionptr, [0, ix as int]);
808 // Cast the result to the appropriate type, if necessary.
810 let rs_ccx = bcx_ccx(rs.bcx);
812 if check type_has_static_size(rs_ccx, elem_ty) {
813 let llelemty = type_of(rs_ccx, sp, elem_ty);
814 PointerCast(rs.bcx, rs.val, T_ptr(llelemty))
817 ret rslt(rs.bcx, val);
820 // trans_shared_malloc: expects a type indicating which pointer type we want
821 // and a size indicating how much space we want malloc'd.
822 fn trans_shared_malloc(cx: @block_ctxt, llptr_ty: TypeRef, llsize: ValueRef)
824 // FIXME: need a table to collect tydesc globals.
826 let tydesc = C_null(T_ptr(bcx_ccx(cx).tydesc_type));
828 Call(cx, bcx_ccx(cx).upcalls.shared_malloc,
830 ret rslt(cx, PointerCast(cx, rval, llptr_ty));
833 // trans_malloc_boxed_raw: expects an unboxed type and returns a pointer to
834 // enough space for something of that type, along with space for a reference
835 // count; in other words, it allocates a box for something of that type.
836 fn trans_malloc_boxed_raw(cx: @block_ctxt, t: ty::t) -> result {
839 // Synthesize a fake box type structurally so we have something
840 // to measure the size of.
842 // We synthesize two types here because we want both the type of the
843 // pointer and the pointee. boxed_body is the type that we measure the
844 // size of; box_ptr is the type that's converted to a TypeRef and used as
845 // the pointer cast target in trans_raw_malloc.
847 // The mk_int here is the space being
848 // reserved for the refcount.
849 let boxed_body = ty::mk_tup(bcx_tcx(bcx), [ty::mk_int(bcx_tcx(cx)), t]);
850 let box_ptr = ty::mk_imm_box(bcx_tcx(bcx), t);
851 let r = size_of(cx, boxed_body);
852 let llsz = r.val; bcx = r.bcx;
854 // Grab the TypeRef type of box_ptr, because that's what trans_raw_malloc
856 // FIXME: Could avoid this check with a postcondition on mk_imm_box?
857 // (requires Issue #586)
858 let ccx = bcx_ccx(bcx);
860 check (type_has_static_size(ccx, box_ptr));
861 let llty = type_of(ccx, sp, box_ptr);
864 let tydesc_result = get_tydesc(bcx, t, true, tps_normal, ti);
865 let lltydesc = tydesc_result.result.val; bcx = tydesc_result.result.bcx;
867 let rval = Call(cx, ccx.upcalls.malloc,
869 ret rslt(cx, PointerCast(cx, rval, llty));
872 // trans_malloc_boxed: usefully wraps trans_malloc_box_raw; allocates a box,
873 // initializes the reference count to 1, and pulls out the body and rc
874 fn trans_malloc_boxed(cx: @block_ctxt, t: ty::t) ->
875 {bcx: @block_ctxt, box: ValueRef, body: ValueRef} {
876 let res = trans_malloc_boxed_raw(cx, t);
878 let rc = GEPi(res.bcx, box, [0, abi::box_rc_field_refcnt]);
879 Store(res.bcx, C_int(bcx_ccx(cx), 1), rc);
880 let body = GEPi(res.bcx, box, [0, abi::box_rc_field_body]);
881 ret {bcx: res.bcx, box: res.val, body: body};
884 // Type descriptor and type glue stuff
886 // Given a type and a field index into its corresponding type descriptor,
887 // returns an LLVM ValueRef of that field from the tydesc, generating the
888 // tydesc if necessary.
889 fn field_of_tydesc(cx: @block_ctxt, t: ty::t, escapes: bool, field: int) ->
891 let ti = none::<@tydesc_info>;
892 let tydesc = get_tydesc(cx, t, escapes, tps_normal, ti).result;
894 GEPi(tydesc.bcx, tydesc.val, [0, field]));
898 // Given a type containing ty params, build a vector containing a ValueRef for
899 // each of the ty params it uses (from the current frame) and a vector of the
900 // indices of the ty params present in the type. This is used solely for
901 // constructing derived tydescs.
902 fn linearize_ty_params(cx: @block_ctxt, t: ty::t) ->
903 {params: [uint], descs: [ValueRef]} {
904 let param_vals: [ValueRef] = [];
905 let param_defs: [uint] = [];
907 {cx: @block_ctxt, mutable vals: [ValueRef], mutable defs: [uint]};
909 fn linearizer(r: @rr, t: ty::t) {
910 alt ty::struct(bcx_tcx(r.cx), t) {
911 ty::ty_param(pid, _) {
912 let seen: bool = false;
913 for d: uint in r.defs { if d == pid { seen = true; } }
915 r.vals += [r.cx.fcx.lltyparams[pid].desc];
922 let x = @{cx: cx, mutable vals: param_vals, mutable defs: param_defs};
923 let f = bind linearizer(x, _);
924 ty::walk_ty(bcx_tcx(cx), f, t);
925 ret {params: x.defs, descs: x.vals};
928 fn trans_stack_local_derived_tydesc(cx: @block_ctxt, llsz: ValueRef,
929 llalign: ValueRef, llroottydesc: ValueRef,
930 llfirstparam: ValueRef, n_params: uint,
931 obj_params: uint) -> ValueRef {
932 let llmyroottydesc = alloca(cx, bcx_ccx(cx).tydesc_type);
934 // By convention, desc 0 is the root descriptor.
935 let llroottydesc = Load(cx, llroottydesc);
936 Store(cx, llroottydesc, llmyroottydesc);
938 // Store a pointer to the rest of the descriptors.
939 let ccx = bcx_ccx(cx);
940 store_inbounds(cx, llfirstparam, llmyroottydesc,
941 [0, abi::tydesc_field_first_param]);
942 store_inbounds(cx, C_uint(ccx, n_params), llmyroottydesc,
943 [0, abi::tydesc_field_n_params]);
944 store_inbounds(cx, llsz, llmyroottydesc,
945 [0, abi::tydesc_field_size]);
946 store_inbounds(cx, llalign, llmyroottydesc,
947 [0, abi::tydesc_field_align]);
948 store_inbounds(cx, C_uint(ccx, obj_params), llmyroottydesc,
949 [0, abi::tydesc_field_obj_params]);
953 // Objects and closures store their type parameters differently (in the object
954 // or closure itself rather than in the type descriptor).
955 tag ty_param_storage { tps_normal; tps_obj(uint); tps_fn(uint); }
957 fn get_derived_tydesc(cx: @block_ctxt, t: ty::t, escapes: bool,
958 storage: ty_param_storage,
959 &static_ti: option::t<@tydesc_info>) -> result {
960 alt cx.fcx.derived_tydescs.find(t) {
962 // If the tydesc escapes in this context, the cached derived
963 // tydesc also has to be one that was marked as escaping.
964 if !(escapes && !info.escapes) && storage == tps_normal {
965 ret rslt(cx, info.lltydesc);
968 none. {/* fall through */ }
973 tps_normal. { is_obj_body = false; }
974 tps_obj(_) | tps_fn(_) { is_obj_body = true; }
977 bcx_ccx(cx).stats.n_derived_tydescs += 1u;
978 let bcx = new_raw_block_ctxt(cx.fcx, cx.fcx.llderivedtydescs);
979 let tys = linearize_ty_params(bcx, t);
980 let root_ti = get_static_tydesc(bcx, t, tys.params, is_obj_body);
981 static_ti = some::<@tydesc_info>(root_ti);
982 lazily_emit_all_tydesc_glue(cx, static_ti);
983 let root = root_ti.tydesc;
984 let sz = size_of(bcx, t);
986 let align = align_of(bcx, t);
989 // Store the captured type descriptors in an alloca if the caller isn't
990 // promising to do so itself.
991 let n_params = ty::count_ty_params(bcx_tcx(bcx), t);
993 assert (n_params == vec::len::<uint>(tys.params));
994 assert (n_params == vec::len::<ValueRef>(tys.descs));
997 alloca(bcx, T_array(T_ptr(bcx_ccx(bcx).tydesc_type), n_params + 1u));
1000 // If the type descriptor escapes, we need to add in the root as
1001 // the first parameter, because upcall_get_type_desc() expects it.
1003 Store(bcx, root, GEPi(bcx, llparamtydescs, [0, 0]));
1007 for td: ValueRef in tys.descs {
1008 Store(bcx, td, GEPi(bcx, llparamtydescs, [0, i]));
1013 PointerCast(bcx, llparamtydescs,
1014 T_ptr(T_ptr(bcx_ccx(bcx).tydesc_type)));
1016 // The top bit indicates whether this type descriptor describes an object
1017 // (0) or a function (1).
1020 tps_normal. { obj_params = 0u; }
1021 tps_obj(np) { obj_params = np; }
1022 tps_fn(np) { obj_params = 0x80000000u | np; }
1027 let ccx = bcx_ccx(bcx);
1029 Call(bcx, ccx.upcalls.get_type_desc,
1030 [C_null(T_ptr(T_nil())), sz.val,
1031 align.val, C_uint(ccx, 1u + n_params), llfirstparam,
1032 C_uint(ccx, obj_params)]);
1036 trans_stack_local_derived_tydesc(bcx, sz.val, align.val, root,
1037 llfirstparam, n_params,
1040 bcx.fcx.derived_tydescs.insert(t, {lltydesc: v, escapes: escapes});
1044 type get_tydesc_result = {kind: tydesc_kind, result: result};
1046 fn get_tydesc(cx: @block_ctxt, t: ty::t, escapes: bool,
1047 storage: ty_param_storage, &static_ti: option::t<@tydesc_info>)
1048 -> get_tydesc_result {
1050 // Is the supplied type a type param? If so, return the passed-in tydesc.
1051 alt ty::type_param(bcx_tcx(cx), t) {
1053 if id < vec::len(cx.fcx.lltyparams) {
1054 ret {kind: tk_param,
1055 result: rslt(cx, cx.fcx.lltyparams[id].desc)};
1057 bcx_tcx(cx).sess.span_bug(cx.sp,
1058 "Unbound typaram in get_tydesc: " +
1060 ty_to_str(bcx_tcx(cx), t) +
1065 none. {/* fall through */ }
1068 // Does it contain a type param? If so, generate a derived tydesc.
1069 if ty::type_contains_params(bcx_tcx(cx), t) {
1070 ret {kind: tk_derived,
1071 result: get_derived_tydesc(cx, t, escapes, storage, static_ti)};
1073 // Otherwise, generate a tydesc if necessary, and return it.
1074 let info = get_static_tydesc(cx, t, [], false);
1075 static_ti = some::<@tydesc_info>(info);
1076 ret {kind: tk_static, result: rslt(cx, info.tydesc)};
1079 fn get_static_tydesc(cx: @block_ctxt, t: ty::t, ty_params: [uint],
1080 is_obj_body: bool) -> @tydesc_info {
1081 alt bcx_ccx(cx).tydescs.find(t) {
1082 some(info) { ret info; }
1084 bcx_ccx(cx).stats.n_static_tydescs += 1u;
1085 let info = declare_tydesc(cx.fcx.lcx, cx.sp, t, ty_params,
1087 bcx_ccx(cx).tydescs.insert(t, info);
1093 fn set_no_inline(f: ValueRef) {
1094 llvm::LLVMAddFunctionAttr(f,
1095 lib::llvm::LLVMNoInlineAttribute as
1096 lib::llvm::llvm::Attribute,
1100 // Tell LLVM to emit the information necessary to unwind the stack for the
1102 fn set_uwtable(f: ValueRef) {
1103 llvm::LLVMAddFunctionAttr(f,
1104 lib::llvm::LLVMUWTableAttribute as
1105 lib::llvm::llvm::Attribute,
1109 fn set_always_inline(f: ValueRef) {
1110 llvm::LLVMAddFunctionAttr(f,
1111 lib::llvm::LLVMAlwaysInlineAttribute as
1112 lib::llvm::llvm::Attribute,
1116 fn set_custom_stack_growth_fn(f: ValueRef) {
1117 // TODO: Remove this hack to work around the lack of u64 in the FFI.
1118 llvm::LLVMAddFunctionAttr(f, 0 as lib::llvm::llvm::Attribute, 1u);
1121 fn set_glue_inlining(cx: @local_ctxt, f: ValueRef, t: ty::t) {
1122 if ty::type_is_structural(cx.ccx.tcx, t) {
1124 } else { set_always_inline(f); }
1128 // Generates the declaration for (but doesn't emit) a type descriptor.
1129 fn declare_tydesc(cx: @local_ctxt, sp: span, t: ty::t, ty_params: [uint],
1130 is_obj_body: bool) ->
1132 log(debug, "+++ declare_tydesc " + ty_to_str(cx.ccx.tcx, t));
1136 if check type_has_static_size(ccx, t) {
1137 let llty = type_of(ccx, sp, t);
1138 llsize = llsize_of(ccx, llty);
1139 llalign = llalign_of(ccx, llty);
1141 // These will be overwritten as the derived tydesc is generated, so
1142 // we create placeholder values.
1144 llsize = C_int(ccx, 0);
1145 llalign = C_int(ccx, 0);
1148 if cx.ccx.sess.get_opts().debuginfo {
1149 name = mangle_internal_name_by_type_only(cx.ccx, t, "tydesc");
1150 name = sanitize(name);
1151 } else { name = mangle_internal_name_by_seq(cx.ccx, "tydesc"); }
1155 llvm::LLVMAddGlobal(ccx.llmod, ccx.tydesc_type, buf)
1162 mutable take_glue: none::<ValueRef>,
1163 mutable drop_glue: none::<ValueRef>,
1164 mutable free_glue: none::<ValueRef>,
1165 mutable cmp_glue: none::<ValueRef>,
1166 ty_params: ty_params,
1167 is_obj_body: is_obj_body};
1168 log(debug, "--- declare_tydesc " + ty_to_str(cx.ccx.tcx, t));
1172 type glue_helper = fn(@block_ctxt, ValueRef, ty::t);
1174 fn declare_generic_glue(cx: @local_ctxt, t: ty::t, llfnty: TypeRef, name: str)
1178 if cx.ccx.sess.get_opts().debuginfo {
1179 fn_nm = mangle_internal_name_by_type_only(cx.ccx, t, "glue_" + name);
1180 fn_nm = sanitize(fn_nm);
1181 } else { fn_nm = mangle_internal_name_by_seq(cx.ccx, "glue_" + name); }
1182 let llfn = decl_cdecl_fn(cx.ccx.llmod, fn_nm, llfnty);
1183 set_glue_inlining(cx, llfn, t);
1187 // FIXME: was this causing the leak?
1188 fn make_generic_glue_inner(cx: @local_ctxt, sp: span, t: ty::t,
1189 llfn: ValueRef, helper: glue_helper,
1190 ty_params: [uint]) -> ValueRef {
1191 let fcx = new_fn_ctxt(cx, sp, llfn);
1192 llvm::LLVMSetLinkage(llfn,
1193 lib::llvm::LLVMInternalLinkage as llvm::Linkage);
1194 cx.ccx.stats.n_glues_created += 1u;
1195 // Any nontrivial glue is with values passed *by alias*; this is a
1196 // requirement since in many contexts glue is invoked indirectly and
1197 // the caller has no idea if it's dealing with something that can be
1202 if check type_has_static_size(ccx, t) {
1203 T_ptr(type_of(ccx, sp, t))
1204 } else { T_ptr(T_i8()) };
1206 let ty_param_count = vec::len::<uint>(ty_params);
1207 let lltyparams = llvm::LLVMGetParam(llfn, 2u);
1208 let load_env_bcx = new_raw_block_ctxt(fcx, fcx.llloadenv);
1209 let lltydescs = [mutable];
1211 while p < ty_param_count {
1212 let llparam = GEPi(load_env_bcx, lltyparams, [p as int]);
1213 llparam = Load(load_env_bcx, llparam);
1214 vec::grow_set(lltydescs, ty_params[p], 0 as ValueRef, llparam);
1218 fcx.lltyparams = vec::map_mut(lltydescs, {|d| {desc: d, dicts: none}});
1220 let bcx = new_top_block_ctxt(fcx);
1221 let lltop = bcx.llbb;
1222 let llrawptr0 = llvm::LLVMGetParam(llfn, 3u);
1223 let llval0 = BitCast(bcx, llrawptr0, llty);
1224 helper(bcx, llval0, t);
1225 finish_fn(fcx, lltop);
1229 fn make_generic_glue(cx: @local_ctxt, sp: span, t: ty::t, llfn: ValueRef,
1230 helper: glue_helper, ty_params: [uint], name: str) ->
1232 if !cx.ccx.sess.get_opts().stats {
1233 ret make_generic_glue_inner(cx, sp, t, llfn, helper, ty_params);
1236 let start = time::get_time();
1237 let llval = make_generic_glue_inner(cx, sp, t, llfn, helper, ty_params);
1238 let end = time::get_time();
1239 log_fn_time(cx.ccx, "glue " + name + " " + ty_to_short_str(cx.ccx.tcx, t),
1244 fn emit_tydescs(ccx: @crate_ctxt) {
1245 ccx.tydescs.items {|key, val|
1246 let glue_fn_ty = T_ptr(T_glue_fn(ccx));
1247 let cmp_fn_ty = T_ptr(T_cmp_glue_fn(ccx));
1251 none. { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
1252 some(v) { ccx.stats.n_real_glues += 1u; v }
1256 none. { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
1257 some(v) { ccx.stats.n_real_glues += 1u; v }
1261 none. { ccx.stats.n_null_glues += 1u; C_null(glue_fn_ty) }
1262 some(v) { ccx.stats.n_real_glues += 1u; v }
1266 none. { ccx.stats.n_null_glues += 1u; C_null(cmp_fn_ty) }
1267 some(v) { ccx.stats.n_real_glues += 1u; v }
1270 let shape = shape::shape_of(ccx, key, ti.ty_params,
1273 llvm::LLVMConstPointerCast(ccx.shape_cx.llshapetables,
1277 C_named_struct(ccx.tydesc_type,
1278 [C_null(T_ptr(T_ptr(ccx.tydesc_type))),
1281 take_glue, // take_glue
1282 drop_glue, // drop_glue
1283 free_glue, // free_glue
1284 C_null(T_ptr(T_i8())), // unused
1285 C_null(glue_fn_ty), // sever_glue
1286 C_null(glue_fn_ty), // mark_glue
1287 C_null(glue_fn_ty), // unused
1288 cmp_glue, // cmp_glue
1289 C_shape(ccx, shape), // shape
1290 shape_tables, // shape_tables
1291 C_int(ccx, 0), // n_params
1292 C_int(ccx, 0)]); // n_obj_params
1294 let gvar = ti.tydesc;
1295 llvm::LLVMSetInitializer(gvar, tydesc);
1296 llvm::LLVMSetGlobalConstant(gvar, True);
1297 llvm::LLVMSetLinkage(gvar,
1298 lib::llvm::LLVMInternalLinkage as llvm::Linkage);
1302 fn make_take_glue(cx: @block_ctxt, v: ValueRef, t: ty::t) {
1305 let tcx = bcx_tcx(cx);
1306 // NB: v is an *alias* of type t here, not a direct value.
1307 bcx = alt ty::struct(tcx, t) {
1309 incr_refcnt_of_boxed(bcx, Load(bcx, v))
1312 check trans_uniq::type_is_unique_box(bcx, t);
1313 let r = trans_uniq::duplicate(bcx, Load(bcx, v), t);
1314 Store(r.bcx, r.val, v);
1317 ty::ty_vec(_) | ty::ty_str. {
1318 let r = tvec::duplicate(bcx, Load(bcx, v), t);
1319 Store(r.bcx, r.val, v);
1323 // sendable type descriptors are basically unique pointers,
1324 // they must be cloned when copied:
1325 let r = Load(bcx, v);
1326 let s = Call(bcx, bcx_ccx(bcx).upcalls.create_shared_type_desc, [r]);
1330 ty::ty_native_fn(_, _) | ty::ty_fn(_) {
1331 trans_closure::make_fn_glue(bcx, v, t, take_ty)
1333 ty::ty_opaque_closure. {
1334 trans_closure::call_opaque_closure_glue(
1335 bcx, v, abi::tydesc_field_take_glue)
1337 _ when ty::type_is_structural(bcx_tcx(bcx), t) {
1338 iter_structural_ty(bcx, v, t, take_ty)
1346 fn incr_refcnt_of_boxed(cx: @block_ctxt, box_ptr: ValueRef) -> @block_ctxt {
1347 let ccx = bcx_ccx(cx);
1349 GEPi(cx, box_ptr, [0, abi::box_rc_field_refcnt]);
1350 let rc = Load(cx, rc_ptr);
1351 rc = Add(cx, rc, C_int(ccx, 1));
1352 Store(cx, rc, rc_ptr);
1356 fn free_box(bcx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1357 ret alt ty::struct(bcx_tcx(bcx), t) {
1358 ty::ty_box(body_mt) {
1359 let v = PointerCast(bcx, v, type_of_1(bcx, t));
1360 let body = GEPi(bcx, v, [0, abi::box_rc_field_body]);
1361 let bcx = drop_ty(bcx, body, body_mt.ty);
1362 trans_free_if_not_gc(bcx, v)
1365 _ { fail "free_box invoked with non-box type"; }
1369 fn make_free_glue(bcx: @block_ctxt, v: ValueRef, t: ty::t) {
1370 // v is a pointer to the actual box component of the type here. The
1371 // ValueRef will have the wrong type here (make_generic_glue is casting
1372 // everything to a pointer to the type that the glue acts on).
1373 let bcx = alt ty::struct(bcx_tcx(bcx), t) {
1374 ty::ty_box(body_mt) {
1377 ty::ty_uniq(content_mt) {
1378 check trans_uniq::type_is_unique_box(bcx, t);
1379 let v = PointerCast(bcx, v, type_of_1(bcx, t));
1380 trans_uniq::make_free_glue(bcx, v, t)
1382 ty::ty_vec(_) | ty::ty_str. {
1383 tvec::make_free_glue(bcx, PointerCast(bcx, v, type_of_1(bcx, t)), t)
1386 // Call through the obj's own fields-drop glue first.
1387 // Then free the body.
1388 let ccx = bcx_ccx(bcx);
1389 let llbox_ty = T_opaque_obj_ptr(ccx);
1390 let b = PointerCast(bcx, v, llbox_ty);
1391 let body = GEPi(bcx, b, [0, abi::box_rc_field_body]);
1393 GEPi(bcx, body, [0, abi::obj_body_elt_tydesc]);
1394 let tydesc = Load(bcx, tydescptr);
1396 call_tydesc_glue_full(bcx, body, tydesc,
1397 abi::tydesc_field_drop_glue, ti);
1398 trans_free_if_not_gc(bcx, b)
1401 // sendable type descriptors are basically unique pointers,
1402 // they must be freed.
1403 trans_shared_free(bcx, v)
1405 ty::ty_native_fn(_, _) | ty::ty_fn(_) {
1406 trans_closure::make_fn_glue(bcx, v, t, free_ty)
1408 ty::ty_opaque_closure. {
1409 trans_closure::call_opaque_closure_glue(
1410 bcx, v, abi::tydesc_field_free_glue)
1417 fn make_drop_glue(bcx: @block_ctxt, v0: ValueRef, t: ty::t) {
1418 // NB: v0 is an *alias* of type t here, not a direct value.
1419 let ccx = bcx_ccx(bcx);
1421 alt ty::struct(ccx.tcx, t) {
1422 ty::ty_box(_) { decr_refcnt_maybe_free(bcx, Load(bcx, v0), t) }
1423 ty::ty_uniq(_) | ty::ty_vec(_) | ty::ty_str. | ty::ty_send_type. {
1424 free_ty(bcx, Load(bcx, v0), t)
1428 GEPi(bcx, v0, [0, abi::obj_field_box]);
1429 decr_refcnt_maybe_free(bcx, Load(bcx, box_cell), t)
1431 ty::ty_res(did, inner, tps) {
1432 trans_res_drop(bcx, v0, did, inner, tps)
1434 ty::ty_native_fn(_, _) | ty::ty_fn(_) {
1435 trans_closure::make_fn_glue(bcx, v0, t, drop_ty)
1437 ty::ty_opaque_closure. {
1438 trans_closure::call_opaque_closure_glue(
1439 bcx, v0, abi::tydesc_field_drop_glue)
1442 if ty::type_needs_drop(ccx.tcx, t) &&
1443 ty::type_is_structural(ccx.tcx, t) {
1444 iter_structural_ty(bcx, v0, t, drop_ty)
1451 fn trans_res_drop(cx: @block_ctxt, rs: ValueRef, did: ast::def_id,
1452 inner_t: ty::t, tps: [ty::t]) -> @block_ctxt {
1453 let ccx = bcx_ccx(cx);
1454 let inner_t_s = ty::substitute_type_params(ccx.tcx, tps, inner_t);
1455 let tup_ty = ty::mk_tup(ccx.tcx, [ty::mk_int(ccx.tcx), inner_t_s]);
1456 let drop_cx = new_sub_block_ctxt(cx, "drop res");
1457 let next_cx = new_sub_block_ctxt(cx, "next");
1460 check type_is_tup_like(cx, tup_ty);
1461 let drop_flag = GEP_tup_like(cx, tup_ty, rs, [0, 0]);
1462 let cx = drop_flag.bcx;
1463 let null_test = IsNull(cx, Load(cx, drop_flag.val));
1464 CondBr(cx, null_test, next_cx.llbb, drop_cx.llbb);
1467 check type_is_tup_like(cx, tup_ty);
1468 let val = GEP_tup_like(cx, tup_ty, rs, [0, 1]);
1470 // Find and call the actual destructor.
1471 let dtor_addr = trans_common::get_res_dtor(ccx, cx.sp, did, inner_t);
1472 let args = [cx.fcx.llretptr, null_env_ptr(cx)];
1473 for tp: ty::t in tps {
1474 let ti: option::t<@tydesc_info> = none;
1475 let td = get_tydesc(cx, tp, false, tps_normal, ti).result;
1479 // Kludge to work around the fact that we know the precise type of the
1480 // value here, but the dtor expects a type that still has opaque pointers
1481 // for type variables.
1482 let val_llty = lib::llvm::fn_ty_param_tys
1483 (llvm::LLVMGetElementType
1484 (llvm::LLVMTypeOf(dtor_addr)))[vec::len(args)];
1485 let val_cast = BitCast(cx, val.val, val_llty);
1486 Call(cx, dtor_addr, args + [val_cast]);
1488 cx = drop_ty(cx, val.val, inner_t_s);
1489 // FIXME #1184: Resource flag is larger than necessary
1490 Store(cx, C_int(ccx, 0), drop_flag.val);
1491 Br(cx, next_cx.llbb);
1495 fn decr_refcnt_maybe_free(cx: @block_ctxt, box_ptr: ValueRef, t: ty::t)
1497 let ccx = bcx_ccx(cx);
1498 let rc_adj_cx = new_sub_block_ctxt(cx, "rc--");
1499 let free_cx = new_sub_block_ctxt(cx, "free");
1500 let next_cx = new_sub_block_ctxt(cx, "next");
1501 let llbox_ty = T_opaque_obj_ptr(ccx);
1502 let box_ptr = PointerCast(cx, box_ptr, llbox_ty);
1503 let null_test = IsNull(cx, box_ptr);
1504 CondBr(cx, null_test, next_cx.llbb, rc_adj_cx.llbb);
1506 GEPi(rc_adj_cx, box_ptr, [0, abi::box_rc_field_refcnt]);
1507 let rc = Load(rc_adj_cx, rc_ptr);
1508 rc = Sub(rc_adj_cx, rc, C_int(ccx, 1));
1509 Store(rc_adj_cx, rc, rc_ptr);
1510 let zero_test = ICmp(rc_adj_cx, lib::llvm::LLVMIntEQ, C_int(ccx, 0), rc);
1511 CondBr(rc_adj_cx, zero_test, free_cx.llbb, next_cx.llbb);
1512 let free_cx = free_ty(free_cx, box_ptr, t);
1513 Br(free_cx, next_cx.llbb);
1518 // Structural comparison: a rather involved form of glue.
1519 fn maybe_name_value(cx: @crate_ctxt, v: ValueRef, s: str) {
1520 if cx.sess.get_opts().save_temps {
1521 let _: () = str::as_buf(s, {|buf| llvm::LLVMSetValueName(v, buf) });
1526 // Used only for creating scalar comparison glue.
1527 tag scalar_type { nil_type; signed_int; unsigned_int; floating_point; }
1530 fn compare_scalar_types(cx: @block_ctxt, lhs: ValueRef, rhs: ValueRef,
1531 t: ty::t, op: ast::binop) -> result {
1532 let f = bind compare_scalar_values(cx, lhs, rhs, _, op);
1534 alt ty::struct(bcx_tcx(cx), t) {
1535 ty::ty_nil. { ret rslt(cx, f(nil_type)); }
1536 ty::ty_bool. | ty::ty_ptr(_) { ret rslt(cx, f(unsigned_int)); }
1537 ty::ty_int(_) { ret rslt(cx, f(signed_int)); }
1538 ty::ty_uint(_) { ret rslt(cx, f(unsigned_int)); }
1539 ty::ty_float(_) { ret rslt(cx, f(floating_point)); }
1541 ret rslt(trans_fail(cx, none,
1542 "attempt to compare values of type type"),
1546 let cx = trans_fail(cx, none::<span>,
1547 "attempt to compare values of type native");
1548 ret rslt(cx, C_nil());
1551 // Should never get here, because t is scalar.
1552 bcx_ccx(cx).sess.bug("non-scalar type passed to \
1553 compare_scalar_types");
1559 // A helper function to do the actual comparison of scalar values.
1560 fn compare_scalar_values(cx: @block_ctxt, lhs: ValueRef, rhs: ValueRef,
1561 nt: scalar_type, op: ast::binop) -> ValueRef {
1564 // We don't need to do actual comparisons for nil.
1565 // () == () holds but () < () does not.
1567 ast::eq. | ast::le. | ast::ge. { ret C_bool(true); }
1568 ast::ne. | ast::lt. | ast::gt. { ret C_bool(false); }
1573 ast::eq. { lib::llvm::LLVMRealOEQ }
1574 ast::ne. { lib::llvm::LLVMRealUNE }
1575 ast::lt. { lib::llvm::LLVMRealOLT }
1576 ast::le. { lib::llvm::LLVMRealOLE }
1577 ast::gt. { lib::llvm::LLVMRealOGT }
1578 ast::ge. { lib::llvm::LLVMRealOGE }
1580 ret FCmp(cx, cmp, lhs, rhs);
1584 ast::eq. { lib::llvm::LLVMIntEQ }
1585 ast::ne. { lib::llvm::LLVMIntNE }
1586 ast::lt. { lib::llvm::LLVMIntSLT }
1587 ast::le. { lib::llvm::LLVMIntSLE }
1588 ast::gt. { lib::llvm::LLVMIntSGT }
1589 ast::ge. { lib::llvm::LLVMIntSGE }
1591 ret ICmp(cx, cmp, lhs, rhs);
1595 ast::eq. { lib::llvm::LLVMIntEQ }
1596 ast::ne. { lib::llvm::LLVMIntNE }
1597 ast::lt. { lib::llvm::LLVMIntULT }
1598 ast::le. { lib::llvm::LLVMIntULE }
1599 ast::gt. { lib::llvm::LLVMIntUGT }
1600 ast::ge. { lib::llvm::LLVMIntUGE }
1602 ret ICmp(cx, cmp, lhs, rhs);
1607 type val_pair_fn = fn(@block_ctxt, ValueRef, ValueRef) -> @block_ctxt;
1608 type val_and_ty_fn = fn(@block_ctxt, ValueRef, ty::t) -> @block_ctxt;
1610 fn load_inbounds(cx: @block_ctxt, p: ValueRef, idxs: [int]) -> ValueRef {
1611 ret Load(cx, GEPi(cx, p, idxs));
1614 fn store_inbounds(cx: @block_ctxt, v: ValueRef, p: ValueRef,
1616 Store(cx, v, GEPi(cx, p, idxs));
1619 // Iterates through the elements of a structural type.
1620 fn iter_structural_ty(cx: @block_ctxt, av: ValueRef, t: ty::t,
1621 f: val_and_ty_fn) -> @block_ctxt {
1622 fn iter_boxpp(cx: @block_ctxt, box_cell: ValueRef, f: val_and_ty_fn) ->
1624 let box_ptr = Load(cx, box_cell);
1625 let tnil = ty::mk_nil(bcx_tcx(cx));
1626 let tbox = ty::mk_imm_box(bcx_tcx(cx), tnil);
1627 let inner_cx = new_sub_block_ctxt(cx, "iter box");
1628 let next_cx = new_sub_block_ctxt(cx, "next");
1629 let null_test = IsNull(cx, box_ptr);
1630 CondBr(cx, null_test, next_cx.llbb, inner_cx.llbb);
1631 let inner_cx = f(inner_cx, box_cell, tbox);
1632 Br(inner_cx, next_cx.llbb);
1636 fn iter_variant(cx: @block_ctxt, a_tup: ValueRef,
1637 variant: ty::variant_info, tps: [ty::t], tid: ast::def_id,
1638 f: val_and_ty_fn) -> @block_ctxt {
1639 if vec::len::<ty::t>(variant.args) == 0u { ret cx; }
1640 let fn_ty = variant.ctor_ty;
1641 let ccx = bcx_ccx(cx);
1643 alt ty::struct(ccx.tcx, fn_ty) {
1644 ty::ty_fn({inputs: args, _}) {
1646 let v_id = variant.id;
1647 for a: ty::arg in args {
1648 check (valid_variant_index(j, cx, tid, v_id));
1649 let rslt = GEP_tag(cx, a_tup, tid, v_id, tps, j);
1650 let llfldp_a = rslt.val;
1652 let ty_subst = ty::substitute_type_params(ccx.tcx, tps, a.ty);
1653 cx = f(cx, llfldp_a, ty_subst);
1662 Typestate constraint that shows the unimpl case doesn't happen?
1665 alt ty::struct(bcx_tcx(cx), t) {
1666 ty::ty_rec(fields) {
1668 for fld: ty::field in fields {
1670 check type_is_tup_like(cx, t);
1671 let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, t, av, [0, i]);
1672 cx = f(bcx, llfld_a, fld.mt.ty);
1680 check type_is_tup_like(cx, t);
1681 let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, t, av, [0, i]);
1682 cx = f(bcx, llfld_a, arg);
1686 ty::ty_res(_, inner, tps) {
1687 let tcx = bcx_tcx(cx);
1688 let inner1 = ty::substitute_type_params(tcx, tps, inner);
1689 let inner_t_s = ty::substitute_type_params(tcx, tps, inner);
1690 let tup_t = ty::mk_tup(tcx, [ty::mk_int(tcx), inner_t_s]);
1692 check type_is_tup_like(cx, tup_t);
1693 let {bcx: bcx, val: llfld_a} = GEP_tup_like(cx, tup_t, av, [0, 1]);
1694 ret f(bcx, llfld_a, inner1);
1696 ty::ty_tag(tid, tps) {
1697 let variants = ty::tag_variants(bcx_tcx(cx), tid);
1698 let n_variants = vec::len(*variants);
1700 // Cast the tags to types we can GEP into.
1701 if n_variants == 1u {
1702 ret iter_variant(cx, av, variants[0], tps, tid, f);
1705 let ccx = bcx_ccx(cx);
1706 let lltagty = T_opaque_tag_ptr(ccx);
1707 let av_tag = PointerCast(cx, av, lltagty);
1708 let lldiscrim_a_ptr = GEPi(cx, av_tag, [0, 0]);
1709 let llunion_a_ptr = GEPi(cx, av_tag, [0, 1]);
1710 let lldiscrim_a = Load(cx, lldiscrim_a_ptr);
1712 // NB: we must hit the discriminant first so that structural
1713 // comparison know not to proceed when the discriminants differ.
1714 cx = f(cx, lldiscrim_a_ptr, ty::mk_int(bcx_tcx(cx)));
1715 let unr_cx = new_sub_block_ctxt(cx, "tag-iter-unr");
1716 Unreachable(unr_cx);
1717 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb, n_variants);
1718 let next_cx = new_sub_block_ctxt(cx, "tag-iter-next");
1720 for variant: ty::variant_info in *variants {
1722 new_sub_block_ctxt(cx,
1723 "tag-iter-variant-" +
1724 uint::to_str(i, 10u));
1725 AddCase(llswitch, C_int(ccx, i as int), variant_cx.llbb);
1727 iter_variant(variant_cx, llunion_a_ptr, variant, tps, tid, f);
1728 Br(variant_cx, next_cx.llbb);
1734 let box_cell_a = GEPi(cx, av, [0, abi::obj_field_box]);
1735 ret iter_boxpp(cx, box_cell_a, f);
1737 _ { bcx_ccx(cx).sess.unimpl("type in iter_structural_ty"); }
1742 fn lazily_emit_all_tydesc_glue(cx: @block_ctxt,
1743 static_ti: option::t<@tydesc_info>) {
1744 lazily_emit_tydesc_glue(cx, abi::tydesc_field_take_glue, static_ti);
1745 lazily_emit_tydesc_glue(cx, abi::tydesc_field_drop_glue, static_ti);
1746 lazily_emit_tydesc_glue(cx, abi::tydesc_field_free_glue, static_ti);
1747 lazily_emit_tydesc_glue(cx, abi::tydesc_field_cmp_glue, static_ti);
1750 fn lazily_emit_all_generic_info_tydesc_glues(cx: @block_ctxt,
1752 for ti: option::t<@tydesc_info> in gi.static_tis {
1753 lazily_emit_all_tydesc_glue(cx, ti);
1757 fn lazily_emit_tydesc_glue(cx: @block_ctxt, field: int,
1758 static_ti: option::t<@tydesc_info>) {
1762 if field == abi::tydesc_field_take_glue {
1766 #debug("+++ lazily_emit_tydesc_glue TAKE %s",
1767 ty_to_str(bcx_tcx(cx), ti.ty));
1768 let lcx = cx.fcx.lcx;
1770 declare_generic_glue(lcx, ti.ty, T_glue_fn(lcx.ccx),
1772 ti.take_glue = some::<ValueRef>(glue_fn);
1773 make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
1775 ti.ty_params, "take");
1776 #debug("--- lazily_emit_tydesc_glue TAKE %s",
1777 ty_to_str(bcx_tcx(cx), ti.ty));
1780 } else if field == abi::tydesc_field_drop_glue {
1784 #debug("+++ lazily_emit_tydesc_glue DROP %s",
1785 ty_to_str(bcx_tcx(cx), ti.ty));
1786 let lcx = cx.fcx.lcx;
1788 declare_generic_glue(lcx, ti.ty, T_glue_fn(lcx.ccx),
1790 ti.drop_glue = some::<ValueRef>(glue_fn);
1791 make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
1793 ti.ty_params, "drop");
1794 #debug("--- lazily_emit_tydesc_glue DROP %s",
1795 ty_to_str(bcx_tcx(cx), ti.ty));
1798 } else if field == abi::tydesc_field_free_glue {
1802 #debug("+++ lazily_emit_tydesc_glue FREE %s",
1803 ty_to_str(bcx_tcx(cx), ti.ty));
1804 let lcx = cx.fcx.lcx;
1806 declare_generic_glue(lcx, ti.ty, T_glue_fn(lcx.ccx),
1808 ti.free_glue = some::<ValueRef>(glue_fn);
1809 make_generic_glue(lcx, cx.sp, ti.ty, glue_fn,
1811 ti.ty_params, "free");
1812 #debug("--- lazily_emit_tydesc_glue FREE %s",
1813 ty_to_str(bcx_tcx(cx), ti.ty));
1816 } else if field == abi::tydesc_field_cmp_glue {
1820 #debug("+++ lazily_emit_tydesc_glue CMP %s",
1821 ty_to_str(bcx_tcx(cx), ti.ty));
1822 ti.cmp_glue = some(bcx_ccx(cx).upcalls.cmp_type);
1823 #debug("--- lazily_emit_tydesc_glue CMP %s",
1824 ty_to_str(bcx_tcx(cx), ti.ty));
1832 fn call_tydesc_glue_full(cx: @block_ctxt, v: ValueRef, tydesc: ValueRef,
1833 field: int, static_ti: option::t<@tydesc_info>) {
1834 lazily_emit_tydesc_glue(cx, field, static_ti);
1836 let static_glue_fn = none;
1838 none. {/* no-op */ }
1840 if field == abi::tydesc_field_take_glue {
1841 static_glue_fn = sti.take_glue;
1842 } else if field == abi::tydesc_field_drop_glue {
1843 static_glue_fn = sti.drop_glue;
1844 } else if field == abi::tydesc_field_free_glue {
1845 static_glue_fn = sti.free_glue;
1850 let llrawptr = PointerCast(cx, v, T_ptr(T_i8()));
1852 GEPi(cx, tydesc, [0, abi::tydesc_field_first_param]);
1853 lltydescs = Load(cx, lltydescs);
1856 alt static_glue_fn {
1858 let llfnptr = GEPi(cx, tydesc, [0, field]);
1859 llfn = Load(cx, llfnptr);
1861 some(sgf) { llfn = sgf; }
1864 Call(cx, llfn, [C_null(T_ptr(T_nil())), C_null(T_ptr(T_nil())),
1865 lltydescs, llrawptr]);
1868 fn call_tydesc_glue(cx: @block_ctxt, v: ValueRef, t: ty::t, field: int) ->
1870 let ti: option::t<@tydesc_info> = none::<@tydesc_info>;
1871 let {bcx: bcx, val: td} = get_tydesc(cx, t, false, tps_normal, ti).result;
1872 call_tydesc_glue_full(bcx, v, td, field, ti);
1876 fn call_cmp_glue(cx: @block_ctxt, lhs: ValueRef, rhs: ValueRef, t: ty::t,
1877 llop: ValueRef) -> result {
1878 // We can't use call_tydesc_glue_full() and friends here because compare
1879 // glue has a special signature.
1883 let r = spill_if_immediate(bcx, lhs, t);
1886 r = spill_if_immediate(bcx, rhs, t);
1890 let llrawlhsptr = BitCast(bcx, lllhs, T_ptr(T_i8()));
1891 let llrawrhsptr = BitCast(bcx, llrhs, T_ptr(T_i8()));
1892 let ti = none::<@tydesc_info>;
1893 r = get_tydesc(bcx, t, false, tps_normal, ti).result;
1894 let lltydesc = r.val;
1896 lazily_emit_tydesc_glue(bcx, abi::tydesc_field_cmp_glue, ti);
1898 GEPi(bcx, lltydesc, [0, abi::tydesc_field_first_param]);
1899 lltydescs = Load(bcx, lltydescs);
1905 GEPi(bcx, lltydesc, [0, abi::tydesc_field_cmp_glue]);
1906 llfn = Load(bcx, llfnptr);
1908 some(sti) { llfn = option::get(sti.cmp_glue); }
1911 let llcmpresultptr = alloca(bcx, T_i1());
1912 Call(bcx, llfn, [llcmpresultptr, lltydesc, lltydescs,
1913 llrawlhsptr, llrawrhsptr, llop]);
1914 ret rslt(bcx, Load(bcx, llcmpresultptr));
1917 fn take_ty(cx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1918 if ty::type_needs_drop(bcx_tcx(cx), t) {
1919 ret call_tydesc_glue(cx, v, t, abi::tydesc_field_take_glue);
1924 fn drop_ty(cx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1925 if ty::type_needs_drop(bcx_tcx(cx), t) {
1926 ret call_tydesc_glue(cx, v, t, abi::tydesc_field_drop_glue);
1931 fn drop_ty_immediate(bcx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1932 alt ty::struct(bcx_tcx(bcx), t) {
1933 ty::ty_uniq(_) | ty::ty_vec(_) | ty::ty_str. {
1934 ret free_ty(bcx, v, t);
1936 ty::ty_box(_) { ret decr_refcnt_maybe_free(bcx, v, t); }
1940 fn take_ty_immediate(bcx: @block_ctxt, v: ValueRef, t: ty::t) -> result {
1941 alt ty::struct(bcx_tcx(bcx), t) {
1942 ty::ty_box(_) { ret rslt(incr_refcnt_of_boxed(bcx, v), v); }
1944 check trans_uniq::type_is_unique_box(bcx, t);
1945 ret trans_uniq::duplicate(bcx, v, t);
1947 ty::ty_str. | ty::ty_vec(_) { ret tvec::duplicate(bcx, v, t); }
1948 _ { ret rslt(bcx, v); }
1952 fn free_ty(cx: @block_ctxt, v: ValueRef, t: ty::t) -> @block_ctxt {
1953 if ty::type_needs_drop(bcx_tcx(cx), t) {
1954 ret call_tydesc_glue(cx, v, t, abi::tydesc_field_free_glue);
1959 fn call_memmove(cx: @block_ctxt, dst: ValueRef, src: ValueRef,
1960 n_bytes: ValueRef) -> result {
1961 // TODO: Provide LLVM with better alignment information when the alignment
1962 // is statically known (it must be nothing more than a constant int, or
1963 // LLVM complains -- not even a constant element of a tydesc works).
1965 let ccx = bcx_ccx(cx);
1966 let key = alt ccx.sess.get_targ_cfg().arch {
1967 session::arch_x86. | session::arch_arm. { "llvm.memmove.p0i8.p0i8.i32" }
1968 session::arch_x86_64. { "llvm.memmove.p0i8.p0i8.i64" }
1970 let i = ccx.intrinsics;
1971 assert (i.contains_key(key));
1972 let memmove = i.get(key);
1973 let src_ptr = PointerCast(cx, src, T_ptr(T_i8()));
1974 let dst_ptr = PointerCast(cx, dst, T_ptr(T_i8()));
1975 // FIXME #1184: Resource flag is larger than necessary
1976 let size = IntCast(cx, n_bytes, ccx.int_type);
1977 let align = C_i32(1i32);
1978 let volatile = C_bool(false);
1979 let ret_val = Call(cx, memmove, [dst_ptr, src_ptr, size,
1981 ret rslt(cx, ret_val);
1984 fn call_bzero(cx: @block_ctxt, dst: ValueRef, n_bytes: ValueRef,
1985 align_bytes: ValueRef) -> result {
1986 // FIXME: switch to the 64-bit variant when on such a platform.
1987 let ccx = bcx_ccx(cx);
1988 let i = ccx.intrinsics;
1989 assert (i.contains_key("llvm.memset.p0i8.i32"));
1990 let memset = i.get("llvm.memset.p0i8.i32");
1991 let dst_ptr = PointerCast(cx, dst, T_ptr(T_i8()));
1992 let size = IntCast(cx, n_bytes, T_i32());
1994 if lib::llvm::llvm::LLVMIsConstant(align_bytes) == True {
1995 IntCast(cx, align_bytes, T_i32())
1996 } else { IntCast(cx, C_int(ccx, 0), T_i32()) };
1997 let volatile = C_bool(false);
1999 Call(cx, memset, [dst_ptr, C_u8(0u), size, align, volatile]));
2002 fn memmove_ty(cx: @block_ctxt, dst: ValueRef, src: ValueRef, t: ty::t) ->
2004 let ccx = bcx_ccx(cx);
2005 if check type_has_static_size(ccx, t) {
2006 if ty::type_is_structural(bcx_tcx(cx), t) {
2008 let llsz = llsize_of(ccx, type_of(ccx, sp, t));
2009 ret call_memmove(cx, dst, src, llsz).bcx;
2011 Store(cx, Load(cx, src), dst);
2015 let llsz = size_of(cx, t);
2016 ret call_memmove(llsz.bcx, dst, src, llsz.val).bcx;
2019 tag copy_action { INIT; DROP_EXISTING; }
2021 // These are the types that are passed by pointer.
2022 fn type_is_structural_or_param(tcx: ty::ctxt, t: ty::t) -> bool {
2023 if ty::type_is_structural(tcx, t) { ret true; }
2024 alt ty::struct(tcx, t) {
2025 ty::ty_param(_, _) { ret true; }
2030 fn copy_val(cx: @block_ctxt, action: copy_action, dst: ValueRef,
2031 src: ValueRef, t: ty::t) -> @block_ctxt {
2032 if action == DROP_EXISTING &&
2033 (type_is_structural_or_param(bcx_tcx(cx), t) ||
2034 ty::type_is_unique(bcx_tcx(cx), t)) {
2035 let do_copy_cx = new_sub_block_ctxt(cx, "do_copy");
2036 let next_cx = new_sub_block_ctxt(cx, "next");
2037 let dstcmp = load_if_immediate(cx, dst, t);
2038 let self_assigning =
2039 ICmp(cx, lib::llvm::LLVMIntNE,
2040 PointerCast(cx, dstcmp, val_ty(src)), src);
2041 CondBr(cx, self_assigning, do_copy_cx.llbb, next_cx.llbb);
2042 do_copy_cx = copy_val_no_check(do_copy_cx, action, dst, src, t);
2043 Br(do_copy_cx, next_cx.llbb);
2046 ret copy_val_no_check(cx, action, dst, src, t);
2049 fn copy_val_no_check(bcx: @block_ctxt, action: copy_action, dst: ValueRef,
2050 src: ValueRef, t: ty::t) -> @block_ctxt {
2051 let ccx = bcx_ccx(bcx), bcx = bcx;
2052 if ty::type_is_scalar(ccx.tcx, t) || ty::type_is_native(ccx.tcx, t) {
2053 Store(bcx, src, dst);
2056 if ty::type_is_nil(ccx.tcx, t) || ty::type_is_bot(ccx.tcx, t) { ret bcx; }
2057 if ty::type_is_boxed(ccx.tcx, t) || ty::type_is_vec(ccx.tcx, t) ||
2058 ty::type_is_unique_box(ccx.tcx, t) {
2059 if action == DROP_EXISTING { bcx = drop_ty(bcx, dst, t); }
2060 Store(bcx, src, dst);
2061 ret take_ty(bcx, dst, t);
2063 if type_is_structural_or_param(ccx.tcx, t) {
2064 if action == DROP_EXISTING { bcx = drop_ty(bcx, dst, t); }
2065 bcx = memmove_ty(bcx, dst, src, t);
2066 ret take_ty(bcx, dst, t);
2068 ccx.sess.bug("unexpected type in trans::copy_val_no_check: " +
2069 ty_to_str(ccx.tcx, t));
2073 // This works like copy_val, except that it deinitializes the source.
2074 // Since it needs to zero out the source, src also needs to be an lval.
2075 // FIXME: We always zero out the source. Ideally we would detect the
2076 // case where a variable is always deinitialized by block exit and thus
2077 // doesn't need to be dropped.
2078 fn move_val(cx: @block_ctxt, action: copy_action, dst: ValueRef,
2079 src: lval_result, t: ty::t) -> @block_ctxt {
2080 let src_val = src.val;
2081 let tcx = bcx_tcx(cx), cx = cx;
2082 if ty::type_is_scalar(tcx, t) || ty::type_is_native(tcx, t) {
2083 if src.kind == owned { src_val = Load(cx, src_val); }
2084 Store(cx, src_val, dst);
2086 } else if ty::type_is_nil(tcx, t) || ty::type_is_bot(tcx, t) {
2088 } else if ty::type_is_boxed(tcx, t) || ty::type_is_unique(tcx, t) {
2089 if src.kind == owned { src_val = Load(cx, src_val); }
2090 if action == DROP_EXISTING { cx = drop_ty(cx, dst, t); }
2091 Store(cx, src_val, dst);
2092 if src.kind == owned { ret zero_alloca(cx, src.val, t); }
2093 // If we're here, it must be a temporary.
2094 revoke_clean(cx, src_val);
2096 } else if type_is_structural_or_param(tcx, t) {
2097 if action == DROP_EXISTING { cx = drop_ty(cx, dst, t); }
2098 cx = memmove_ty(cx, dst, src_val, t);
2099 if src.kind == owned { ret zero_alloca(cx, src_val, t); }
2100 // If we're here, it must be a temporary.
2101 revoke_clean(cx, src_val);
2104 /* FIXME: suggests a type constraint */
2105 bcx_ccx(cx).sess.bug("unexpected type in trans::move_val: " +
2109 fn store_temp_expr(cx: @block_ctxt, action: copy_action, dst: ValueRef,
2110 src: lval_result, t: ty::t, last_use: bool)
2112 // Lvals in memory are not temporaries. Copy them.
2113 if src.kind != temporary && !last_use {
2114 let v = src.kind == owned ? load_if_immediate(cx, src.val, t)
2116 ret copy_val(cx, action, dst, v, t);
2118 ret move_val(cx, action, dst, src, t);
2121 fn trans_crate_lit(cx: @crate_ctxt, lit: ast::lit) -> ValueRef {
2123 ast::lit_int(i, t) { C_integral(T_int_ty(cx, t), i as u64, True) }
2124 ast::lit_uint(u, t) { C_integral(T_uint_ty(cx, t), u, False) }
2125 ast::lit_float(fs, t) { C_floating(fs, T_float_ty(cx, t)) }
2126 ast::lit_bool(b) { C_bool(b) }
2127 ast::lit_nil. { C_nil() }
2129 cx.sess.span_unimpl(lit.span, "unique string in this context");
2134 fn trans_lit(cx: @block_ctxt, lit: ast::lit, dest: dest) -> @block_ctxt {
2135 if dest == ignore { ret cx; }
2137 ast::lit_str(s) { ret tvec::trans_str(cx, s, dest); }
2139 ret store_in_dest(cx, trans_crate_lit(bcx_ccx(cx), lit), dest);
2145 // Converts an annotation to a type
2146 fn node_id_type(cx: @crate_ctxt, id: ast::node_id) -> ty::t {
2147 ret ty::node_id_to_monotype(cx.tcx, id);
2150 fn node_type(cx: @crate_ctxt, sp: span, id: ast::node_id) -> TypeRef {
2151 let ty = node_id_type(cx, id);
2152 // How to make this a precondition?
2153 // FIXME (again, would require a predicate that implies
2154 // another predicate)
2155 check (type_has_static_size(cx, ty));
2159 fn trans_unary(bcx: @block_ctxt, op: ast::unop, e: @ast::expr,
2160 id: ast::node_id, dest: dest) -> @block_ctxt {
2161 if dest == ignore { ret trans_expr(bcx, e, ignore); }
2162 let e_ty = ty::expr_ty(bcx_tcx(bcx), e);
2165 let {bcx, val} = trans_temp_expr(bcx, e);
2166 ret store_in_dest(bcx, Not(bcx, val), dest);
2169 let {bcx, val} = trans_temp_expr(bcx, e);
2170 let neg = if ty::type_is_fp(bcx_tcx(bcx), e_ty) {
2172 } else { Neg(bcx, val) };
2173 ret store_in_dest(bcx, neg, dest);
2176 let {bcx, box, body} = trans_malloc_boxed(bcx, e_ty);
2177 add_clean_free(bcx, box, false);
2178 // Cast the body type to the type of the value. This is needed to
2179 // make tags work, since tags have a different LLVM type depending
2180 // on whether they're boxed or not.
2181 let ccx = bcx_ccx(bcx);
2182 if check type_has_static_size(ccx, e_ty) {
2184 let llety = T_ptr(type_of(ccx, e_sp, e_ty));
2185 body = PointerCast(bcx, body, llety);
2187 bcx = trans_expr_save_in(bcx, e, body);
2188 revoke_clean(bcx, box);
2189 ret store_in_dest(bcx, box, dest);
2192 ret trans_uniq::trans_uniq(bcx, e, id, dest);
2195 bcx_ccx(bcx).sess.bug("deref expressions should have been \
2196 translated using trans_lval(), not \
2202 fn trans_compare(cx: @block_ctxt, op: ast::binop, lhs: ValueRef,
2203 _lhs_t: ty::t, rhs: ValueRef, rhs_t: ty::t) -> result {
2204 if ty::type_is_scalar(bcx_tcx(cx), rhs_t) {
2205 let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, op);
2206 ret rslt(rs.bcx, rs.val);
2209 // Determine the operation we need.
2212 ast::eq. | ast::ne. { llop = C_u8(abi::cmp_glue_op_eq); }
2213 ast::lt. | ast::ge. { llop = C_u8(abi::cmp_glue_op_lt); }
2214 ast::le. | ast::gt. { llop = C_u8(abi::cmp_glue_op_le); }
2217 let rs = call_cmp_glue(cx, lhs, rhs, rhs_t, llop);
2219 // Invert the result if necessary.
2221 ast::eq. | ast::lt. | ast::le. { ret rslt(rs.bcx, rs.val); }
2222 ast::ne. | ast::ge. | ast::gt. {
2223 ret rslt(rs.bcx, Not(rs.bcx, rs.val));
2228 // Important to get types for both lhs and rhs, because one might be _|_
2229 // and the other not.
2230 fn trans_eager_binop(cx: @block_ctxt, op: ast::binop, lhs: ValueRef,
2231 lhs_t: ty::t, rhs: ValueRef, rhs_t: ty::t, dest: dest)
2233 if dest == ignore { ret cx; }
2235 if ty::type_is_bot(bcx_tcx(cx), intype) { intype = rhs_t; }
2236 let is_float = ty::type_is_fp(bcx_tcx(cx), intype);
2238 if op == ast::add && ty::type_is_sequence(bcx_tcx(cx), intype) {
2239 ret tvec::trans_add(cx, intype, lhs, rhs, dest);
2241 let cx = cx, val = alt op {
2243 if is_float { FAdd(cx, lhs, rhs) }
2244 else { Add(cx, lhs, rhs) }
2247 if is_float { FSub(cx, lhs, rhs) }
2248 else { Sub(cx, lhs, rhs) }
2251 if is_float { FMul(cx, lhs, rhs) }
2252 else { Mul(cx, lhs, rhs) }
2255 if is_float { FDiv(cx, lhs, rhs) }
2256 else if ty::type_is_signed(bcx_tcx(cx), intype) {
2258 } else { UDiv(cx, lhs, rhs) }
2261 if is_float { FRem(cx, lhs, rhs) }
2262 else if ty::type_is_signed(bcx_tcx(cx), intype) {
2264 } else { URem(cx, lhs, rhs) }
2266 ast::bitor. { Or(cx, lhs, rhs) }
2267 ast::bitand. { And(cx, lhs, rhs) }
2268 ast::bitxor. { Xor(cx, lhs, rhs) }
2269 ast::lsl. { Shl(cx, lhs, rhs) }
2270 ast::lsr. { LShr(cx, lhs, rhs) }
2271 ast::asr. { AShr(cx, lhs, rhs) }
2273 let cmpr = trans_compare(cx, op, lhs, lhs_t, rhs, rhs_t);
2278 ret store_in_dest(cx, val, dest);
2281 fn trans_assign_op(bcx: @block_ctxt, op: ast::binop, dst: @ast::expr,
2282 src: @ast::expr) -> @block_ctxt {
2283 let tcx = bcx_tcx(bcx);
2284 let t = ty::expr_ty(tcx, src);
2285 let lhs_res = trans_lval(bcx, dst);
2286 assert (lhs_res.kind == owned);
2287 // Special case for `+= [x]`
2288 alt ty::struct(tcx, t) {
2291 ast::expr_vec(args, _) {
2292 ret tvec::trans_append_literal(lhs_res.bcx,
2293 lhs_res.val, t, args);
2300 let {bcx, val: rhs_val} = trans_temp_expr(lhs_res.bcx, src);
2301 if ty::type_is_sequence(tcx, t) {
2304 ret tvec::trans_append(bcx, t, lhs_res.val, rhs_val);
2309 ret trans_eager_binop(bcx, op, Load(bcx, lhs_res.val), t, rhs_val, t,
2310 save_in(lhs_res.val));
2313 fn autoderef(cx: @block_ctxt, v: ValueRef, t: ty::t) -> result_t {
2314 let v1: ValueRef = v;
2316 let ccx = bcx_ccx(cx);
2319 alt ty::struct(ccx.tcx, t1) {
2321 let body = GEPi(cx, v1, [0, abi::box_rc_field_body]);
2324 // Since we're changing levels of box indirection, we may have
2325 // to cast this pointer, since statically-sized tag types have
2326 // different types depending on whether they're behind a box
2328 if check type_has_static_size(ccx, t1) {
2329 let llty = type_of(ccx, sp, t1);
2330 v1 = PointerCast(cx, body, T_ptr(llty));
2331 } else { v1 = body; }
2334 check trans_uniq::type_is_unique_box(cx, t1);
2335 let derefed = trans_uniq::autoderef(cx, v1, t1);
2339 ty::ty_res(did, inner, tps) {
2340 t1 = ty::substitute_type_params(ccx.tcx, tps, inner);
2341 v1 = GEPi(cx, v1, [0, 1]);
2343 ty::ty_tag(did, tps) {
2344 let variants = ty::tag_variants(ccx.tcx, did);
2345 if vec::len(*variants) != 1u ||
2346 vec::len(variants[0].args) != 1u {
2350 ty::substitute_type_params(ccx.tcx, tps, variants[0].args[0]);
2351 if check type_has_static_size(ccx, t1) {
2352 v1 = PointerCast(cx, v1, T_ptr(type_of(ccx, sp, t1)));
2353 } else { } // FIXME: typestate hack
2357 v1 = load_if_immediate(cx, v1, t1);
2359 ret {bcx: cx, val: v1, ty: t1};
2362 fn trans_lazy_binop(bcx: @block_ctxt, op: ast::binop, a: @ast::expr,
2363 b: @ast::expr, dest: dest) -> @block_ctxt {
2364 let is_and = alt op { ast::and. { true } ast::or. { false } };
2365 let lhs_res = trans_temp_expr(bcx, a);
2366 if lhs_res.bcx.unreachable { ret lhs_res.bcx; }
2367 let rhs_cx = new_scope_block_ctxt(lhs_res.bcx, "rhs");
2368 let rhs_res = trans_temp_expr(rhs_cx, b);
2370 let lhs_past_cx = new_scope_block_ctxt(lhs_res.bcx, "lhs");
2371 // The following line ensures that any cleanups for rhs
2372 // are done within the block for rhs. This is necessary
2373 // because and/or are lazy. So the rhs may never execute,
2374 // and the cleanups can't be pushed into later code.
2375 let rhs_bcx = trans_block_cleanups(rhs_res.bcx, rhs_cx);
2377 CondBr(lhs_res.bcx, lhs_res.val, rhs_cx.llbb, lhs_past_cx.llbb);
2379 CondBr(lhs_res.bcx, lhs_res.val, lhs_past_cx.llbb, rhs_cx.llbb);
2382 let join_cx = new_sub_block_ctxt(bcx, "join");
2383 Br(lhs_past_cx, join_cx.llbb);
2384 if rhs_bcx.unreachable {
2385 ret store_in_dest(join_cx, C_bool(!is_and), dest);
2387 Br(rhs_bcx, join_cx.llbb);
2388 let phi = Phi(join_cx, T_bool(), [C_bool(!is_and), rhs_res.val],
2389 [lhs_past_cx.llbb, rhs_bcx.llbb]);
2390 ret store_in_dest(join_cx, phi, dest);
2393 fn trans_binary(cx: @block_ctxt, op: ast::binop, a: @ast::expr, b: @ast::expr,
2394 dest: dest) -> @block_ctxt {
2395 // First couple cases are lazy:
2397 ast::and. | ast::or. {
2398 ret trans_lazy_binop(cx, op, a, b, dest);
2401 // Remaining cases are eager:
2402 let lhs = trans_temp_expr(cx, a);
2403 let rhs = trans_temp_expr(lhs.bcx, b);
2404 ret trans_eager_binop(rhs.bcx, op, lhs.val,
2405 ty::expr_ty(bcx_tcx(cx), a), rhs.val,
2406 ty::expr_ty(bcx_tcx(cx), b), dest);
2412 by_val(@mutable ValueRef);
2417 fn empty_dest_cell() -> @mutable ValueRef {
2418 ret @mutable llvm::LLVMGetUndef(T_nil());
2421 fn dup_for_join(dest: dest) -> dest {
2423 by_val(_) { by_val(empty_dest_cell()) }
2428 fn join_returns(parent_cx: @block_ctxt, in_cxs: [@block_ctxt],
2429 in_ds: [dest], out_dest: dest) -> @block_ctxt {
2430 let out = new_sub_block_ctxt(parent_cx, "join");
2431 let reachable = false, i = 0u, phi = none;
2433 if !cx.unreachable {
2438 if option::is_none(phi) {
2439 phi = some(EmptyPhi(out, val_ty(*cell)));
2441 AddIncomingToPhi(option::get(phi), *cell, cx.llbb);
2452 by_val(cell) { *cell = option::get(phi); }
2459 // Used to put an immediate value in a dest.
2460 fn store_in_dest(bcx: @block_ctxt, val: ValueRef, dest: dest) -> @block_ctxt {
2463 by_val(cell) { *cell = val; }
2464 save_in(addr) { Store(bcx, val, addr); }
2469 fn get_dest_addr(dest: dest) -> ValueRef {
2470 alt dest { save_in(a) { a } }
2473 fn trans_if(cx: @block_ctxt, cond: @ast::expr, thn: ast::blk,
2474 els: option::t<@ast::expr>, dest: dest)
2476 let {bcx, val: cond_val} = trans_temp_expr(cx, cond);
2478 let then_dest = dup_for_join(dest);
2479 let else_dest = dup_for_join(dest);
2480 let then_cx = new_scope_block_ctxt(bcx, "then");
2481 let else_cx = new_scope_block_ctxt(bcx, "else");
2482 CondBr(bcx, cond_val, then_cx.llbb, else_cx.llbb);
2483 then_cx = trans_block_dps(then_cx, thn, then_dest);
2484 // Calling trans_block directly instead of trans_expr
2485 // because trans_expr will create another scope block
2486 // context for the block, but we've already got the
2491 ast::expr_if(_, _, _) {
2492 let elseif_blk = ast_util::block_from_expr(elexpr);
2493 else_cx = trans_block_dps(else_cx, elseif_blk, else_dest);
2495 ast::expr_block(blk) {
2496 else_cx = trans_block_dps(else_cx, blk, else_dest);
2502 ret join_returns(cx, [then_cx, else_cx], [then_dest, else_dest], dest);
2505 fn trans_for(cx: @block_ctxt, local: @ast::local, seq: @ast::expr,
2506 body: ast::blk) -> @block_ctxt {
2507 fn inner(bcx: @block_ctxt, local: @ast::local, curr: ValueRef, t: ty::t,
2508 body: ast::blk, outer_next_cx: @block_ctxt) -> @block_ctxt {
2509 let next_cx = new_sub_block_ctxt(bcx, "next");
2511 new_loop_scope_block_ctxt(bcx, option::some(next_cx),
2512 outer_next_cx, "for loop scope");
2513 Br(bcx, scope_cx.llbb);
2514 let curr = PointerCast(bcx, curr, T_ptr(type_of_or_i8(bcx, t)));
2515 let bcx = trans_alt::bind_irrefutable_pat(scope_cx, local.node.pat,
2517 bcx = trans_block_dps(bcx, body, ignore);
2518 Br(bcx, next_cx.llbb);
2521 let ccx = bcx_ccx(cx);
2522 let next_cx = new_sub_block_ctxt(cx, "next");
2523 let seq_ty = ty::expr_ty(bcx_tcx(cx), seq);
2524 let {bcx: bcx, val: seq} = trans_temp_expr(cx, seq);
2525 let seq = PointerCast(bcx, seq, T_ptr(ccx.opaque_vec_type));
2526 let fill = tvec::get_fill(bcx, seq);
2527 if ty::type_is_str(bcx_tcx(bcx), seq_ty) {
2528 fill = Sub(bcx, fill, C_int(ccx, 1));
2530 let bcx = tvec::iter_vec_raw(bcx, seq, seq_ty, fill,
2531 bind inner(_, local, _, _, body, next_cx));
2532 Br(bcx, next_cx.llbb);
2536 fn trans_while(cx: @block_ctxt, cond: @ast::expr, body: ast::blk)
2538 let next_cx = new_sub_block_ctxt(cx, "while next");
2540 new_loop_scope_block_ctxt(cx, option::none::<@block_ctxt>, next_cx,
2542 let body_cx = new_scope_block_ctxt(cond_cx, "while loop body");
2543 let body_end = trans_block(body_cx, body);
2544 let cond_res = trans_temp_expr(cond_cx, cond);
2545 Br(body_end, cond_cx.llbb);
2546 let cond_bcx = trans_block_cleanups(cond_res.bcx, cond_cx);
2547 CondBr(cond_bcx, cond_res.val, body_cx.llbb, next_cx.llbb);
2548 Br(cx, cond_cx.llbb);
2552 fn trans_do_while(cx: @block_ctxt, body: ast::blk, cond: @ast::expr) ->
2554 let next_cx = new_sub_block_ctxt(cx, "next");
2556 new_loop_scope_block_ctxt(cx, option::none::<@block_ctxt>, next_cx,
2557 "do-while loop body");
2558 let body_end = trans_block(body_cx, body);
2559 let cond_cx = new_scope_block_ctxt(body_cx, "do-while cond");
2560 Br(body_end, cond_cx.llbb);
2561 let cond_res = trans_temp_expr(cond_cx, cond);
2562 let cond_bcx = trans_block_cleanups(cond_res.bcx, cond_cx);
2563 CondBr(cond_bcx, cond_res.val, body_cx.llbb, next_cx.llbb);
2564 Br(cx, body_cx.llbb);
2568 type generic_info = {
2570 static_tis: [option::t<@tydesc_info>],
2571 tydescs: [ValueRef],
2572 param_bounds: @[ty::param_bounds],
2573 origins: option::t<typeck::dict_res>
2577 temporary; //< Temporary value passed by value if of immediate type
2578 owned; //< Non-temporary value passed by pointer
2579 owned_imm; //< Non-temporary value passed by value
2581 type local_var_result = {val: ValueRef, kind: lval_kind};
2582 type lval_result = {bcx: @block_ctxt, val: ValueRef, kind: lval_kind};
2587 dict_env(ValueRef, ValueRef);
2589 type lval_maybe_callee = {bcx: @block_ctxt,
2593 generic: option::t<generic_info>};
2595 fn null_env_ptr(bcx: @block_ctxt) -> ValueRef {
2596 C_null(T_opaque_boxed_closure_ptr(bcx_ccx(bcx)))
2599 fn lval_from_local_var(bcx: @block_ctxt, r: local_var_result) -> lval_result {
2600 ret { bcx: bcx, val: r.val, kind: r.kind };
2603 fn lval_owned(bcx: @block_ctxt, val: ValueRef) -> lval_result {
2604 ret {bcx: bcx, val: val, kind: owned};
2606 fn lval_temp(bcx: @block_ctxt, val: ValueRef) -> lval_result {
2607 ret {bcx: bcx, val: val, kind: temporary};
2610 fn lval_no_env(bcx: @block_ctxt, val: ValueRef, kind: lval_kind)
2611 -> lval_maybe_callee {
2612 ret {bcx: bcx, val: val, kind: kind, env: is_closure, generic: none};
2615 fn trans_external_path(cx: @block_ctxt, did: ast::def_id,
2616 tpt: ty::ty_param_bounds_and_ty) -> ValueRef {
2617 let lcx = cx.fcx.lcx;
2618 let name = csearch::get_symbol(lcx.ccx.sess.get_cstore(), did);
2619 ret get_extern_const(lcx.ccx.externs, lcx.ccx.llmod, name,
2620 type_of_ty_param_bounds_and_ty(lcx, cx.sp, tpt));
2623 fn lval_static_fn(bcx: @block_ctxt, fn_id: ast::def_id, id: ast::node_id)
2624 -> lval_maybe_callee {
2625 let ccx = bcx_ccx(bcx);
2626 let tpt = ty::lookup_item_type(ccx.tcx, fn_id);
2627 let val = if fn_id.crate == ast::local_crate {
2628 // Internal reference.
2629 assert (ccx.item_ids.contains_key(fn_id.node));
2630 ccx.item_ids.get(fn_id.node)
2632 // External reference.
2633 trans_external_path(bcx, fn_id, tpt)
2635 let tys = ty::node_id_to_type_params(ccx.tcx, id);
2636 let gen = none, bcx = bcx;
2637 if vec::len(tys) != 0u {
2638 let tydescs = [], tis = [];
2640 // TODO: Doesn't always escape.
2642 let td = get_tydesc(bcx, t, true, tps_normal, ti).result;
2645 tydescs += [td.val];
2647 gen = some({item_type: tpt.ty,
2650 param_bounds: tpt.bounds,
2651 origins: ccx.dict_map.find(id)});
2653 ret {bcx: bcx, val: val, kind: owned, env: null_env, generic: gen};
2656 fn lookup_discriminant(lcx: @local_ctxt, vid: ast::def_id) -> ValueRef {
2658 alt ccx.discrims.find(vid) {
2660 // It's an external discriminant that we haven't seen yet.
2661 assert (vid.crate != ast::local_crate);
2662 let sym = csearch::get_symbol(lcx.ccx.sess.get_cstore(), vid);
2666 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
2668 llvm::LLVMSetLinkage(gvar,
2669 lib::llvm::LLVMExternalLinkage as llvm::Linkage);
2670 llvm::LLVMSetGlobalConstant(gvar, True);
2671 lcx.ccx.discrims.insert(vid, gvar);
2674 some(llval) { ret llval; }
2678 fn trans_local_var(cx: @block_ctxt, def: ast::def) -> local_var_result {
2679 fn take_local(table: hashmap<ast::node_id, local_val>,
2680 id: ast::node_id) -> local_var_result {
2681 alt table.find(id) {
2682 some(local_mem(v)) { {val: v, kind: owned} }
2683 some(local_imm(v)) { {val: v, kind: owned_imm} }
2687 ast::def_upvar(did, _, _) {
2688 assert (cx.fcx.llupvars.contains_key(did.node));
2689 ret { val: cx.fcx.llupvars.get(did.node), kind: owned };
2691 ast::def_arg(did, _) {
2692 ret take_local(cx.fcx.llargs, did.node);
2694 ast::def_local(did, _) | ast::def_binding(did) {
2695 ret take_local(cx.fcx.lllocals, did.node);
2697 ast::def_obj_field(did, _) {
2698 assert (cx.fcx.llobjfields.contains_key(did.node));
2699 ret { val: cx.fcx.llobjfields.get(did.node), kind: owned };
2701 ast::def_self(did) {
2702 let slf = option::get(cx.fcx.llself);
2703 let ptr = PointerCast(cx, slf.v, T_ptr(type_of_or_i8(cx, slf.t)));
2704 ret {val: ptr, kind: owned};
2707 bcx_ccx(cx).sess.span_unimpl
2708 (cx.sp, "unsupported def type in trans_local_def");
2713 fn trans_path(cx: @block_ctxt, p: @ast::path, id: ast::node_id)
2714 -> lval_maybe_callee {
2715 ret trans_var(cx, p.span, bcx_tcx(cx).def_map.get(id), id);
2718 fn trans_var(cx: @block_ctxt, sp: span, def: ast::def, id: ast::node_id)
2719 -> lval_maybe_callee {
2720 let ccx = bcx_ccx(cx);
2722 ast::def_fn(did, _) | ast::def_native_fn(did, _) {
2723 ret lval_static_fn(cx, did, id);
2725 ast::def_variant(tid, vid) {
2726 if vec::len(ty::tag_variant_with_id(ccx.tcx, tid, vid).args) > 0u {
2728 ret lval_static_fn(cx, vid, id);
2731 let tag_ty = node_id_type(ccx, id);
2732 let alloc_result = alloc_ty(cx, tag_ty);
2733 let lltagblob = alloc_result.val;
2734 let lltagty = type_of_tag(ccx, sp, tid, tag_ty);
2735 let bcx = alloc_result.bcx;
2736 let lltagptr = PointerCast(bcx, lltagblob, T_ptr(lltagty));
2737 let lldiscrimptr = GEPi(bcx, lltagptr, [0, 0]);
2738 let d = if vec::len(*ty::tag_variants(ccx.tcx, tid)) != 1u {
2739 let lldiscrim_gv = lookup_discriminant(bcx.fcx.lcx, vid);
2740 let lldiscrim = Load(bcx, lldiscrim_gv);
2742 } else { C_int(ccx, 0) };
2743 Store(bcx, d, lldiscrimptr);
2744 ret lval_no_env(bcx, lltagptr, temporary);
2747 ast::def_const(did) {
2748 if did.crate == ast::local_crate {
2749 assert (ccx.consts.contains_key(did.node));
2750 ret lval_no_env(cx, ccx.consts.get(did.node), owned);
2752 let tp = ty::node_id_to_monotype(ccx.tcx, id);
2753 let val = trans_external_path(cx, did, {bounds: @[], ty: tp});
2754 ret lval_no_env(cx, load_if_immediate(cx, val, tp), owned_imm);
2758 let loc = trans_local_var(cx, def);
2759 ret lval_no_env(cx, loc.val, loc.kind);
2764 fn trans_object_field(bcx: @block_ctxt, o: @ast::expr, field: ast::ident)
2765 -> {bcx: @block_ctxt, mthptr: ValueRef, objptr: ValueRef} {
2766 let {bcx, val} = trans_temp_expr(bcx, o);
2767 let {bcx, val, ty} = autoderef(bcx, val, ty::expr_ty(bcx_tcx(bcx), o));
2768 ret trans_object_field_inner(bcx, val, field, ty);
2771 fn trans_object_field_inner(bcx: @block_ctxt, o: ValueRef,
2772 field: ast::ident, o_ty: ty::t)
2773 -> {bcx: @block_ctxt, mthptr: ValueRef, objptr: ValueRef} {
2774 let ccx = bcx_ccx(bcx), tcx = ccx.tcx;
2775 let mths = alt ty::struct(tcx, o_ty) { ty::ty_obj(ms) { ms } };
2777 let ix = option::get(ty::method_idx(field, mths));
2778 let vtbl = Load(bcx, GEPi(bcx, o, [0, abi::obj_field_vtbl]));
2779 let vtbl_type = T_ptr(T_array(T_ptr(T_nil()), ix + 1u));
2780 vtbl = PointerCast(bcx, vtbl, vtbl_type);
2782 let v = GEPi(bcx, vtbl, [0, ix as int]);
2783 let fn_ty: ty::t = ty::mk_fn(tcx, mths[ix].fty);
2784 let ret_ty = ty::ty_fn_ret(tcx, fn_ty);
2785 // FIXME: constrain ty_obj?
2786 let ll_fn_ty = type_of_fn(ccx, bcx.sp, true,
2787 ty::ty_fn_args(tcx, fn_ty), ret_ty, []);
2788 v = Load(bcx, PointerCast(bcx, v, T_ptr(T_ptr(ll_fn_ty))));
2789 ret {bcx: bcx, mthptr: v, objptr: o};
2793 fn trans_rec_field(bcx: @block_ctxt, base: @ast::expr,
2794 field: ast::ident) -> lval_result {
2795 let {bcx, val} = trans_temp_expr(bcx, base);
2796 let {bcx, val, ty} = autoderef(bcx, val, ty::expr_ty(bcx_tcx(bcx), base));
2797 let fields = alt ty::struct(bcx_tcx(bcx), ty) { ty::ty_rec(fs) { fs } };
2798 let ix = option::get(ty::field_idx(field, fields));
2800 check type_is_tup_like(bcx, ty);
2801 let {bcx, val} = GEP_tup_like(bcx, ty, val, [0, ix as int]);
2802 ret {bcx: bcx, val: val, kind: owned};
2805 fn trans_index(cx: @block_ctxt, sp: span, base: @ast::expr, idx: @ast::expr,
2806 id: ast::node_id) -> lval_result {
2807 // Is this an interior vector?
2808 let base_ty = ty::expr_ty(bcx_tcx(cx), base);
2809 let exp = trans_temp_expr(cx, base);
2810 let lv = autoderef(exp.bcx, exp.val, base_ty);
2811 let ix = trans_temp_expr(lv.bcx, idx);
2814 let ccx = bcx_ccx(cx);
2816 // Cast to an LLVM integer. Rust is less strict than LLVM in this regard.
2818 let ix_size = llsize_of_real(bcx_ccx(cx), val_ty(ix.val));
2819 let int_size = llsize_of_real(bcx_ccx(cx), ccx.int_type);
2820 if ix_size < int_size {
2821 ix_val = ZExt(bcx, ix.val, ccx.int_type);
2822 } else if ix_size > int_size {
2823 ix_val = Trunc(bcx, ix.val, ccx.int_type);
2824 } else { ix_val = ix.val; }
2826 let unit_ty = node_id_type(bcx_ccx(cx), id);
2827 let unit_sz = size_of(bcx, unit_ty);
2829 maybe_name_value(bcx_ccx(cx), unit_sz.val, "unit_sz");
2830 let scaled_ix = Mul(bcx, ix_val, unit_sz.val);
2831 maybe_name_value(bcx_ccx(cx), scaled_ix, "scaled_ix");
2832 let lim = tvec::get_fill(bcx, v);
2833 let body = tvec::get_dataptr(bcx, v, type_of_or_i8(bcx, unit_ty));
2834 let bounds_check = ICmp(bcx, lib::llvm::LLVMIntULT, scaled_ix, lim);
2835 let fail_cx = new_sub_block_ctxt(bcx, "fail");
2836 let next_cx = new_sub_block_ctxt(bcx, "next");
2837 let ncx = bcx_ccx(next_cx);
2838 CondBr(bcx, bounds_check, next_cx.llbb, fail_cx.llbb);
2839 // fail: bad bounds check.
2841 trans_fail(fail_cx, some::<span>(sp), "bounds check");
2843 if check type_has_static_size(ncx, unit_ty) {
2844 let elt_1 = GEP(next_cx, body, [ix_val]);
2845 let llunitty = type_of(ncx, sp, unit_ty);
2846 PointerCast(next_cx, elt_1, T_ptr(llunitty))
2848 body = PointerCast(next_cx, body, T_ptr(T_i8()));
2849 GEP(next_cx, body, [scaled_ix])
2852 ret lval_owned(next_cx, elt);
2855 fn expr_is_lval(bcx: @block_ctxt, e: @ast::expr) -> bool {
2856 let ccx = bcx_ccx(bcx);
2857 ty::expr_is_lval(ccx.method_map, ccx.tcx, e)
2860 fn trans_callee(bcx: @block_ctxt, e: @ast::expr) -> lval_maybe_callee {
2862 ast::expr_path(p) { ret trans_path(bcx, p, e.id); }
2863 ast::expr_field(base, ident, _) {
2864 // Lval means this is a record field, so not a method
2865 if !expr_is_lval(bcx, e) {
2866 alt bcx_ccx(bcx).method_map.find(e.id) {
2867 some(typeck::method_static(did)) { // An impl method
2868 ret trans_impl::trans_static_callee(bcx, e, base, did);
2870 some(typeck::method_param(iid, off, p, b)) {
2871 ret trans_impl::trans_dict_callee(
2872 bcx, e, base, iid, off, p, b);
2874 none. { // An object method
2875 let of = trans_object_field(bcx, base, ident);
2876 ret {bcx: of.bcx, val: of.mthptr, kind: owned,
2877 env: obj_env(of.objptr), generic: none};
2884 let lv = trans_temp_lval(bcx, e);
2885 ret lval_no_env(lv.bcx, lv.val, lv.kind);
2888 // Use this when you know you are compiling an lval.
2889 // The additional bool returned indicates whether it's mem (that is
2890 // represented as an alloca or heap, hence needs a 'load' to be used as an
2892 fn trans_lval(cx: @block_ctxt, e: @ast::expr) -> lval_result {
2895 let v = trans_path(cx, p, e.id);
2896 ret lval_maybe_callee_to_lval(v, ty::expr_ty(bcx_tcx(cx), e));
2898 ast::expr_field(base, ident, _) {
2899 ret trans_rec_field(cx, base, ident);
2901 ast::expr_index(base, idx) {
2902 ret trans_index(cx, e.span, base, idx, e.id);
2904 ast::expr_unary(ast::deref., base) {
2905 let ccx = bcx_ccx(cx);
2906 let sub = trans_temp_expr(cx, base);
2907 let t = ty::expr_ty(ccx.tcx, base);
2909 alt ty::struct(ccx.tcx, t) {
2911 GEPi(sub.bcx, sub.val, [0, abi::box_rc_field_body])
2913 ty::ty_res(_, _, _) {
2914 GEPi(sub.bcx, sub.val, [0, 1])
2917 let ety = ty::expr_ty(ccx.tcx, e);
2920 if check type_has_static_size(ccx, ety) {
2921 T_ptr(type_of(ccx, sp, ety))
2922 } else { T_typaram_ptr(ccx.tn) };
2923 PointerCast(sub.bcx, sub.val, ellty)
2925 ty::ty_ptr(_) | ty::ty_uniq(_) { sub.val }
2927 ret lval_owned(sub.bcx, val);
2929 // This is a by-ref returning call. Regular calls are not lval
2930 ast::expr_call(f, args, _) {
2931 let cell = empty_dest_cell();
2932 let bcx = trans_call(cx, f, args, e.id, by_val(cell));
2933 ret lval_owned(bcx, *cell);
2935 _ { bcx_ccx(cx).sess.span_bug(e.span, "non-lval in trans_lval"); }
2939 fn maybe_add_env(bcx: @block_ctxt, c: lval_maybe_callee)
2940 -> (lval_kind, ValueRef) {
2942 is_closure. { (c.kind, c.val) }
2943 obj_env(_) | dict_env(_, _) {
2944 fail "Taking the value of a method does not work yet (issue #435)";
2947 let llfnty = llvm::LLVMGetElementType(val_ty(c.val));
2948 (temporary, create_real_fn_pair(bcx, llfnty, c.val,
2954 fn lval_maybe_callee_to_lval(c: lval_maybe_callee, ty: ty::t) -> lval_result {
2957 let n_args = vec::len(ty::ty_fn_args(bcx_tcx(c.bcx), ty));
2958 let args = vec::init_elt(none::<@ast::expr>, n_args);
2959 let space = alloc_ty(c.bcx, ty);
2960 let bcx = trans_closure::trans_bind_1(space.bcx, ty, c, args, ty,
2961 save_in(space.val));
2962 add_clean_temp(bcx, space.val, ty);
2963 ret {bcx: bcx, val: space.val, kind: temporary};
2966 let (kind, val) = maybe_add_env(c.bcx, c);
2967 ret {bcx: c.bcx, val: val, kind: kind};
2972 fn int_cast(bcx: @block_ctxt, lldsttype: TypeRef, llsrctype: TypeRef,
2973 llsrc: ValueRef, signed: bool) -> ValueRef {
2974 let srcsz = llvm::LLVMGetIntTypeWidth(llsrctype);
2975 let dstsz = llvm::LLVMGetIntTypeWidth(lldsttype);
2976 ret if dstsz == srcsz {
2977 BitCast(bcx, llsrc, lldsttype)
2978 } else if srcsz > dstsz {
2979 TruncOrBitCast(bcx, llsrc, lldsttype)
2981 SExtOrBitCast(bcx, llsrc, lldsttype)
2982 } else { ZExtOrBitCast(bcx, llsrc, lldsttype) };
2985 fn float_cast(bcx: @block_ctxt, lldsttype: TypeRef, llsrctype: TypeRef,
2986 llsrc: ValueRef) -> ValueRef {
2987 let srcsz = lib::llvm::float_width(llsrctype);
2988 let dstsz = lib::llvm::float_width(lldsttype);
2989 ret if dstsz > srcsz {
2990 FPExt(bcx, llsrc, lldsttype)
2991 } else if srcsz > dstsz {
2992 FPTrunc(bcx, llsrc, lldsttype)
2996 fn trans_cast(cx: @block_ctxt, e: @ast::expr, id: ast::node_id,
2997 dest: dest) -> @block_ctxt {
2998 let ccx = bcx_ccx(cx);
2999 let e_res = trans_temp_expr(cx, e);
3000 let ll_t_in = val_ty(e_res.val);
3001 let t_in = ty::expr_ty(ccx.tcx, e);
3002 let t_out = node_id_type(ccx, id);
3003 // Check should be avoidable because it's a cast.
3004 // FIXME: Constrain types so as to avoid this check.
3005 check (type_has_static_size(ccx, t_out));
3006 let ll_t_out = type_of(ccx, e.span, t_out);
3008 tag kind { pointer; integral; float; other; }
3009 fn t_kind(tcx: ty::ctxt, t: ty::t) -> kind {
3010 ret if ty::type_is_fp(tcx, t) {
3012 } else if ty::type_is_native(tcx, t) ||
3013 ty::type_is_unsafe_ptr(tcx, t) {
3015 } else if ty::type_is_integral(tcx, t) {
3019 let k_in = t_kind(ccx.tcx, t_in);
3020 let k_out = t_kind(ccx.tcx, t_out);
3021 let s_in = k_in == integral && ty::type_is_signed(ccx.tcx, t_in);
3024 alt {in: k_in, out: k_out} {
3025 {in: integral., out: integral.} {
3026 int_cast(e_res.bcx, ll_t_out, ll_t_in, e_res.val, s_in)
3028 {in: float., out: float.} {
3029 float_cast(e_res.bcx, ll_t_out, ll_t_in, e_res.val)
3031 {in: integral., out: float.} {
3033 SIToFP(e_res.bcx, e_res.val, ll_t_out)
3034 } else { UIToFP(e_res.bcx, e_res.val, ll_t_out) }
3036 {in: float., out: integral.} {
3037 if ty::type_is_signed(ccx.tcx, t_out) {
3038 FPToSI(e_res.bcx, e_res.val, ll_t_out)
3039 } else { FPToUI(e_res.bcx, e_res.val, ll_t_out) }
3041 {in: integral., out: pointer.} {
3042 IntToPtr(e_res.bcx, e_res.val, ll_t_out)
3044 {in: pointer., out: integral.} {
3045 PtrToInt(e_res.bcx, e_res.val, ll_t_out)
3047 {in: pointer., out: pointer.} {
3048 PointerCast(e_res.bcx, e_res.val, ll_t_out)
3050 _ { ccx.sess.bug("Translating unsupported cast.") }
3052 ret store_in_dest(e_res.bcx, newval, dest);
3055 fn trans_arg_expr(cx: @block_ctxt, arg: ty::arg, lldestty0: TypeRef,
3056 &to_zero: [{v: ValueRef, t: ty::t}],
3057 &to_revoke: [{v: ValueRef, t: ty::t}], e: @ast::expr) ->
3059 let ccx = bcx_ccx(cx);
3060 let e_ty = ty::expr_ty(ccx.tcx, e);
3061 let is_bot = ty::type_is_bot(ccx.tcx, e_ty);
3062 let lv = trans_temp_lval(cx, e);
3066 // For values of type _|_, we generate an
3067 // "undef" value, as such a value should never
3068 // be inspected. It's important for the value
3069 // to have type lldestty0 (the callee's expected type).
3070 val = llvm::LLVMGetUndef(lldestty0);
3071 } else if arg.mode == ast::by_ref || arg.mode == ast::by_val {
3072 let copied = false, imm = ty::type_is_immediate(ccx.tcx, e_ty);
3073 if arg.mode == ast::by_ref && lv.kind != owned && imm {
3074 val = do_spill_noroot(bcx, val);
3077 if ccx.copy_map.contains_key(e.id) && lv.kind != temporary {
3079 let alloc = alloc_ty(bcx, e_ty);
3080 bcx = copy_val(alloc.bcx, INIT, alloc.val,
3081 load_if_immediate(alloc.bcx, val, e_ty), e_ty);
3083 } else { bcx = take_ty(bcx, val, e_ty); }
3084 add_clean(bcx, val, e_ty);
3086 if arg.mode == ast::by_val && (lv.kind == owned || !imm) {
3087 val = Load(bcx, val);
3089 } else if arg.mode == ast::by_copy {
3090 let {bcx: cx, val: alloc} = alloc_ty(bcx, e_ty);
3091 let last_use = ccx.last_uses.contains_key(e.id);
3093 if lv.kind == temporary { revoke_clean(bcx, val); }
3094 if lv.kind == owned || !ty::type_is_immediate(ccx.tcx, e_ty) {
3095 bcx = memmove_ty(bcx, alloc, val, e_ty);
3096 if last_use && ty::type_needs_drop(ccx.tcx, e_ty) {
3097 bcx = zero_alloca(bcx, val, e_ty);
3099 } else { Store(bcx, val, alloc); }
3101 if lv.kind != temporary && !last_use {
3102 bcx = take_ty(bcx, val, e_ty);
3104 } else if ty::type_is_immediate(ccx.tcx, e_ty) && lv.kind != owned {
3105 let r = do_spill(bcx, val, e_ty);
3110 if !is_bot && ty::type_contains_params(ccx.tcx, arg.ty) {
3111 let lldestty = lldestty0;
3112 val = PointerCast(bcx, val, lldestty);
3115 // Collect arg for later if it happens to be one we've moving out.
3116 if arg.mode == ast::by_move {
3117 if lv.kind == owned {
3118 // Use actual ty, not declared ty -- anything else doesn't make
3119 // sense if declared ty is a ty param
3120 to_zero += [{v: lv.val, t: e_ty}];
3121 } else { to_revoke += [{v: lv.val, t: e_ty}]; }
3127 // NB: must keep 4 fns in sync:
3130 // - create_llargs_for_fn_args.
3133 fn trans_args(cx: @block_ctxt, llenv: ValueRef,
3134 gen: option::t<generic_info>, es: [@ast::expr], fn_ty: ty::t,
3136 -> {bcx: @block_ctxt,
3139 to_zero: [{v: ValueRef, t: ty::t}],
3140 to_revoke: [{v: ValueRef, t: ty::t}]} {
3142 let args: [ty::arg] = ty::ty_fn_args(bcx_tcx(cx), fn_ty);
3143 let llargs: [ValueRef] = [];
3144 let lltydescs: [ValueRef] = [];
3148 let ccx = bcx_ccx(cx);
3152 let retty = ty::ty_fn_ret(tcx, fn_ty), full_retty = retty;
3155 lazily_emit_all_generic_info_tydesc_glues(cx, g);
3156 let i = 0u, n_orig = 0u;
3157 for param in *g.param_bounds {
3158 lltydescs += [g.tydescs[i]];
3159 for bound in *param {
3161 ty::bound_iface(_) {
3162 let res = trans_impl::get_dict(
3163 bcx, option::get(g.origins)[n_orig]);
3164 lltydescs += [res.val];
3173 args = ty::ty_fn_args(tcx, g.item_type);
3174 retty = ty::ty_fn_ret(tcx, g.item_type);
3178 // Arg 0: Output pointer.
3179 let llretslot = alt dest {
3181 if ty::type_is_nil(tcx, retty) {
3182 llvm::LLVMGetUndef(T_ptr(T_nil()))
3184 let {bcx: cx, val} = alloc_ty(bcx, full_retty);
3189 save_in(dst) { dst }
3191 let {bcx: cx, val} = alloc_ty(bcx, full_retty);
3197 if ty::type_contains_params(tcx, retty) {
3198 // It's possible that the callee has some generic-ness somewhere in
3199 // its return value -- say a method signature within an obj or a fn
3200 // type deep in a structure -- which the caller has a concrete view
3201 // of. If so, cast the caller's view of the restlot to the callee's
3202 // view, for the sake of making a type-compatible call.
3203 check non_ty_var(ccx, retty);
3204 let llretty = T_ptr(type_of_inner(ccx, bcx.sp, retty));
3205 llargs += [PointerCast(cx, llretslot, llretty)];
3206 } else { llargs += [llretslot]; }
3208 // Arg 1: Env (closure-bindings / self-obj)
3211 // Args >2: ty_params ...
3212 llargs += lltydescs;
3214 // ... then explicit args.
3216 // First we figure out the caller's view of the types of the arguments.
3217 // This will be needed if this is a generic call, because the callee has
3218 // to cast her view of the arguments to the caller's view.
3219 let arg_tys = type_of_explicit_args(ccx, cx.sp, args);
3221 for e: @ast::expr in es {
3222 let r = trans_arg_expr(bcx, args[i], arg_tys[i], to_zero, to_revoke,
3232 to_revoke: to_revoke};
3235 fn trans_call(in_cx: @block_ctxt, f: @ast::expr,
3236 args: [@ast::expr], id: ast::node_id, dest: dest)
3238 // NB: 'f' isn't necessarily a function; it might be an entire self-call
3239 // expression because of the hack that allows us to process self-calls
3241 let tcx = bcx_tcx(in_cx);
3242 let fn_expr_ty = ty::expr_ty(tcx, f);
3244 let cx = new_scope_block_ctxt(in_cx, "call");
3246 let f_res = trans_callee(cx, f);
3247 let bcx = f_res.bcx;
3249 let faddr = f_res.val;
3250 let llenv, dict_param = none;
3253 llenv = llvm::LLVMGetUndef(T_opaque_boxed_closure_ptr(bcx_ccx(cx)));
3255 obj_env(e) { llenv = e; }
3256 dict_env(dict, e) { llenv = e; dict_param = some(dict); }
3258 // It's a closure. Have to fetch the elements
3259 if f_res.kind == owned {
3260 faddr = load_if_immediate(bcx, faddr, fn_expr_ty);
3263 faddr = GEPi(bcx, pair, [0, abi::fn_field_code]);
3264 faddr = Load(bcx, faddr);
3265 let llclosure = GEPi(bcx, pair, [0, abi::fn_field_box]);
3266 llenv = Load(bcx, llclosure);
3270 let ret_ty = ty::node_id_to_type(tcx, id);
3272 trans_args(bcx, llenv, f_res.generic, args, fn_expr_ty, dest);
3274 let llargs = args_res.args;
3275 option::may(dict_param) {|dict| llargs = [dict] + llargs}
3276 let llretslot = args_res.retslot;
3278 /* If the block is terminated,
3279 then one or more of the args has
3280 type _|_. Since that means it diverges, the code
3281 for the call itself is unreachable. */
3282 bcx = invoke_full(bcx, faddr, llargs, args_res.to_zero,
3283 args_res.to_revoke);
3286 if llvm::LLVMIsUndef(llretslot) != lib::llvm::True {
3287 bcx = drop_ty(bcx, llretslot, ret_ty);
3290 save_in(_) { } // Already saved by callee
3292 *cell = Load(bcx, llretslot);
3295 // Forget about anything we moved out.
3296 bcx = zero_and_revoke(bcx, args_res.to_zero, args_res.to_revoke);
3298 bcx = trans_block_cleanups(bcx, cx);
3299 let next_cx = new_sub_block_ctxt(in_cx, "next");
3300 if bcx.unreachable || ty::type_is_bot(tcx, ret_ty) {
3301 Unreachable(next_cx);
3303 Br(bcx, next_cx.llbb);
3307 fn zero_and_revoke(bcx: @block_ctxt,
3308 to_zero: [{v: ValueRef, t: ty::t}],
3309 to_revoke: [{v: ValueRef, t: ty::t}]) -> @block_ctxt {
3311 for {v, t} in to_zero {
3312 bcx = zero_alloca(bcx, v, t);
3314 for {v, _} in to_revoke { revoke_clean(bcx, v); }
3318 fn invoke(bcx: @block_ctxt, llfn: ValueRef,
3319 llargs: [ValueRef]) -> @block_ctxt {
3320 ret invoke_(bcx, llfn, llargs, [], [], Invoke);
3323 fn invoke_full(bcx: @block_ctxt, llfn: ValueRef, llargs: [ValueRef],
3324 to_zero: [{v: ValueRef, t: ty::t}],
3325 to_revoke: [{v: ValueRef, t: ty::t}]) -> @block_ctxt {
3326 ret invoke_(bcx, llfn, llargs, to_zero, to_revoke, Invoke);
3329 fn invoke_(bcx: @block_ctxt, llfn: ValueRef, llargs: [ValueRef],
3330 to_zero: [{v: ValueRef, t: ty::t}],
3331 to_revoke: [{v: ValueRef, t: ty::t}],
3332 invoker: fn(@block_ctxt, ValueRef, [ValueRef],
3333 BasicBlockRef, BasicBlockRef)) -> @block_ctxt {
3334 // FIXME: May be worth turning this into a plain call when there are no
3336 if bcx.unreachable { ret bcx; }
3337 let normal_bcx = new_sub_block_ctxt(bcx, "normal return");
3338 invoker(bcx, llfn, llargs, normal_bcx.llbb,
3339 get_landing_pad(bcx, to_zero, to_revoke));
3343 fn get_landing_pad(bcx: @block_ctxt,
3344 to_zero: [{v: ValueRef, t: ty::t}],
3345 to_revoke: [{v: ValueRef, t: ty::t}]
3346 ) -> BasicBlockRef {
3347 let have_zero_or_revoke = vec::is_not_empty(to_zero)
3348 || vec::is_not_empty(to_revoke);
3349 let scope_bcx = find_scope_for_lpad(bcx, have_zero_or_revoke);
3350 if scope_bcx.lpad_dirty || have_zero_or_revoke {
3351 let unwind_bcx = new_sub_block_ctxt(bcx, "unwind");
3352 trans_landing_pad(unwind_bcx, to_zero, to_revoke);
3353 scope_bcx.lpad = some(unwind_bcx.llbb);
3354 scope_bcx.lpad_dirty = have_zero_or_revoke;
3356 assert option::is_some(scope_bcx.lpad);
3357 ret option::get(scope_bcx.lpad);
3359 fn find_scope_for_lpad(bcx: @block_ctxt,
3360 have_zero_or_revoke: bool) -> @block_ctxt {
3361 let scope_bcx = bcx;
3363 scope_bcx = find_scope_cx(scope_bcx);
3364 if vec::is_not_empty(scope_bcx.cleanups)
3365 || have_zero_or_revoke {
3368 scope_bcx = alt scope_bcx.parent {
3369 parent_some(b) { b }
3380 fn trans_landing_pad(bcx: @block_ctxt,
3381 to_zero: [{v: ValueRef, t: ty::t}],
3382 to_revoke: [{v: ValueRef, t: ty::t}]) -> BasicBlockRef {
3383 // The landing pad return type (the type being propagated). Not sure what
3384 // this represents but it's determined by the personality function and
3385 // this is what the EH proposal example uses.
3386 let llretty = T_struct([T_ptr(T_i8()), T_i32()]);
3387 // The exception handling personality function. This is the C++
3388 // personality function __gxx_personality_v0, wrapped in our naming
3390 let personality = bcx_ccx(bcx).upcalls.rust_personality;
3391 // The only landing pad clause will be 'cleanup'
3393 let llpad = LandingPad(bcx, llretty, personality, clauses);
3394 // The landing pad result is used both for modifying the landing pad
3395 // in the C API and as the exception value
3396 let llretval = llpad;
3397 // The landing pad block is a cleanup
3398 SetCleanup(bcx, llpad);
3400 // Because we may have unwound across a stack boundary, we must call into
3401 // the runtime to figure out which stack segment we are on and place the
3402 // stack limit back into the TLS.
3403 Call(bcx, bcx_ccx(bcx).upcalls.reset_stack_limit, []);
3405 // FIXME: This seems like a very naive and redundant way to generate the
3406 // landing pads, as we're re-generating all in-scope cleanups for each
3407 // function call. Probably good optimization opportunities here.
3408 let bcx = zero_and_revoke(bcx, to_zero, to_revoke);
3411 scope_cx = find_scope_cx(scope_cx);
3412 bcx = trans_block_cleanups(bcx, scope_cx);
3413 scope_cx = alt scope_cx.parent {
3414 parent_some(b) { b }
3415 parent_none. { break; }
3419 // Continue unwinding
3420 Resume(bcx, llretval);
3424 fn trans_tup(bcx: @block_ctxt, elts: [@ast::expr], id: ast::node_id,
3425 dest: dest) -> @block_ctxt {
3426 let t = node_id_type(bcx.fcx.lcx.ccx, id);
3428 let addr = alt dest {
3430 for ex in elts { bcx = trans_expr(bcx, ex, ignore); }
3433 save_in(pos) { pos }
3435 let temp_cleanups = [], i = 0;
3437 let dst = GEP_tup_like_1(bcx, t, addr, [0, i]);
3438 let e_ty = ty::expr_ty(bcx_tcx(bcx), e);
3439 bcx = trans_expr_save_in(dst.bcx, e, dst.val);
3440 add_clean_temp_mem(bcx, dst.val, e_ty);
3441 temp_cleanups += [dst.val];
3444 for cleanup in temp_cleanups { revoke_clean(bcx, cleanup); }
3448 fn trans_rec(bcx: @block_ctxt, fields: [ast::field],
3449 base: option::t<@ast::expr>, id: ast::node_id,
3450 dest: dest) -> @block_ctxt {
3451 let t = node_id_type(bcx_ccx(bcx), id);
3453 let addr = alt dest {
3456 bcx = trans_expr(bcx, fld.node.expr, ignore);
3460 save_in(pos) { pos }
3463 let ty_fields = alt ty::struct(bcx_tcx(bcx), t) { ty::ty_rec(f) { f } };
3464 let temp_cleanups = [];
3466 let ix = option::get(vec::position_pred(ty_fields, {|ft|
3467 str::eq(fld.node.ident, ft.ident)
3469 let dst = GEP_tup_like_1(bcx, t, addr, [0, ix as int]);
3470 bcx = trans_expr_save_in(dst.bcx, fld.node.expr, dst.val);
3471 add_clean_temp_mem(bcx, dst.val, ty_fields[ix].mt.ty);
3472 temp_cleanups += [dst.val];
3476 let {bcx: cx, val: base_val} = trans_temp_expr(bcx, bexp), i = 0;
3478 // Copy over inherited fields
3479 for tf in ty_fields {
3480 if !vec::any(fields, {|f| str::eq(f.node.ident, tf.ident)}) {
3481 let dst = GEP_tup_like_1(bcx, t, addr, [0, i]);
3482 let base = GEP_tup_like_1(bcx, t, base_val, [0, i]);
3483 let val = load_if_immediate(base.bcx, base.val, tf.mt.ty);
3484 bcx = copy_val(base.bcx, INIT, dst.val, val, tf.mt.ty);
3492 // Now revoke the cleanups as we pass responsibility for the data
3493 // structure on to the caller
3494 for cleanup in temp_cleanups { revoke_clean(bcx, cleanup); }
3498 // Store the result of an expression in the given memory location, ensuring
3499 // that nil or bot expressions get ignore rather than save_in as destination.
3500 fn trans_expr_save_in(bcx: @block_ctxt, e: @ast::expr, dest: ValueRef)
3502 let tcx = bcx_tcx(bcx), t = ty::expr_ty(tcx, e);
3503 let do_ignore = ty::type_is_bot(tcx, t) || ty::type_is_nil(tcx, t);
3504 ret trans_expr(bcx, e, do_ignore ? ignore : save_in(dest));
3507 // Call this to compile an expression that you need as an intermediate value,
3508 // and you want to know whether you're dealing with an lval or not (the kind
3509 // field in the returned struct). For non-intermediates, use trans_expr or
3510 // trans_expr_save_in. For intermediates where you don't care about lval-ness,
3511 // use trans_temp_expr.
3512 fn trans_temp_lval(bcx: @block_ctxt, e: @ast::expr) -> lval_result {
3514 if expr_is_lval(bcx, e) {
3515 ret trans_lval(bcx, e);
3517 let tcx = bcx_tcx(bcx);
3518 let ty = ty::expr_ty(tcx, e);
3519 if ty::type_is_nil(tcx, ty) || ty::type_is_bot(tcx, ty) {
3520 bcx = trans_expr(bcx, e, ignore);
3521 ret {bcx: bcx, val: C_nil(), kind: temporary};
3522 } else if ty::type_is_immediate(bcx_tcx(bcx), ty) {
3523 let cell = empty_dest_cell();
3524 bcx = trans_expr(bcx, e, by_val(cell));
3525 add_clean_temp(bcx, *cell, ty);
3526 ret {bcx: bcx, val: *cell, kind: temporary};
3528 let {bcx, val: scratch} = alloc_ty(bcx, ty);
3529 bcx = trans_expr_save_in(bcx, e, scratch);
3530 add_clean_temp(bcx, scratch, ty);
3531 ret {bcx: bcx, val: scratch, kind: temporary};
3536 // Use only for intermediate values. See trans_expr and trans_expr_save_in for
3537 // expressions that must 'end up somewhere' (or get ignored).
3538 fn trans_temp_expr(bcx: @block_ctxt, e: @ast::expr) -> result {
3539 let {bcx, val, kind} = trans_temp_lval(bcx, e);
3541 val = load_if_immediate(bcx, val, ty::expr_ty(bcx_tcx(bcx), e));
3543 ret {bcx: bcx, val: val};
3546 // Translate an expression, with the dest argument deciding what happens with
3547 // the result. Invariants:
3548 // - exprs returning nil or bot always get dest=ignore
3549 // - exprs with non-immediate type never get dest=by_val
3550 fn trans_expr(bcx: @block_ctxt, e: @ast::expr, dest: dest) -> @block_ctxt {
3551 let tcx = bcx_tcx(bcx);
3552 debuginfo::update_source_pos(bcx, e.span);
3554 if expr_is_lval(bcx, e) {
3555 ret lval_to_dps(bcx, e, dest);
3559 ast::expr_if(cond, thn, els) | ast::expr_if_check(cond, thn, els) {
3560 ret trans_if(bcx, cond, thn, els, dest);
3562 ast::expr_ternary(_, _, _) {
3563 ret trans_expr(bcx, ast_util::ternary_to_if(e), dest);
3565 ast::expr_alt(expr, arms) {
3566 ret trans_alt::trans_alt(bcx, expr, arms, dest);
3568 ast::expr_block(blk) {
3569 let sub_cx = new_scope_block_ctxt(bcx, "block-expr body");
3570 Br(bcx, sub_cx.llbb);
3571 sub_cx = trans_block_dps(sub_cx, blk, dest);
3572 let next_cx = new_sub_block_ctxt(bcx, "next");
3573 Br(sub_cx, next_cx.llbb);
3574 if sub_cx.unreachable { Unreachable(next_cx); }
3577 ast::expr_rec(args, base) {
3578 ret trans_rec(bcx, args, base, e.id, dest);
3580 ast::expr_tup(args) { ret trans_tup(bcx, args, e.id, dest); }
3581 ast::expr_lit(lit) { ret trans_lit(bcx, *lit, dest); }
3582 ast::expr_vec(args, _) { ret tvec::trans_vec(bcx, args, e.id, dest); }
3583 ast::expr_binary(op, x, y) { ret trans_binary(bcx, op, x, y, dest); }
3584 ast::expr_unary(op, x) {
3585 assert op != ast::deref; // lvals are handled above
3586 ret trans_unary(bcx, op, x, e.id, dest);
3588 ast::expr_fn(proto, decl, body, cap_clause) {
3589 ret trans_closure::trans_expr_fn(
3590 bcx, proto, decl, body, e.span, e.id, *cap_clause, dest);
3592 ast::expr_fn_block(decl, body) {
3593 alt ty::struct(tcx, ty::expr_ty(tcx, e)) {
3594 ty::ty_fn({proto, _}) {
3595 #debug("translating fn_block %s with type %s",
3596 expr_to_str(e), ty_to_str(tcx, ty::expr_ty(tcx, e)));
3597 let cap_clause = { copies: [], moves: [] };
3598 ret trans_closure::trans_expr_fn(
3599 bcx, proto, decl, body, e.span, e.id, cap_clause, dest);
3602 fail "Type of fn block is not a function!";
3606 ast::expr_bind(f, args) {
3607 ret trans_closure::trans_bind(
3608 bcx, f, args, e.id, dest);
3611 if !expr_is_lval(bcx, a) {
3612 ret trans_expr(bcx, a, dest);
3614 else { ret lval_to_dps(bcx, a, dest); }
3616 ast::expr_cast(val, _) { ret trans_cast(bcx, val, e.id, dest); }
3617 ast::expr_anon_obj(anon_obj) {
3618 ret trans_anon_obj(bcx, e.span, anon_obj, e.id, dest);
3620 ast::expr_call(f, args, _) {
3621 ret trans_call(bcx, f, args, e.id, dest);
3623 ast::expr_field(_, _, _) {
3624 fail "Taking the value of a method does not work yet (issue #435)";
3627 // These return nothing
3629 assert dest == ignore;
3630 ret trans_break(e.span, bcx);
3633 assert dest == ignore;
3634 ret trans_cont(e.span, bcx);
3637 assert dest == ignore;
3638 ret trans_ret(bcx, ex);
3641 // Ideally, the expr_be tag would have a precondition
3642 // that is_call_expr(ex) -- but we don't support that
3645 check (ast_util::is_call_expr(ex));
3646 ret trans_be(bcx, ex);
3648 ast::expr_fail(expr) {
3649 assert dest == ignore;
3650 ret trans_fail_expr(bcx, some(e.span), expr);
3652 ast::expr_log(_, lvl, a) {
3653 assert dest == ignore;
3654 ret trans_log(lvl, bcx, a);
3656 ast::expr_assert(a) {
3657 assert dest == ignore;
3658 ret trans_check_expr(bcx, a, "Assertion");
3660 ast::expr_check(ast::checked_expr., a) {
3661 assert dest == ignore;
3662 ret trans_check_expr(bcx, a, "Predicate");
3664 ast::expr_check(ast::claimed_expr., a) {
3665 assert dest == ignore;
3666 /* Claims are turned on and off by a global variable
3667 that the RTS sets. This case generates code to
3668 check the value of that variable, doing nothing
3669 if it's set to false and acting like a check
3672 get_extern_const(bcx_ccx(bcx).externs, bcx_ccx(bcx).llmod,
3673 "check_claims", T_bool());
3674 let cond = Load(bcx, c);
3676 let then_cx = new_scope_block_ctxt(bcx, "claim_then");
3677 let check_cx = trans_check_expr(then_cx, a, "Claim");
3678 let next_cx = new_sub_block_ctxt(bcx, "join");
3680 CondBr(bcx, cond, then_cx.llbb, next_cx.llbb);
3681 Br(check_cx, next_cx.llbb);
3684 ast::expr_for(decl, seq, body) {
3685 assert dest == ignore;
3686 ret trans_for(bcx, decl, seq, body);
3688 ast::expr_while(cond, body) {
3689 assert dest == ignore;
3690 ret trans_while(bcx, cond, body);
3692 ast::expr_do_while(body, cond) {
3693 assert dest == ignore;
3694 ret trans_do_while(bcx, body, cond);
3696 ast::expr_assign(dst, src) {
3697 assert dest == ignore;
3698 let src_r = trans_temp_lval(bcx, src);
3699 let {bcx, val: addr, kind} = trans_lval(src_r.bcx, dst);
3700 assert kind == owned;
3701 ret store_temp_expr(bcx, DROP_EXISTING, addr, src_r,
3702 ty::expr_ty(bcx_tcx(bcx), src),
3703 bcx_ccx(bcx).last_uses.contains_key(src.id));
3705 ast::expr_move(dst, src) {
3706 // FIXME: calculate copy init-ness in typestate.
3707 assert dest == ignore;
3708 let src_r = trans_temp_lval(bcx, src);
3709 let {bcx, val: addr, kind} = trans_lval(src_r.bcx, dst);
3710 assert kind == owned;
3711 ret move_val(bcx, DROP_EXISTING, addr, src_r,
3712 ty::expr_ty(bcx_tcx(bcx), src));
3714 ast::expr_swap(dst, src) {
3715 assert dest == ignore;
3716 let lhs_res = trans_lval(bcx, dst);
3717 assert lhs_res.kind == owned;
3718 let rhs_res = trans_lval(lhs_res.bcx, src);
3719 let t = ty::expr_ty(tcx, src);
3720 let {bcx: bcx, val: tmp_alloc} = alloc_ty(rhs_res.bcx, t);
3721 // Swap through a temporary.
3722 bcx = move_val(bcx, INIT, tmp_alloc, lhs_res, t);
3723 bcx = move_val(bcx, INIT, lhs_res.val, rhs_res, t);
3724 ret move_val(bcx, INIT, rhs_res.val, lval_owned(bcx, tmp_alloc), t);
3726 ast::expr_assign_op(op, dst, src) {
3727 assert dest == ignore;
3728 ret trans_assign_op(bcx, op, dst, src);
3733 fn lval_to_dps(bcx: @block_ctxt, e: @ast::expr, dest: dest) -> @block_ctxt {
3734 let lv = trans_lval(bcx, e), ccx = bcx_ccx(bcx);
3735 let {bcx, val, kind} = lv;
3736 let last_use = kind == owned && ccx.last_uses.contains_key(e.id);
3737 let ty = ty::expr_ty(ccx.tcx, e);
3740 if kind == temporary {
3741 revoke_clean(bcx, val);
3743 } else if last_use {
3744 *cell = Load(bcx, val);
3745 if ty::type_needs_drop(ccx.tcx, ty) {
3746 bcx = zero_alloca(bcx, val, ty);
3749 if kind == owned { val = Load(bcx, val); }
3750 let {bcx: cx, val} = take_ty_immediate(bcx, val, ty);
3756 bcx = store_temp_expr(bcx, INIT, loc, lv, ty, last_use);
3763 fn do_spill(cx: @block_ctxt, v: ValueRef, t: ty::t) -> result {
3764 // We have a value but we have to spill it, and root it, to pass by alias.
3767 if ty::type_is_bot(bcx_tcx(bcx), t) {
3768 ret rslt(bcx, C_null(T_ptr(T_i8())));
3771 let r = alloc_ty(bcx, t);
3775 Store(bcx, v, llptr);
3777 ret rslt(bcx, llptr);
3780 // Since this function does *not* root, it is the caller's responsibility to
3781 // ensure that the referent is pointed to by a root.
3782 fn do_spill_noroot(cx: @block_ctxt, v: ValueRef) -> ValueRef {
3783 let llptr = alloca(cx, val_ty(v));
3784 Store(cx, v, llptr);
3788 fn spill_if_immediate(cx: @block_ctxt, v: ValueRef, t: ty::t) -> result {
3789 if ty::type_is_immediate(bcx_tcx(cx), t) { ret do_spill(cx, v, t); }
3793 fn load_if_immediate(cx: @block_ctxt, v: ValueRef, t: ty::t) -> ValueRef {
3794 if ty::type_is_immediate(bcx_tcx(cx), t) { ret Load(cx, v); }
3798 fn trans_log(lvl: @ast::expr, cx: @block_ctxt, e: @ast::expr) -> @block_ctxt {
3799 let ccx = bcx_ccx(cx);
3800 let lcx = cx.fcx.lcx;
3801 let modname = str::connect(lcx.module_path, "::");
3802 let global = if lcx.ccx.module_data.contains_key(modname) {
3803 lcx.ccx.module_data.get(modname)
3805 let s = link::mangle_internal_name_by_path_and_seq(
3806 lcx.ccx, lcx.module_path, "loglevel");
3807 let global = str::as_buf(s, {|buf|
3808 llvm::LLVMAddGlobal(lcx.ccx.llmod, T_i32(), buf)
3810 llvm::LLVMSetGlobalConstant(global, False);
3811 llvm::LLVMSetInitializer(global, C_null(T_i32()));
3812 llvm::LLVMSetLinkage(global,
3813 lib::llvm::LLVMInternalLinkage as llvm::Linkage);
3814 lcx.ccx.module_data.insert(modname, global);
3817 let level_cx = new_scope_block_ctxt(cx, "level");
3818 let log_cx = new_scope_block_ctxt(cx, "log");
3819 let after_cx = new_sub_block_ctxt(cx, "after");
3820 let load = Load(cx, global);
3822 Br(cx, level_cx.llbb);
3823 let level_res = trans_temp_expr(level_cx, lvl);
3824 let test = ICmp(level_res.bcx, lib::llvm::LLVMIntUGE,
3825 load, level_res.val);
3827 CondBr(level_res.bcx, test, log_cx.llbb, after_cx.llbb);
3828 let sub = trans_temp_expr(log_cx, e);
3829 let e_ty = ty::expr_ty(bcx_tcx(cx), e);
3830 let log_bcx = sub.bcx;
3832 let ti = none::<@tydesc_info>;
3833 let r = get_tydesc(log_bcx, e_ty, false, tps_normal, ti).result;
3835 let lltydesc = r.val;
3837 // Call the polymorphic log function.
3838 r = spill_if_immediate(log_bcx, sub.val, e_ty);
3840 let llvalptr = r.val;
3841 let llval_i8 = PointerCast(log_bcx, llvalptr, T_ptr(T_i8()));
3843 Call(log_bcx, ccx.upcalls.log_type,
3844 [lltydesc, llval_i8, level_res.val]);
3846 log_bcx = trans_block_cleanups(log_bcx, log_cx);
3847 Br(log_bcx, after_cx.llbb);
3848 ret trans_block_cleanups(after_cx, level_cx);
3851 fn trans_check_expr(cx: @block_ctxt, e: @ast::expr, s: str) -> @block_ctxt {
3852 let cond_res = trans_temp_expr(cx, e);
3853 let expr_str = s + " " + expr_to_str(e) + " failed";
3854 let fail_cx = new_sub_block_ctxt(cx, "fail");
3855 trans_fail(fail_cx, some::<span>(e.span), expr_str);
3856 let next_cx = new_sub_block_ctxt(cx, "next");
3857 CondBr(cond_res.bcx, cond_res.val, next_cx.llbb, fail_cx.llbb);
3861 fn trans_fail_expr(bcx: @block_ctxt, sp_opt: option::t<span>,
3862 fail_expr: option::t<@ast::expr>) -> @block_ctxt {
3866 let tcx = bcx_tcx(bcx);
3867 let expr_res = trans_temp_expr(bcx, expr);
3868 let e_ty = ty::expr_ty(tcx, expr);
3871 if ty::type_is_str(tcx, e_ty) {
3872 let data = tvec::get_dataptr(
3873 bcx, expr_res.val, type_of_or_i8(
3874 bcx, ty::mk_mach_uint(tcx, ast::ty_u8)));
3875 ret trans_fail_value(bcx, sp_opt, data);
3876 } else if bcx.unreachable {
3879 bcx_ccx(bcx).sess.span_bug(
3880 expr.span, "fail called with unsupported type " +
3881 ty_to_str(tcx, e_ty));
3884 _ { ret trans_fail(bcx, sp_opt, "explicit failure"); }
3888 fn trans_fail(bcx: @block_ctxt, sp_opt: option::t<span>, fail_str: str) ->
3890 let V_fail_str = C_cstr(bcx_ccx(bcx), fail_str);
3891 ret trans_fail_value(bcx, sp_opt, V_fail_str);
3894 fn trans_fail_value(bcx: @block_ctxt, sp_opt: option::t<span>,
3895 V_fail_str: ValueRef) -> @block_ctxt {
3896 let ccx = bcx_ccx(bcx);
3901 let loc = bcx_ccx(bcx).sess.lookup_pos(sp.lo);
3902 V_filename = C_cstr(bcx_ccx(bcx), loc.filename);
3903 V_line = loc.line as int;
3905 none. { V_filename = C_cstr(bcx_ccx(bcx), "<runtime>"); V_line = 0; }
3907 let V_str = PointerCast(bcx, V_fail_str, T_ptr(T_i8()));
3908 V_filename = PointerCast(bcx, V_filename, T_ptr(T_i8()));
3909 let args = [V_str, V_filename, C_int(ccx, V_line)];
3910 let bcx = invoke(bcx, bcx_ccx(bcx).upcalls._fail, args);
3915 fn trans_break_cont(sp: span, bcx: @block_ctxt, to_end: bool)
3917 // Locate closest loop block, outputting cleanup as we go.
3918 let cleanup_cx = bcx, bcx = bcx;
3920 bcx = trans_block_cleanups(bcx, cleanup_cx);
3921 alt copy cleanup_cx.kind {
3922 LOOP_SCOPE_BLOCK(_cont, _break) {
3924 Br(bcx, _break.llbb);
3927 option::some(_cont) { Br(bcx, _cont.llbb); }
3928 _ { Br(bcx, cleanup_cx.llbb); }
3935 alt cleanup_cx.parent {
3936 parent_some(cx) { cleanup_cx = cx; }
3938 bcx_ccx(bcx).sess.span_fatal
3939 (sp, if to_end { "Break" } else { "Cont" } +
3946 // If we get here without returning, it's a bug
3947 bcx_ccx(bcx).sess.bug("in trans::trans_break_cont()");
3950 fn trans_break(sp: span, cx: @block_ctxt) -> @block_ctxt {
3951 ret trans_break_cont(sp, cx, true);
3954 fn trans_cont(sp: span, cx: @block_ctxt) -> @block_ctxt {
3955 ret trans_break_cont(sp, cx, false);
3958 fn trans_ret(bcx: @block_ctxt, e: option::t<@ast::expr>) -> @block_ctxt {
3959 let cleanup_cx = bcx, bcx = bcx;
3961 some(x) { bcx = trans_expr_save_in(bcx, x, bcx.fcx.llretptr); }
3964 // run all cleanups and back out.
3966 let more_cleanups: bool = true;
3967 while more_cleanups {
3968 bcx = trans_block_cleanups(bcx, cleanup_cx);
3969 alt cleanup_cx.parent {
3970 parent_some(b) { cleanup_cx = b; }
3971 parent_none. { more_cleanups = false; }
3979 fn build_return(bcx: @block_ctxt) { Br(bcx, bcx_fcx(bcx).llreturn); }
3981 // fn trans_be(cx: &@block_ctxt, e: &@ast::expr) -> result {
3982 fn trans_be(cx: @block_ctxt, e: @ast::expr) : ast_util::is_call_expr(e) ->
3984 // FIXME: Turn this into a real tail call once
3985 // calling convention issues are settled
3986 ret trans_ret(cx, some(e));
3989 fn init_local(bcx: @block_ctxt, local: @ast::local) -> @block_ctxt {
3990 let ty = node_id_type(bcx_ccx(bcx), local.node.id);
3991 let llptr = alt bcx.fcx.lllocals.find(local.node.id) {
3992 some(local_mem(v)) { v }
3993 // This is a local that is kept immediate
3995 let initexpr = alt local.node.init { some({expr, _}) { expr } };
3996 let {bcx, val, kind} = trans_temp_lval(bcx, initexpr);
3997 if kind != temporary {
3998 if kind == owned { val = Load(bcx, val); }
3999 let rs = take_ty_immediate(bcx, val, ty);
4000 bcx = rs.bcx; val = rs.val;
4001 add_clean_temp(bcx, val, ty);
4003 bcx.fcx.lllocals.insert(local.node.pat.id, local_imm(val));
4009 alt local.node.init {
4011 if init.op == ast::init_assign || !expr_is_lval(bcx, init.expr) {
4012 bcx = trans_expr_save_in(bcx, init.expr, llptr);
4013 } else { // This is a move from an lval, must perform an actual move
4014 let sub = trans_lval(bcx, init.expr);
4015 bcx = move_val(sub.bcx, INIT, llptr, sub, ty);
4018 _ { bcx = zero_alloca(bcx, llptr, ty); }
4020 // Make a note to drop this slot on the way out.
4021 add_clean(bcx, llptr, ty);
4022 ret trans_alt::bind_irrefutable_pat(bcx, local.node.pat, llptr, false);
4025 fn init_ref_local(bcx: @block_ctxt, local: @ast::local) -> @block_ctxt {
4026 let init_expr = option::get(local.node.init).expr;
4027 let {bcx, val, kind} = trans_lval(bcx, init_expr);
4029 owned_imm. { val = do_spill_noroot(bcx, val); }
4032 ret trans_alt::bind_irrefutable_pat(bcx, local.node.pat, val, false);
4035 fn zero_alloca(cx: @block_ctxt, llptr: ValueRef, t: ty::t)
4038 let ccx = bcx_ccx(cx);
4039 if check type_has_static_size(ccx, t) {
4041 let llty = type_of(ccx, sp, t);
4042 Store(bcx, C_null(llty), llptr);
4044 let llsz = size_of(bcx, t);
4045 // FIXME passing in the align here is correct, but causes issue #843
4046 // let llalign = align_of(llsz.bcx, t);
4047 bcx = call_bzero(llsz.bcx, llptr, llsz.val, C_int(ccx, 0)).bcx;
4052 fn trans_stmt(cx: @block_ctxt, s: ast::stmt) -> @block_ctxt {
4053 // FIXME Fill in cx.sp
4055 if (!bcx_ccx(cx).sess.get_opts().no_asm_comments) {
4056 add_span_comment(cx, s.span, stmt_to_str(s));
4060 debuginfo::update_source_pos(cx, s.span);
4063 ast::stmt_expr(e, _) | ast::stmt_semi(e, _) {
4064 bcx = trans_expr(cx, e, ignore);
4066 ast::stmt_decl(d, _) {
4068 ast::decl_local(locals) {
4069 for (style, local) in locals {
4070 if style == ast::let_copy {
4071 bcx = init_local(bcx, local);
4073 bcx = init_ref_local(bcx, local);
4075 if bcx_ccx(cx).sess.get_opts().extra_debuginfo {
4076 debuginfo::create_local_var(bcx, local);
4080 ast::decl_item(i) { trans_item(cx.fcx.lcx, *i); }
4083 _ { bcx_ccx(cx).sess.unimpl("stmt variant"); }
4089 // You probably don't want to use this one. See the
4090 // next three functions instead.
4091 fn new_block_ctxt(cx: @fn_ctxt, parent: block_parent, kind: block_kind,
4092 name: str) -> @block_ctxt {
4094 if cx.lcx.ccx.sess.get_opts().save_temps ||
4095 cx.lcx.ccx.sess.get_opts().debuginfo {
4096 s = cx.lcx.ccx.names.next(name);
4098 let llbb: BasicBlockRef =
4099 str::as_buf(s, {|buf| llvm::LLVMAppendBasicBlock(cx.llfn, buf) });
4100 let bcx = @{llbb: llbb,
4101 mutable terminated: false,
4102 mutable unreachable: false,
4105 mutable cleanups: [],
4106 mutable lpad_dirty: true,
4107 mutable lpad: option::none,
4112 if cx.unreachable { Unreachable(bcx); }
4120 // Use this when you're at the top block of a function or the like.
4121 fn new_top_block_ctxt(fcx: @fn_ctxt) -> @block_ctxt {
4122 ret new_block_ctxt(fcx, parent_none, SCOPE_BLOCK, "function top level");
4126 // Use this when you're at a curly-brace or similar lexical scope.
4127 fn new_scope_block_ctxt(bcx: @block_ctxt, n: str) -> @block_ctxt {
4128 ret new_block_ctxt(bcx.fcx, parent_some(bcx), SCOPE_BLOCK, n);
4131 fn new_loop_scope_block_ctxt(bcx: @block_ctxt, _cont: option::t<@block_ctxt>,
4132 _break: @block_ctxt, n: str) -> @block_ctxt {
4133 ret new_block_ctxt(bcx.fcx, parent_some(bcx),
4134 LOOP_SCOPE_BLOCK(_cont, _break), n);
4138 // Use this when you're making a general CFG BB within a scope.
4139 fn new_sub_block_ctxt(bcx: @block_ctxt, n: str) -> @block_ctxt {
4140 ret new_block_ctxt(bcx.fcx, parent_some(bcx), NON_SCOPE_BLOCK, n);
4143 fn new_raw_block_ctxt(fcx: @fn_ctxt, llbb: BasicBlockRef) -> @block_ctxt {
4145 mutable terminated: false,
4146 mutable unreachable: false,
4147 parent: parent_none,
4148 kind: NON_SCOPE_BLOCK,
4149 mutable cleanups: [],
4150 mutable lpad_dirty: true,
4151 mutable lpad: option::none,
4157 // trans_block_cleanups: Go through all the cleanups attached to this
4158 // block_ctxt and execute them.
4160 // When translating a block that introdces new variables during its scope, we
4161 // need to make sure those variables go out of scope when the block ends. We
4162 // do that by running a 'cleanup' function for each variable.
4163 // trans_block_cleanups runs all the cleanup functions for the block.
4164 fn trans_block_cleanups(bcx: @block_ctxt, cleanup_cx: @block_ctxt) ->
4166 if bcx.unreachable { ret bcx; }
4167 if cleanup_cx.kind == NON_SCOPE_BLOCK {
4168 assert (vec::len::<cleanup>(cleanup_cx.cleanups) == 0u);
4170 let i = vec::len::<cleanup>(cleanup_cx.cleanups), bcx = bcx;
4173 let c = cleanup_cx.cleanups[i];
4175 clean(cfn) { bcx = cfn(bcx); }
4176 clean_temp(_, cfn) { bcx = cfn(bcx); }
4182 fn trans_fn_cleanups(fcx: @fn_ctxt, cx: @block_ctxt) {
4183 alt fcx.llobstacktoken {
4185 let lltoken = lltoken_; // satisfy alias checker
4186 Call(cx, fcx_ccx(fcx).upcalls.dynastack_free, [lltoken]);
4188 none. {/* nothing to do */ }
4192 fn block_locals(b: ast::blk, it: block(@ast::local)) {
4193 for s: @ast::stmt in b.node.stmts {
4195 ast::stmt_decl(d, _) {
4197 ast::decl_local(locals) {
4198 for (style, local) in locals {
4199 if style == ast::let_copy { it(local); }
4202 _ {/* fall through */ }
4205 _ {/* fall through */ }
4210 fn llstaticallocas_block_ctxt(fcx: @fn_ctxt) -> @block_ctxt {
4211 ret @{llbb: fcx.llstaticallocas,
4212 mutable terminated: false,
4213 mutable unreachable: false,
4214 parent: parent_none,
4216 mutable cleanups: [],
4217 mutable lpad_dirty: true,
4218 mutable lpad: option::none,
4223 fn llderivedtydescs_block_ctxt(fcx: @fn_ctxt) -> @block_ctxt {
4224 ret @{llbb: fcx.llderivedtydescs,
4225 mutable terminated: false,
4226 mutable unreachable: false,
4227 parent: parent_none,
4229 mutable cleanups: [],
4230 mutable lpad_dirty: true,
4231 mutable lpad: option::none,
4237 fn alloc_ty(cx: @block_ctxt, t: ty::t) -> result {
4239 let ccx = bcx_ccx(cx);
4241 if check type_has_static_size(ccx, t) {
4243 alloca(bcx, type_of(ccx, sp, t))
4245 // NB: we have to run this particular 'size_of' in a
4246 // block_ctxt built on the llderivedtydescs block for the fn,
4247 // so that the size dominates the array_alloca that
4250 let n = size_of(llderivedtydescs_block_ctxt(bcx.fcx), t);
4251 bcx.fcx.llderivedtydescs = n.bcx.llbb;
4252 dynastack_alloca(bcx, T_i8(), n.val, t)
4255 // NB: since we've pushed all size calculations in this
4256 // function up to the alloca block, we actually return the
4257 // block passed into us unmodified; it doesn't really
4258 // have to be passed-and-returned here, but it fits
4259 // past caller conventions and may well make sense again,
4260 // so we leave it as-is.
4262 if bcx_tcx(cx).sess.get_opts().do_gc {
4263 bcx = gc::add_gc_root(bcx, val, t);
4269 fn alloc_local(cx: @block_ctxt, local: @ast::local) -> @block_ctxt {
4270 let t = node_id_type(bcx_ccx(cx), local.node.id);
4271 let is_simple = alt local.node.pat.node {
4272 ast::pat_bind(_, none.) { true } _ { false }
4274 // Do not allocate space for locals that can be kept immediate.
4275 let ccx = bcx_ccx(cx);
4276 if is_simple && !ccx.mut_map.contains_key(local.node.pat.id) &&
4277 !ccx.last_uses.contains_key(local.node.pat.id) &&
4278 ty::type_is_immediate(ccx.tcx, t) {
4279 alt local.node.init {
4280 some({op: ast::init_assign., _}) { ret cx; }
4284 let r = alloc_ty(cx, t);
4285 alt local.node.pat.node {
4286 ast::pat_bind(ident, none.) {
4287 if bcx_ccx(cx).sess.get_opts().debuginfo {
4288 let _: () = str::as_buf(ident, {|buf|
4289 llvm::LLVMSetValueName(r.val, buf)
4295 cx.fcx.lllocals.insert(local.node.id, local_mem(r.val));
4299 fn trans_block(bcx: @block_ctxt, b: ast::blk) -> @block_ctxt {
4300 trans_block_dps(bcx, b, ignore)
4303 fn trans_block_dps(bcx: @block_ctxt, b: ast::blk, dest: dest)
4306 block_locals(b) {|local| bcx = alloc_local(bcx, local); };
4307 for s: @ast::stmt in b.node.stmts {
4308 debuginfo::update_source_pos(bcx, b.span);
4309 bcx = trans_stmt(bcx, *s);
4313 let bt = ty::type_is_bot(bcx_tcx(bcx), ty::expr_ty(bcx_tcx(bcx), e));
4314 debuginfo::update_source_pos(bcx, e.span);
4315 bcx = trans_expr(bcx, e, bt ? ignore : dest);
4317 _ { assert dest == ignore || bcx.unreachable; }
4319 let rv = trans_block_cleanups(bcx, find_scope_cx(bcx));
4323 fn new_local_ctxt(ccx: @crate_ctxt) -> @local_ctxt {
4324 let pth: [str] = [];
4326 module_path: [ccx.link_meta.name],
4333 // Creates the standard quartet of basic blocks: static allocas, copy args,
4334 // derived tydescs, and dynamic allocas.
4335 fn mk_standard_basic_blocks(llfn: ValueRef) ->
4340 rt: BasicBlockRef} {
4342 str::as_buf("static_allocas",
4343 {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4345 str::as_buf("load_env",
4346 {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4348 str::as_buf("derived_tydescs",
4349 {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4351 str::as_buf("dynamic_allocas",
4352 {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) }),
4354 str::as_buf("return",
4355 {|buf| llvm::LLVMAppendBasicBlock(llfn, buf) })};
4359 // NB: must keep 4 fns in sync:
4362 // - create_llargs_for_fn_args.
4365 fn new_fn_ctxt_w_id(cx: @local_ctxt, sp: span, llfndecl: ValueRef,
4366 id: ast::node_id, rstyle: ast::ret_style)
4368 let llbbs = mk_standard_basic_blocks(llfndecl);
4369 ret @{llfn: llfndecl,
4370 llenv: llvm::LLVMGetParam(llfndecl, 1u),
4371 llretptr: llvm::LLVMGetParam(llfndecl, 0u),
4372 mutable llstaticallocas: llbbs.sa,
4373 mutable llloadenv: llbbs.ca,
4374 mutable llderivedtydescs_first: llbbs.dt,
4375 mutable llderivedtydescs: llbbs.dt,
4376 mutable lldynamicallocas: llbbs.da,
4377 mutable llreturn: llbbs.rt,
4378 mutable llobstacktoken: none::<ValueRef>,
4379 mutable llself: none::<val_self_pair>,
4380 llargs: new_int_hash::<local_val>(),
4381 llobjfields: new_int_hash::<ValueRef>(),
4382 lllocals: new_int_hash::<local_val>(),
4383 llupvars: new_int_hash::<ValueRef>(),
4384 mutable lltyparams: [],
4385 derived_tydescs: ty::new_ty_hash(),
4392 fn new_fn_ctxt(cx: @local_ctxt, sp: span, llfndecl: ValueRef) -> @fn_ctxt {
4393 ret new_fn_ctxt_w_id(cx, sp, llfndecl, -1, ast::return_val);
4396 // NB: must keep 4 fns in sync:
4399 // - create_llargs_for_fn_args.
4403 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
4404 // allocas created for them.
4406 // When we translate a function, we need to map its incoming arguments to the
4407 // spaces that have been created for them (by code in the llallocas field of
4408 // the function's fn_ctxt). create_llargs_for_fn_args populates the llargs
4409 // field of the fn_ctxt with
4410 fn create_llargs_for_fn_args(cx: @fn_ctxt, ty_self: self_arg,
4411 args: [ast::arg], ty_params: [ast::ty_param]) {
4412 // Skip the implicit arguments 0, and 1. TODO: Pull out 2u and define
4413 // it as a constant, since we're using it in several places in trans this
4417 obj_self(tt) | impl_self(tt) {
4418 cx.llself = some({v: cx.llenv, t: tt});
4425 for tp in ty_params {
4426 let lltydesc = llvm::LLVMGetParam(cx.llfn, arg_n), dicts = none;
4428 for bound in *fcx_tcx(cx).ty_param_bounds.get(tp.id) {
4430 ty::bound_iface(_) {
4431 let dict = llvm::LLVMGetParam(cx.llfn, arg_n);
4433 dicts = some(alt dicts {
4435 some(ds) { ds + [dict] }
4441 cx.lltyparams += [{desc: lltydesc, dicts: dicts}];
4446 // Populate the llargs field of the function context with the ValueRefs
4447 // that we get from llvm::LLVMGetParam for each argument.
4448 for arg: ast::arg in args {
4449 let llarg = llvm::LLVMGetParam(cx.llfn, arg_n);
4450 assert (llarg as int != 0);
4451 // Note that this uses local_mem even for things passed by value.
4452 // copy_args_to_allocas will overwrite the table entry with local_imm
4453 // before it's actually used.
4454 cx.llargs.insert(arg.id, local_mem(llarg));
4459 fn copy_args_to_allocas(fcx: @fn_ctxt, bcx: @block_ctxt, args: [ast::arg],
4460 arg_tys: [ty::arg]) -> @block_ctxt {
4461 if fcx_ccx(fcx).sess.get_opts().extra_debuginfo {
4462 llvm::LLVMAddAttribute(llvm::LLVMGetFirstParam(fcx.llfn),
4463 lib::llvm::LLVMStructRetAttribute as
4464 lib::llvm::llvm::Attribute);
4466 let arg_n: uint = 0u, bcx = bcx;
4467 for arg in arg_tys {
4468 let id = args[arg_n].id;
4469 let argval = alt fcx.llargs.get(id) { local_mem(v) { v } };
4471 ast::by_mut_ref. { }
4472 ast::by_move. | ast::by_copy. { add_clean(bcx, argval, arg.ty); }
4474 if !ty::type_is_immediate(bcx_tcx(bcx), arg.ty) {
4475 let {bcx: cx, val: alloc} = alloc_ty(bcx, arg.ty);
4477 Store(bcx, argval, alloc);
4478 fcx.llargs.insert(id, local_mem(alloc));
4480 fcx.llargs.insert(id, local_imm(argval));
4485 if fcx_ccx(fcx).sess.get_opts().extra_debuginfo {
4486 debuginfo::create_arg(bcx, args[arg_n]);
4493 fn arg_tys_of_fn(ccx: @crate_ctxt, id: ast::node_id) -> [ty::arg] {
4494 alt ty::struct(ccx.tcx, ty::node_id_to_type(ccx.tcx, id)) {
4495 ty::ty_fn({inputs, _}) { inputs }
4499 fn populate_fn_ctxt_from_llself(fcx: @fn_ctxt, llself: val_self_pair) {
4500 let ccx = fcx_ccx(fcx);
4501 let bcx = llstaticallocas_block_ctxt(fcx);
4502 let field_tys: [ty::t] = [];
4503 for f: ast::obj_field in bcx.fcx.lcx.obj_fields {
4504 field_tys += [node_id_type(ccx, f.id)];
4506 // Synthesize a tuple type for the fields so that GEP_tup_like() can work
4509 let fields_tup_ty = ty::mk_tup(fcx.lcx.ccx.tcx, field_tys);
4510 let n_typarams = vec::len::<ast::ty_param>(bcx.fcx.lcx.obj_typarams);
4511 let llobj_box_ty: TypeRef = T_obj_ptr(ccx, n_typarams);
4512 let box_cell = GEPi(bcx, llself.v, [0, abi::obj_field_box]);
4513 let box_ptr = Load(bcx, box_cell);
4514 box_ptr = PointerCast(bcx, box_ptr, llobj_box_ty);
4516 GEPi(bcx, box_ptr, [0, abi::box_rc_field_body,
4517 abi::obj_body_elt_typarams]);
4519 // The object fields immediately follow the type parameters, so we skip
4520 // over them to get the pointer.
4522 PointerCast(bcx, GEPi(bcx, obj_typarams, [1]),
4523 T_ptr(type_of_or_i8(bcx, fields_tup_ty)));
4526 for p: ast::ty_param in fcx.lcx.obj_typarams {
4527 let lltyparam: ValueRef =
4528 GEPi(bcx, obj_typarams, [0, i]);
4529 lltyparam = Load(bcx, lltyparam);
4530 fcx.lltyparams += [{desc: lltyparam, dicts: none}];
4534 for f: ast::obj_field in fcx.lcx.obj_fields {
4535 // FIXME: silly check
4536 check type_is_tup_like(bcx, fields_tup_ty);
4537 let rslt = GEP_tup_like(bcx, fields_tup_ty, obj_fields, [0, i]);
4538 bcx = llstaticallocas_block_ctxt(fcx);
4539 let llfield = rslt.val;
4540 fcx.llobjfields.insert(f.id, llfield);
4543 fcx.llstaticallocas = bcx.llbb;
4547 // Ties up the llstaticallocas -> llloadenv -> llderivedtydescs ->
4548 // lldynamicallocas -> lltop edges, and builds the return block.
4549 fn finish_fn(fcx: @fn_ctxt, lltop: BasicBlockRef) {
4550 Br(new_raw_block_ctxt(fcx, fcx.llstaticallocas), fcx.llloadenv);
4551 Br(new_raw_block_ctxt(fcx, fcx.llloadenv), fcx.llderivedtydescs_first);
4552 Br(new_raw_block_ctxt(fcx, fcx.llderivedtydescs), fcx.lldynamicallocas);
4553 Br(new_raw_block_ctxt(fcx, fcx.lldynamicallocas), lltop);
4555 let ret_cx = new_raw_block_ctxt(fcx, fcx.llreturn);
4556 trans_fn_cleanups(fcx, ret_cx);
4560 tag self_arg { obj_self(ty::t); impl_self(ty::t); no_self; }
4562 // trans_closure: Builds an LLVM function out of a source function.
4563 // If the function closes over its environment a closure will be
4565 fn trans_closure(cx: @local_ctxt, sp: span, decl: ast::fn_decl,
4566 body: ast::blk, llfndecl: ValueRef,
4567 ty_self: self_arg, ty_params: [ast::ty_param],
4568 id: ast::node_id, maybe_load_env: block(@fn_ctxt)) {
4569 set_uwtable(llfndecl);
4571 // Set up arguments to the function.
4572 let fcx = new_fn_ctxt_w_id(cx, sp, llfndecl, id, decl.cf);
4573 create_llargs_for_fn_args(fcx, ty_self, decl.inputs, ty_params);
4576 populate_fn_ctxt_from_llself(fcx, option::get(fcx.llself));
4581 // Create the first basic block in the function and keep a handle on it to
4582 // pass to finish_fn later.
4583 let bcx = new_top_block_ctxt(fcx);
4584 let lltop = bcx.llbb;
4585 let block_ty = node_id_type(cx.ccx, body.node.id);
4587 let arg_tys = arg_tys_of_fn(fcx.lcx.ccx, id);
4588 bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, arg_tys);
4590 maybe_load_env(fcx);
4592 // This call to trans_block is the place where we bridge between
4593 // translation calls that don't have a return value (trans_crate,
4594 // trans_mod, trans_item, trans_obj, et cetera) and those that do
4595 // (trans_block, trans_expr, et cetera).
4596 if ty::type_is_bot(cx.ccx.tcx, block_ty) ||
4597 ty::type_is_nil(cx.ccx.tcx, block_ty) ||
4598 option::is_none(body.node.expr) {
4599 bcx = trans_block_dps(bcx, body, ignore);
4600 } else if ty::type_is_immediate(cx.ccx.tcx, block_ty) {
4601 let cell = empty_dest_cell();
4602 bcx = trans_block_dps(bcx, body, by_val(cell));
4603 Store(bcx, *cell, fcx.llretptr);
4605 bcx = trans_block_dps(bcx, body, save_in(fcx.llretptr));
4608 // FIXME: until LLVM has a unit type, we are moving around
4609 // C_nil values rather than their void type.
4610 if !bcx.unreachable { build_return(bcx); }
4611 // Insert the mandatory first few basic blocks before lltop.
4612 finish_fn(fcx, lltop);
4615 // trans_fn: creates an LLVM function corresponding to a source language
4617 fn trans_fn(cx: @local_ctxt, sp: span, decl: ast::fn_decl, body: ast::blk,
4618 llfndecl: ValueRef, ty_self: self_arg, ty_params: [ast::ty_param],
4620 let do_time = cx.ccx.sess.get_opts().stats;
4621 let start = do_time ? time::get_time() : {sec: 0u32, usec: 0u32};
4622 let fcx = option::none;
4623 trans_closure(cx, sp, decl, body, llfndecl, ty_self, ty_params, id,
4624 {|new_fcx| fcx = option::some(new_fcx);});
4625 if cx.ccx.sess.get_opts().extra_debuginfo {
4626 debuginfo::create_function(option::get(fcx));
4629 let end = time::get_time();
4630 log_fn_time(cx.ccx, str::connect(cx.path, "::"), start, end);
4634 fn trans_res_ctor(cx: @local_ctxt, sp: span, dtor: ast::fn_decl,
4635 ctor_id: ast::node_id, ty_params: [ast::ty_param]) {
4638 // Create a function for the constructor
4640 alt ccx.item_ids.find(ctor_id) {
4641 some(x) { llctor_decl = x; }
4642 _ { ccx.sess.span_fatal(sp, "unbound ctor_id in trans_res_ctor"); }
4644 let fcx = new_fn_ctxt(cx, sp, llctor_decl);
4645 let ret_t = ty::ret_ty_of_fn(cx.ccx.tcx, ctor_id);
4646 create_llargs_for_fn_args(fcx, no_self, dtor.inputs, ty_params);
4647 let bcx = new_top_block_ctxt(fcx);
4648 let lltop = bcx.llbb;
4649 let arg_t = arg_tys_of_fn(ccx, ctor_id)[0].ty;
4650 let tup_t = ty::mk_tup(ccx.tcx, [ty::mk_int(ccx.tcx), arg_t]);
4651 let arg = alt fcx.llargs.find(dtor.inputs[0].id) {
4652 some(local_mem(x)) { x }
4654 let llretptr = fcx.llretptr;
4655 if ty::type_has_dynamic_size(ccx.tcx, ret_t) {
4656 let llret_t = T_ptr(T_struct([ccx.int_type, llvm::LLVMTypeOf(arg)]));
4657 llretptr = BitCast(bcx, llretptr, llret_t);
4660 // FIXME: silly checks
4661 check type_is_tup_like(bcx, tup_t);
4662 let {bcx, val: dst} = GEP_tup_like(bcx, tup_t, llretptr, [0, 1]);
4663 bcx = memmove_ty(bcx, dst, arg, arg_t);
4664 check type_is_tup_like(bcx, tup_t);
4665 let flag = GEP_tup_like(bcx, tup_t, llretptr, [0, 0]);
4667 // FIXME #1184: Resource flag is larger than necessary
4668 let one = C_int(ccx, 1);
4669 Store(bcx, one, flag.val);
4671 finish_fn(fcx, lltop);
4675 fn trans_tag_variant(cx: @local_ctxt, tag_id: ast::node_id,
4676 variant: ast::variant, index: int, is_degen: bool,
4677 ty_params: [ast::ty_param]) {
4680 if vec::len::<ast::variant_arg>(variant.node.args) == 0u {
4681 ret; // nullary constructors are just constants
4684 // Translate variant arguments to function arguments.
4686 let fn_args: [ast::arg] = [];
4688 for varg: ast::variant_arg in variant.node.args {
4690 [{mode: ast::by_copy,
4692 ident: "arg" + uint::to_str(i, 10u),
4695 assert (ccx.item_ids.contains_key(variant.node.id));
4696 let llfndecl: ValueRef;
4697 alt ccx.item_ids.find(variant.node.id) {
4698 some(x) { llfndecl = x; }
4700 ccx.sess.span_fatal(variant.span,
4701 "unbound variant id in trans_tag_variant");
4704 let fcx = new_fn_ctxt(cx, variant.span, llfndecl);
4705 create_llargs_for_fn_args(fcx, no_self, fn_args, ty_params);
4706 let ty_param_substs: [ty::t] = [];
4708 for tp: ast::ty_param in ty_params {
4709 ty_param_substs += [ty::mk_param(ccx.tcx, i,
4710 ast_util::local_def(tp.id))];
4713 let arg_tys = arg_tys_of_fn(ccx, variant.node.id);
4714 let bcx = new_top_block_ctxt(fcx);
4715 let lltop = bcx.llbb;
4716 bcx = copy_args_to_allocas(fcx, bcx, fn_args, arg_tys);
4718 // Cast the tag to a type we can GEP into.
4724 PointerCast(bcx, fcx.llretptr, T_opaque_tag_ptr(ccx));
4725 let lldiscrimptr = GEPi(bcx, lltagptr, [0, 0]);
4726 Store(bcx, C_int(ccx, index), lldiscrimptr);
4727 GEPi(bcx, lltagptr, [0, 1])
4730 let t_id = ast_util::local_def(tag_id);
4731 let v_id = ast_util::local_def(variant.node.id);
4732 for va: ast::variant_arg in variant.node.args {
4733 check (valid_variant_index(i, bcx, t_id, v_id));
4734 let rslt = GEP_tag(bcx, llblobptr, t_id, v_id, ty_param_substs, i);
4736 let lldestptr = rslt.val;
4737 // If this argument to this function is a tag, it'll have come in to
4738 // this function as an opaque blob due to the way that type_of()
4739 // works. So we have to cast to the destination's view of the type.
4740 let llarg = alt fcx.llargs.find(va.id) { some(local_mem(x)) { x } };
4741 let arg_ty = arg_tys[i].ty;
4742 if ty::type_contains_params(bcx_tcx(bcx), arg_ty) {
4743 lldestptr = PointerCast(bcx, lldestptr, val_ty(llarg));
4745 bcx = memmove_ty(bcx, lldestptr, llarg, arg_ty);
4749 finish_fn(fcx, lltop);
4753 // FIXME: this should do some structural hash-consing to avoid
4754 // duplicate constants. I think. Maybe LLVM has a magical mode
4755 // that does so later on?
4756 fn trans_const_expr(cx: @crate_ctxt, e: @ast::expr) -> ValueRef {
4758 ast::expr_lit(lit) { ret trans_crate_lit(cx, *lit); }
4759 ast::expr_binary(b, e1, e2) {
4760 let te1 = trans_const_expr(cx, e1);
4761 let te2 = trans_const_expr(cx, e2);
4762 /* Neither type is bottom, and we expect them to be unified already,
4763 * so the following is safe. */
4764 let ty = ty::expr_ty(ccx_tcx(cx), e1);
4765 let is_float = ty::type_is_fp(ccx_tcx(cx), ty);
4766 let signed = ty::type_is_signed(ccx_tcx(cx), ty);
4769 if is_float { llvm::LLVMConstFAdd(te1, te2) }
4770 else { llvm::LLVMConstAdd(te1, te2) }
4773 if is_float { llvm::LLVMConstFSub(te1, te2) }
4774 else { llvm::LLVMConstSub(te1, te2) }
4777 if is_float { llvm::LLVMConstFMul(te1, te2) }
4778 else { llvm::LLVMConstMul(te1, te2) }
4781 if is_float { llvm::LLVMConstFDiv(te1, te2) }
4782 else if signed { llvm::LLVMConstSDiv(te1, te2) }
4783 else { llvm::LLVMConstUDiv(te1, te2) }
4786 if is_float { llvm::LLVMConstFRem(te1, te2) }
4787 else if signed { llvm::LLVMConstSRem(te1, te2) }
4788 else { llvm::LLVMConstURem(te1, te2) }
4791 ast::or. { cx.sess.span_unimpl(e.span, "binop logic"); }
4792 ast::bitxor. { llvm::LLVMConstXor(te1, te2) }
4793 ast::bitand. { llvm::LLVMConstAnd(te1, te2) }
4794 ast::bitor. { llvm::LLVMConstOr(te1, te2) }
4795 ast::lsl. { llvm::LLVMConstShl(te1, te2) }
4796 ast::lsr. { llvm::LLVMConstLShr(te1, te2) }
4797 ast::asr. { llvm::LLVMConstAShr(te1, te2) }
4803 ast::gt. { cx.sess.span_unimpl(e.span, "binop comparator"); }
4806 ast::expr_unary(u, e) {
4807 let te = trans_const_expr(cx, e);
4808 let ty = ty::expr_ty(ccx_tcx(cx), e);
4809 let is_float = ty::type_is_fp(ccx_tcx(cx), ty);
4813 ast::deref. { cx.sess.span_bug(e.span,
4814 "bad unop type in trans_const_expr"); }
4815 ast::not. { llvm::LLVMConstNot(te) }
4817 if is_float { llvm::LLVMConstFNeg(te) }
4818 else { llvm::LLVMConstNeg(te) }
4822 _ { cx.sess.span_bug(e.span,
4823 "bad constant expression type in trans_const_expr"); }
4827 fn trans_const(cx: @crate_ctxt, e: @ast::expr, id: ast::node_id) {
4828 let v = trans_const_expr(cx, e);
4830 // The scalars come back as 1st class LLVM vals
4831 // which we have to stick into global constants.
4833 alt cx.consts.find(id) {
4835 llvm::LLVMSetInitializer(g, v);
4836 llvm::LLVMSetGlobalConstant(g, True);
4838 _ { cx.sess.span_fatal(e.span, "Unbound const in trans_const"); }
4842 type c_stack_tys = {
4846 base_fn_ty: TypeRef,
4851 fn c_stack_tys(ccx: @crate_ctxt,
4853 id: ast::node_id) -> @c_stack_tys {
4854 alt ty::struct(ccx.tcx, ty::node_id_to_type(ccx.tcx, id)) {
4855 ty::ty_native_fn(arg_tys, ret_ty) {
4857 let llargtys = type_of_explicit_args(ccx, sp, arg_tys);
4858 check non_ty_var(ccx, ret_ty); // NDM does this truly hold?
4859 let llretty = type_of_inner(ccx, sp, ret_ty);
4860 let bundle_ty = T_struct(llargtys + [T_ptr(llretty)]);
4864 ret_def: !ty::type_is_bot(tcx, ret_ty) &&
4865 !ty::type_is_nil(tcx, ret_ty),
4866 base_fn_ty: T_fn(llargtys, llretty),
4867 bundle_ty: bundle_ty,
4868 shim_fn_ty: T_fn([T_ptr(bundle_ty)], T_void())
4873 ccx.sess.span_fatal(
4875 "Non-function type for native fn");
4880 // For each native function F, we generate a wrapper function W and a shim
4881 // function S that all work together. The wrapper function W is the function
4882 // that other rust code actually invokes. Its job is to marshall the
4883 // arguments into a struct. It then uses a small bit of assembly to switch
4884 // over to the C stack and invoke the shim function. The shim function S then
4885 // unpacks the arguments from the struct and invokes the actual function F
4886 // according to its specified calling convention.
4888 // Example: Given a native c-stack function F(x: X, y: Y) -> Z,
4889 // we generate a wrapper function W that looks like:
4891 // void W(Z* dest, void *env, X x, Y y) {
4892 // struct { X x; Y y; Z *z; } args = { x, y, z };
4893 // call_on_c_stack_shim(S, &args);
4896 // The shim function S then looks something like:
4898 // void S(struct { X x; Y y; Z *z; } *args) {
4899 // *args->z = F(args->x, args->y);
4902 // However, if the return type of F is dynamically sized or of aggregate type,
4903 // the shim function looks like:
4905 // void S(struct { X x; Y y; Z *z; } *args) {
4906 // F(args->z, args->x, args->y);
4909 // Note: on i386, the layout of the args struct is generally the same as the
4910 // desired layout of the arguments on the C stack. Therefore, we could use
4911 // upcall_alloc_c_stack() to allocate the `args` structure and switch the
4912 // stack pointer appropriately to avoid a round of copies. (In fact, the shim
4913 // function itself is unnecessary). We used to do this, in fact, and will
4914 // perhaps do so in the future.
4915 fn trans_native_mod(lcx: @local_ctxt, native_mod: ast::native_mod,
4916 abi: ast::native_abi) {
4917 fn build_shim_fn(lcx: @local_ctxt,
4918 native_item: @ast::native_item,
4920 cc: uint) -> ValueRef {
4921 let lname = link_name(native_item);
4922 let ccx = lcx_ccx(lcx);
4923 let span = native_item.span;
4925 // Declare the "prototype" for the base function F:
4926 let llbasefn = decl_fn(ccx.llmod, lname, cc, tys.base_fn_ty);
4928 // Create the shim function:
4929 let shim_name = lname + "__c_stack_shim";
4930 let llshimfn = decl_internal_cdecl_fn(
4931 ccx.llmod, shim_name, tys.shim_fn_ty);
4933 // Declare the body of the shim function:
4934 let fcx = new_fn_ctxt(lcx, span, llshimfn);
4935 let bcx = new_top_block_ctxt(fcx);
4936 let lltop = bcx.llbb;
4937 let llargbundle = llvm::LLVMGetParam(llshimfn, 0u);
4938 let i = 0u, n = vec::len(tys.arg_tys);
4941 let llargval = load_inbounds(bcx, llargbundle, [0, i as int]);
4942 llargvals += [llargval];
4946 // Create the call itself and store the return value:
4947 let llretval = CallWithConv(bcx, llbasefn, llargvals, cc); // r
4949 // R** llretptr = &args->r;
4950 let llretptr = GEPi(bcx, llargbundle, [0, n as int]);
4951 // R* llretloc = *llretptr; /* (args->r) */
4952 let llretloc = Load(bcx, llretptr);
4954 Store(bcx, llretval, llretloc);
4959 finish_fn(fcx, lltop);
4964 fn build_wrap_fn(lcx: @local_ctxt,
4965 native_item: @ast::native_item,
4969 llwrapfn: ValueRef) {
4970 let span = native_item.span;
4971 let ccx = lcx_ccx(lcx);
4972 let fcx = new_fn_ctxt(lcx, span, llwrapfn);
4973 let bcx = new_top_block_ctxt(fcx);
4974 let lltop = bcx.llbb;
4976 // Allocate the struct and write the arguments into it.
4977 let llargbundle = alloca(bcx, tys.bundle_ty);
4978 let i = 0u, n = vec::len(tys.arg_tys);
4979 let implicit_args = 2u + num_tps; // ret + env
4981 let llargval = llvm::LLVMGetParam(llwrapfn, i + implicit_args);
4982 store_inbounds(bcx, llargval, llargbundle, [0, i as int]);
4985 let llretptr = llvm::LLVMGetParam(llwrapfn, 0u);
4986 store_inbounds(bcx, llretptr, llargbundle, [0, n as int]);
4988 // Create call itself.
4989 let call_shim_on_c_stack = ccx.upcalls.call_shim_on_c_stack;
4990 let llshimfnptr = PointerCast(bcx, llshimfn, T_ptr(T_i8()));
4991 let llrawargbundle = PointerCast(bcx, llargbundle, T_ptr(T_i8()));
4992 Call(bcx, call_shim_on_c_stack, [llrawargbundle, llshimfnptr]);
4994 finish_fn(fcx, lltop);
4997 let ccx = lcx_ccx(lcx);
4998 let cc: uint = lib::llvm::LLVMCCallConv;
5000 ast::native_abi_rust_intrinsic. { ret; }
5001 ast::native_abi_cdecl. { cc = lib::llvm::LLVMCCallConv; }
5002 ast::native_abi_stdcall. { cc = lib::llvm::LLVMX86StdcallCallConv; }
5005 for native_item in native_mod.items {
5006 alt native_item.node {
5007 ast::native_item_ty. {}
5008 ast::native_item_fn(fn_decl, tps) {
5009 let span = native_item.span;
5010 let id = native_item.id;
5011 let tys = c_stack_tys(ccx, span, id);
5012 alt ccx.item_ids.find(id) {
5014 let llshimfn = build_shim_fn(lcx, native_item, tys, cc);
5015 build_wrap_fn(lcx, native_item, tys,
5016 vec::len(tps), llshimfn, llwrapfn);
5020 ccx.sess.span_fatal(
5022 "unbound function item in trans_native_mod");
5030 fn trans_item(cx: @local_ctxt, item: ast::item) {
5032 ast::item_fn(decl, tps, body) {
5033 let sub_cx = extend_path(cx, item.ident);
5034 alt cx.ccx.item_ids.find(item.id) {
5036 trans_fn(sub_cx, item.span, decl, body, llfndecl, no_self, tps,
5040 cx.ccx.sess.span_fatal(item.span,
5041 "unbound function item in trans_item");
5045 ast::item_obj(ob, tps, ctor_id) {
5047 @{obj_typarams: tps, obj_fields: ob.fields
5048 with *extend_path(cx, item.ident)};
5049 trans_obj(sub_cx, item.span, ob, ctor_id, tps);
5051 ast::item_impl(tps, _, _, ms) {
5052 trans_impl::trans_impl(cx, item.ident, ms, item.id, tps);
5054 ast::item_res(decl, tps, body, dtor_id, ctor_id) {
5055 trans_res_ctor(cx, item.span, decl, ctor_id, tps);
5057 // Create a function for the destructor
5058 alt cx.ccx.item_ids.find(item.id) {
5060 trans_fn(cx, item.span, decl, body, lldtor_decl, no_self,
5064 cx.ccx.sess.span_fatal(item.span, "unbound dtor in trans_item");
5070 @{path: cx.path + [item.ident],
5071 module_path: cx.module_path + [item.ident] with *cx};
5072 trans_mod(sub_cx, m);
5074 ast::item_tag(variants, tps) {
5075 let sub_cx = extend_path(cx, item.ident);
5076 let degen = vec::len(variants) == 1u;
5078 for variant: ast::variant in variants {
5079 trans_tag_variant(sub_cx, item.id, variant, i, degen, tps);
5083 ast::item_const(_, expr) { trans_const(cx.ccx, expr, item.id); }
5084 ast::item_native_mod(native_mod) {
5085 let abi = alt attr::native_abi(item.attrs) {
5086 either::right(abi_) { abi_ }
5087 either::left(msg) { cx.ccx.sess.span_fatal(item.span, msg) }
5089 trans_native_mod(cx, native_mod, abi);
5091 _ {/* fall through */ }
5095 // Translate a module. Doing this amounts to translating the items in the
5096 // module; there ends up being no artifact (aside from linkage names) of
5097 // separate modules in the compiled program. That's because modules exist
5098 // only as a convenience for humans working with the code, to organize names
5099 // and control visibility.
5100 fn trans_mod(cx: @local_ctxt, m: ast::_mod) {
5101 for item: @ast::item in m.items { trans_item(cx, *item); }
5104 fn get_pair_fn_ty(llpairty: TypeRef) -> TypeRef {
5105 // Bit of a kludge: pick the fn typeref out of the pair.
5107 ret struct_elt(llpairty, 0u);
5110 fn register_fn(ccx: @crate_ctxt, sp: span, path: [str], flav: str,
5111 ty_params: [ast::ty_param], node_id: ast::node_id) {
5112 // FIXME: pull this out
5113 let t = node_id_type(ccx, node_id);
5114 check returns_non_ty_var(ccx, t);
5115 register_fn_full(ccx, sp, path, flav, ty_params, node_id, t);
5118 fn param_bounds(ccx: @crate_ctxt, tp: ast::ty_param) -> ty::param_bounds {
5119 ccx.tcx.ty_param_bounds.get(tp.id)
5122 fn register_fn_full(ccx: @crate_ctxt, sp: span, path: [str], _flav: str,
5123 tps: [ast::ty_param], node_id: ast::node_id,
5125 : returns_non_ty_var(ccx, node_type) {
5127 let llfty = type_of_fn_from_ty(ccx, sp, node_type,
5128 vec::map(tps, {|p| param_bounds(ccx, p)}));
5129 let ps: str = mangle_exported_name(ccx, path, node_type);
5130 let llfn: ValueRef = decl_cdecl_fn(ccx.llmod, ps, llfty);
5131 ccx.item_ids.insert(node_id, llfn);
5132 ccx.item_symbols.insert(node_id, ps);
5134 let is_main: bool = is_main_name(path) && !ccx.sess.building_library();
5135 if is_main { create_main_wrapper(ccx, sp, llfn, node_type); }
5138 // Create a _rust_main(args: [str]) function which will be called from the
5139 // runtime rust_start function
5140 fn create_main_wrapper(ccx: @crate_ctxt, sp: span, main_llfn: ValueRef,
5141 main_node_type: ty::t) {
5143 if ccx.main_fn != none::<ValueRef> {
5144 ccx.sess.span_fatal(sp, "multiple 'main' functions");
5147 let main_takes_argv =
5148 alt ty::struct(ccx.tcx, main_node_type) {
5149 ty::ty_fn({inputs, _}) { vec::len(inputs) != 0u }
5152 let llfn = create_main(ccx, sp, main_llfn, main_takes_argv);
5153 ccx.main_fn = some(llfn);
5154 create_entry_fn(ccx, llfn);
5156 fn create_main(ccx: @crate_ctxt, sp: span, main_llfn: ValueRef,
5157 takes_argv: bool) -> ValueRef {
5158 let unit_ty = ty::mk_str(ccx.tcx);
5159 let vecarg_ty: ty::arg =
5161 ty: ty::mk_vec(ccx.tcx, {ty: unit_ty, mut: ast::imm})};
5162 // FIXME: mk_nil should have a postcondition
5163 let nt = ty::mk_nil(ccx.tcx);
5164 let llfty = type_of_fn(ccx, sp, false, [vecarg_ty], nt, []);
5165 let llfdecl = decl_fn(ccx.llmod, "_rust_main",
5166 lib::llvm::LLVMCCallConv, llfty);
5168 let fcx = new_fn_ctxt(new_local_ctxt(ccx), sp, llfdecl);
5170 let bcx = new_top_block_ctxt(fcx);
5171 let lltop = bcx.llbb;
5173 let lloutputarg = llvm::LLVMGetParam(llfdecl, 0u);
5174 let llenvarg = llvm::LLVMGetParam(llfdecl, 1u);
5175 let args = [lloutputarg, llenvarg];
5176 if takes_argv { args += [llvm::LLVMGetParam(llfdecl, 2u)]; }
5177 Call(bcx, main_llfn, args);
5180 finish_fn(fcx, lltop);
5185 fn create_entry_fn(ccx: @crate_ctxt, rust_main: ValueRef) {
5186 #[cfg(target_os = "win32")]
5187 fn main_name() -> str { ret "WinMain@16"; }
5188 #[cfg(target_os = "macos")]
5189 fn main_name() -> str { ret "main"; }
5190 #[cfg(target_os = "linux")]
5191 fn main_name() -> str { ret "main"; }
5192 #[cfg(target_os = "freebsd")]
5193 fn main_name() -> str { ret "main"; }
5194 let llfty = T_fn([ccx.int_type, ccx.int_type], ccx.int_type);
5195 let llfn = decl_cdecl_fn(ccx.llmod, main_name(), llfty);
5196 let llbb = str::as_buf("top", {|buf|
5197 llvm::LLVMAppendBasicBlock(llfn, buf)
5199 let bld = *ccx.builder;
5200 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
5201 let crate_map = ccx.crate_map;
5202 let start_ty = T_fn([val_ty(rust_main), ccx.int_type, ccx.int_type,
5203 val_ty(crate_map)], ccx.int_type);
5204 let start = str::as_buf("rust_start", {|buf|
5205 llvm::LLVMAddGlobal(ccx.llmod, start_ty, buf)
5207 let args = [rust_main, llvm::LLVMGetParam(llfn, 0u),
5208 llvm::LLVMGetParam(llfn, 1u), crate_map];
5209 let result = unsafe {
5210 llvm::LLVMBuildCall(bld, start, vec::to_ptr(args),
5211 vec::len(args), noname())
5213 llvm::LLVMBuildRet(bld, result);
5217 // Create a /real/ closure: this is like create_fn_pair, but creates a
5218 // a fn value on the stack with a specified environment (which need not be
5220 fn create_real_fn_pair(cx: @block_ctxt, llfnty: TypeRef, llfn: ValueRef,
5221 llenvptr: ValueRef) -> ValueRef {
5222 let lcx = cx.fcx.lcx;
5224 let pair = alloca(cx, T_fn_pair(lcx.ccx, llfnty));
5225 fill_fn_pair(cx, pair, llfn, llenvptr);
5229 fn fill_fn_pair(bcx: @block_ctxt, pair: ValueRef, llfn: ValueRef,
5230 llenvptr: ValueRef) {
5231 let ccx = bcx_ccx(bcx);
5232 let code_cell = GEPi(bcx, pair, [0, abi::fn_field_code]);
5233 Store(bcx, llfn, code_cell);
5234 let env_cell = GEPi(bcx, pair, [0, abi::fn_field_box]);
5236 PointerCast(bcx, llenvptr, T_opaque_boxed_closure_ptr(ccx));
5237 Store(bcx, llenvblobptr, env_cell);
5240 // Returns the number of type parameters that the given native function has.
5241 fn native_fn_ty_param_count(cx: @crate_ctxt, id: ast::node_id) -> uint {
5244 alt cx.ast_map.find(id) { some(ast_map::node_native_item(i)) { i } };
5245 alt native_item.node {
5246 ast::native_item_ty. {
5247 cx.sess.bug("register_native_fn(): native fn isn't \
5250 ast::native_item_fn(_, tps) {
5251 count = vec::len::<ast::ty_param>(tps);
5257 fn native_fn_wrapper_type(cx: @crate_ctxt, sp: span,
5258 param_bounds: [ty::param_bounds],
5259 x: ty::t) -> TypeRef {
5260 alt ty::struct(cx.tcx, x) {
5261 ty::ty_native_fn(args, out) {
5262 ret type_of_fn(cx, sp, false, args, out, param_bounds);
5267 fn raw_native_fn_type(ccx: @crate_ctxt, sp: span, args: [ty::arg],
5268 ret_ty: ty::t) -> TypeRef {
5269 check type_has_static_size(ccx, ret_ty);
5270 ret T_fn(type_of_explicit_args(ccx, sp, args), type_of(ccx, sp, ret_ty));
5273 fn link_name(i: @ast::native_item) -> str {
5274 alt attr::get_meta_item_value_str_by_name(i.attrs, "link_name") {
5275 none. { ret i.ident; }
5276 option::some(ln) { ret ln; }
5280 fn collect_native_item(ccx: @crate_ctxt,
5281 abi: @mutable option::t<ast::native_abi>,
5282 i: @ast::native_item,
5286 ast::native_item_fn(_, tps) {
5289 let node_type = node_id_type(ccx, id);
5291 alt attr::get_meta_item_value_str_by_name(i.attrs, "abi") {
5293 // if abi isn't specified for this function, inherit from
5294 // its enclosing native module
5298 alt attr::native_abi(i.attrs) {
5299 either::right(abi_) { abi_ }
5300 either::left(msg) { ccx.sess.span_fatal(i.span, msg) }
5305 ast::native_abi_rust_intrinsic. {
5306 // For intrinsics: link the function directly to the intrinsic
5308 let fn_type = type_of_fn_from_ty(
5310 vec::map(tps, {|p| param_bounds(ccx, p)}));
5311 let ri_name = "rust_intrinsic_" + link_name(i);
5312 let llnativefn = get_extern_fn(
5313 ccx.externs, ccx.llmod, ri_name,
5314 lib::llvm::LLVMCCallConv, fn_type);
5315 ccx.item_ids.insert(id, llnativefn);
5316 ccx.item_symbols.insert(id, ri_name);
5319 ast::native_abi_cdecl. | ast::native_abi_stdcall. {
5320 // For true external functions: create a rust wrapper
5321 // and link to that. The rust wrapper will handle
5322 // switching to the C stack.
5323 let new_pt = pt + [i.ident];
5324 register_fn(ccx, i.span, new_pt, "native fn", tps, i.id);
5332 fn collect_item(ccx: @crate_ctxt, abi: @mutable option::t<ast::native_abi>,
5333 i: @ast::item, &&pt: [str], v: vt<[str]>) {
5334 let new_pt = pt + [i.ident];
5336 ast::item_const(_, _) {
5337 let typ = node_id_type(ccx, i.id);
5339 mangle_exported_name(ccx, pt + [i.ident],
5340 node_id_type(ccx, i.id));
5341 // FIXME: Could follow from a constraint on types of const
5343 let g = str::as_buf(s, {|buf|
5344 check (type_has_static_size(ccx, typ));
5345 llvm::LLVMAddGlobal(ccx.llmod, type_of(ccx, i.span, typ), buf)
5347 ccx.item_symbols.insert(i.id, s);
5348 ccx.consts.insert(i.id, g);
5350 ast::item_native_mod(native_mod) {
5351 // Propagate the native ABI down to collect_native_item(),
5352 alt attr::native_abi(i.attrs) {
5353 either::left(msg) { ccx.sess.span_fatal(i.span, msg); }
5354 either::right(abi_) {
5355 *abi = option::some(abi_);
5359 ast::item_fn(_, tps, _) {
5360 register_fn(ccx, i.span, new_pt, "fn", tps, i.id);
5362 ast::item_obj(ob, tps, ctor_id) {
5363 register_fn(ccx, i.span, new_pt, "obj_ctor", tps, ctor_id);
5365 ast::item_impl(tps, _, _, methods) {
5366 let name = i.ident + int::str(i.id);
5368 register_fn(ccx, i.span, pt + [name, m.ident],
5369 "impl_method", tps + m.tps, m.id);
5372 ast::item_res(_, tps, _, dtor_id, ctor_id) {
5373 register_fn(ccx, i.span, new_pt, "res_ctor", tps, ctor_id);
5374 // Note that the destructor is associated with the item's id, not
5375 // the dtor_id. This is a bit counter-intuitive, but simplifies
5376 // ty_res, which would have to carry around two def_ids otherwise
5377 // -- one to identify the type, and one to find the dtor symbol.
5378 let t = node_id_type(ccx, dtor_id);
5379 // FIXME: how to get rid of this check?
5380 check returns_non_ty_var(ccx, t);
5381 register_fn_full(ccx, i.span, new_pt, "res_dtor", tps, i.id, t);
5383 ast::item_tag(variants, tps) {
5384 for variant in variants {
5385 if vec::len(variant.node.args) != 0u {
5386 register_fn(ccx, i.span, new_pt + [variant.node.name],
5387 "tag", tps, variant.node.id);
5393 visit::visit_item(i, new_pt, v);
5396 fn collect_items(ccx: @crate_ctxt, crate: @ast::crate) {
5397 let abi = @mutable none::<ast::native_abi>;
5398 visit::visit_crate(*crate, [], visit::mk_vt(@{
5399 visit_native_item: bind collect_native_item(ccx, abi, _, _, _),
5400 visit_item: bind collect_item(ccx, abi, _, _, _)
5401 with *visit::default_visitor()
5405 // The constant translation pass.
5406 fn trans_constant(ccx: @crate_ctxt, it: @ast::item, &&pt: [str],
5408 let new_pt = pt + [it.ident];
5409 visit::visit_item(it, new_pt, v);
5411 ast::item_tag(variants, _) {
5413 for variant in variants {
5414 let p = new_pt + [variant.node.name, "discrim"];
5415 let s = mangle_exported_name(ccx, p, ty::mk_int(ccx.tcx));
5416 let discrim_gvar = str::as_buf(s, {|buf|
5417 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
5419 llvm::LLVMSetInitializer(discrim_gvar, C_int(ccx, i as int));
5420 llvm::LLVMSetGlobalConstant(discrim_gvar, True);
5421 ccx.discrims.insert(
5422 ast_util::local_def(variant.node.id), discrim_gvar);
5423 ccx.discrim_symbols.insert(variant.node.id, s);
5427 ast::item_impl(tps, some(@{node: ast::ty_path(_, id), _}), _, ms) {
5428 let i_did = ast_util::def_id_of_def(ccx.tcx.def_map.get(id));
5429 let ty = ty::lookup_item_type(ccx.tcx, i_did).ty;
5430 let new_pt = pt + [it.ident + int::str(it.id), "wrap"];
5431 let extra_tps = vec::map(tps, {|p| param_bounds(ccx, p)});
5432 let tbl = C_struct(vec::map(*ty::iface_methods(ccx.tcx, i_did), {|im|
5433 alt vec::find(ms, {|m| m.ident == im.ident}) {
5435 trans_impl::trans_wrapper(ccx, new_pt, extra_tps, m)
5439 let s = mangle_exported_name(ccx, new_pt + ["!vtable"], ty);
5440 let vt_gvar = str::as_buf(s, {|buf|
5441 llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl), buf)
5443 llvm::LLVMSetInitializer(vt_gvar, tbl);
5444 llvm::LLVMSetGlobalConstant(vt_gvar, True);
5445 ccx.item_ids.insert(it.id, vt_gvar);
5446 ccx.item_symbols.insert(it.id, s);
5452 fn trans_constants(ccx: @crate_ctxt, crate: @ast::crate) {
5454 @{visit_item: bind trans_constant(ccx, _, _, _)
5455 with *visit::default_visitor()};
5456 visit::visit_crate(*crate, [], visit::mk_vt(visitor));
5459 fn vp2i(cx: @block_ctxt, v: ValueRef) -> ValueRef {
5460 let ccx = bcx_ccx(cx);
5461 ret PtrToInt(cx, v, ccx.int_type);
5464 fn p2i(ccx: @crate_ctxt, v: ValueRef) -> ValueRef {
5465 ret llvm::LLVMConstPtrToInt(v, ccx.int_type);
5468 fn declare_intrinsics(llmod: ModuleRef) -> hashmap<str, ValueRef> {
5469 let T_memmove32_args: [TypeRef] =
5470 [T_ptr(T_i8()), T_ptr(T_i8()), T_i32(), T_i32(), T_i1()];
5471 let T_memmove64_args: [TypeRef] =
5472 [T_ptr(T_i8()), T_ptr(T_i8()), T_i64(), T_i32(), T_i1()];
5473 let T_memset32_args: [TypeRef] =
5474 [T_ptr(T_i8()), T_i8(), T_i32(), T_i32(), T_i1()];
5475 let T_memset64_args: [TypeRef] =
5476 [T_ptr(T_i8()), T_i8(), T_i64(), T_i32(), T_i1()];
5477 let T_trap_args: [TypeRef] = [];
5479 decl_cdecl_fn(llmod, "llvm.gcroot",
5480 T_fn([T_ptr(T_ptr(T_i8())), T_ptr(T_i8())], T_void()));
5482 decl_cdecl_fn(llmod, "llvm.gcread",
5483 T_fn([T_ptr(T_i8()), T_ptr(T_ptr(T_i8()))], T_void()));
5485 decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i32",
5486 T_fn(T_memmove32_args, T_void()));
5488 decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i64",
5489 T_fn(T_memmove64_args, T_void()));
5491 decl_cdecl_fn(llmod, "llvm.memset.p0i8.i32",
5492 T_fn(T_memset32_args, T_void()));
5494 decl_cdecl_fn(llmod, "llvm.memset.p0i8.i64",
5495 T_fn(T_memset64_args, T_void()));
5496 let trap = decl_cdecl_fn(llmod, "llvm.trap", T_fn(T_trap_args, T_void()));
5497 let intrinsics = new_str_hash::<ValueRef>();
5498 intrinsics.insert("llvm.gcroot", gcroot);
5499 intrinsics.insert("llvm.gcread", gcread);
5500 intrinsics.insert("llvm.memmove.p0i8.p0i8.i32", memmove32);
5501 intrinsics.insert("llvm.memmove.p0i8.p0i8.i64", memmove64);
5502 intrinsics.insert("llvm.memset.p0i8.i32", memset32);
5503 intrinsics.insert("llvm.memset.p0i8.i64", memset64);
5504 intrinsics.insert("llvm.trap", trap);
5508 fn declare_dbg_intrinsics(llmod: ModuleRef,
5509 intrinsics: hashmap<str, ValueRef>) {
5511 decl_cdecl_fn(llmod, "llvm.dbg.declare",
5512 T_fn([T_metadata(), T_metadata()], T_void()));
5514 decl_cdecl_fn(llmod, "llvm.dbg.value",
5515 T_fn([T_metadata(), T_i64(), T_metadata()], T_void()));
5516 intrinsics.insert("llvm.dbg.declare", declare);
5517 intrinsics.insert("llvm.dbg.value", value);
5520 fn trap(bcx: @block_ctxt) {
5521 let v: [ValueRef] = [];
5522 alt bcx_ccx(bcx).intrinsics.find("llvm.trap") {
5523 some(x) { Call(bcx, x, v); }
5524 _ { bcx_ccx(bcx).sess.bug("unbound llvm.trap in trap"); }
5528 fn create_module_map(ccx: @crate_ctxt) -> ValueRef {
5529 let elttype = T_struct([ccx.int_type, ccx.int_type]);
5530 let maptype = T_array(elttype, ccx.module_data.size() + 1u);
5532 str::as_buf("_rust_mod_map",
5533 {|buf| llvm::LLVMAddGlobal(ccx.llmod, maptype, buf) });
5534 llvm::LLVMSetLinkage(map,
5535 lib::llvm::LLVMInternalLinkage as llvm::Linkage);
5536 let elts: [ValueRef] = [];
5537 ccx.module_data.items {|key, val|
5538 let elt = C_struct([p2i(ccx, C_cstr(ccx, key)),
5542 let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
5544 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
5549 fn decl_crate_map(sess: session::session, mapname: str,
5550 llmod: ModuleRef) -> ValueRef {
5551 let targ_cfg = sess.get_targ_cfg();
5552 let int_type = T_int(targ_cfg);
5553 let n_subcrates = 1;
5554 let cstore = sess.get_cstore();
5555 while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
5556 let mapname = sess.building_library() ? mapname : "toplevel";
5557 let sym_name = "_rust_crate_map_" + mapname;
5558 let arrtype = T_array(int_type, n_subcrates as uint);
5559 let maptype = T_struct([int_type, arrtype]);
5560 let map = str::as_buf(sym_name, {|buf|
5561 llvm::LLVMAddGlobal(llmod, maptype, buf)
5563 llvm::LLVMSetLinkage(map, lib::llvm::LLVMExternalLinkage
5568 // FIXME use hashed metadata instead of crate names once we have that
5569 fn fill_crate_map(ccx: @crate_ctxt, map: ValueRef) {
5570 let subcrates: [ValueRef] = [];
5572 let cstore = ccx.sess.get_cstore();
5573 while cstore::have_crate_data(cstore, i) {
5574 let nm = "_rust_crate_map_" + cstore::get_crate_data(cstore, i).name;
5575 let cr = str::as_buf(nm, {|buf|
5576 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
5578 subcrates += [p2i(ccx, cr)];
5581 subcrates += [C_int(ccx, 0)];
5582 llvm::LLVMSetInitializer(map, C_struct(
5583 [p2i(ccx, create_module_map(ccx)),
5584 C_array(ccx.int_type, subcrates)]));
5587 fn write_metadata(cx: @crate_ctxt, crate: @ast::crate) {
5588 if !cx.sess.building_library() { ret; }
5589 let llmeta = C_postr(metadata::encoder::encode_metadata(cx, crate));
5590 let llconst = trans_common::C_struct([llmeta]);
5592 str::as_buf("rust_metadata",
5594 llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst), buf)
5596 llvm::LLVMSetInitializer(llglobal, llconst);
5598 str::as_buf(cx.sess.get_targ_cfg().target_strs.meta_sect_name,
5599 {|buf| llvm::LLVMSetSection(llglobal, buf) });
5600 llvm::LLVMSetLinkage(llglobal,
5601 lib::llvm::LLVMInternalLinkage as llvm::Linkage);
5603 let t_ptr_i8 = T_ptr(T_i8());
5604 llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8);
5606 str::as_buf("llvm.used",
5608 llvm::LLVMAddGlobal(cx.llmod, T_array(t_ptr_i8, 1u),
5611 llvm::LLVMSetLinkage(llvm_used,
5612 lib::llvm::LLVMAppendingLinkage as llvm::Linkage);
5613 llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
5616 // Writes the current ABI version into the crate.
5617 fn write_abi_version(ccx: @crate_ctxt) {
5618 shape::mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version),
5622 fn trans_crate(sess: session::session, crate: @ast::crate, tcx: ty::ctxt,
5623 output: str, emap: resolve::exp_map, amap: ast_map::map,
5624 mut_map: mut::mut_map, copy_map: alias::copy_map,
5625 last_uses: last_use::last_uses, method_map: typeck::method_map,
5626 dict_map: typeck::dict_map)
5627 -> (ModuleRef, link::link_meta) {
5628 let sha = std::sha1::mk_sha1();
5629 let link_meta = link::build_link_meta(sess, *crate, output, sha);
5631 // Append ".rc" to crate name as LLVM module identifier.
5633 // LLVM code generator emits a ".file filename" directive
5634 // for ELF backends. Value of the "filename" is set as the
5635 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
5636 // crashes if the module identifer is same as other symbols
5637 // such as a function name in the module.
5638 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
5639 let llmod_id = link_meta.name + ".rc";
5641 let llmod = str::as_buf(llmod_id, {|buf|
5642 llvm::LLVMModuleCreateWithNameInContext
5643 (buf, llvm::LLVMGetGlobalContext())
5645 let data_layout = sess.get_targ_cfg().target_strs.data_layout;
5646 let targ_triple = sess.get_targ_cfg().target_strs.target_triple;
5648 str::as_buf(data_layout,
5649 {|buf| llvm::LLVMSetDataLayout(llmod, buf) });
5651 str::as_buf(targ_triple,
5652 {|buf| llvm::LLVMSetTarget(llmod, buf) });
5653 let targ_cfg = sess.get_targ_cfg();
5654 let td = mk_target_data(sess.get_targ_cfg().target_strs.data_layout);
5655 let tn = mk_type_names();
5656 let intrinsics = declare_intrinsics(llmod);
5657 if sess.get_opts().extra_debuginfo {
5658 declare_dbg_intrinsics(llmod, intrinsics);
5660 let int_type = T_int(targ_cfg);
5661 let float_type = T_float(targ_cfg);
5662 let task_type = T_task(targ_cfg);
5663 let taskptr_type = T_ptr(task_type);
5664 tn.associate("taskptr", taskptr_type);
5665 let tydesc_type = T_tydesc(targ_cfg);
5666 tn.associate("tydesc", tydesc_type);
5667 let crate_map = decl_crate_map(sess, link_meta.name, llmod);
5668 let dbg_cx = if sess.get_opts().debuginfo {
5669 option::some(@{llmetadata: map::new_int_hash(),
5679 externs: new_str_hash::<ValueRef>(),
5680 intrinsics: intrinsics,
5681 item_ids: new_int_hash::<ValueRef>(),
5684 item_symbols: new_int_hash::<str>(),
5685 mutable main_fn: none::<ValueRef>,
5686 link_meta: link_meta,
5687 tag_sizes: ty::new_ty_hash(),
5688 discrims: ast_util::new_def_id_hash::<ValueRef>(),
5689 discrim_symbols: new_int_hash::<str>(),
5690 consts: new_int_hash::<ValueRef>(),
5691 tydescs: ty::new_ty_hash(),
5692 module_data: new_str_hash::<ValueRef>(),
5693 lltypes: ty::new_ty_hash(),
5696 type_sha1s: ty::new_ty_hash(),
5697 type_short_names: ty::new_ty_hash(),
5701 last_uses: last_uses,
5702 method_map: method_map,
5705 {mutable n_static_tydescs: 0u,
5706 mutable n_derived_tydescs: 0u,
5707 mutable n_glues_created: 0u,
5708 mutable n_null_glues: 0u,
5709 mutable n_real_glues: 0u,
5710 fn_times: @mutable []},
5712 upcall::declare_upcalls(targ_cfg, tn, tydesc_type,
5714 rust_object_type: T_rust_object(),
5715 tydesc_type: tydesc_type,
5717 float_type: float_type,
5718 task_type: task_type,
5719 opaque_vec_type: T_opaque_vec(targ_cfg),
5720 builder: BuilderRef_res(llvm::LLVMCreateBuilder()),
5721 shape_cx: shape::mk_ctxt(llmod),
5722 gc_cx: gc::mk_ctxt(),
5723 crate_map: crate_map,
5725 let cx = new_local_ctxt(ccx);
5726 collect_items(ccx, crate);
5727 trans_constants(ccx, crate);
5728 trans_mod(cx, crate.node.module);
5729 fill_crate_map(ccx, crate_map);
5731 shape::gen_shape_tables(ccx);
5732 write_abi_version(ccx);
5734 // Translate the metadata.
5735 write_metadata(cx.ccx, crate);
5736 if ccx.sess.get_opts().stats {
5737 #error("--- trans stats ---");
5738 #error("n_static_tydescs: %u", ccx.stats.n_static_tydescs);
5739 #error("n_derived_tydescs: %u", ccx.stats.n_derived_tydescs);
5740 #error("n_glues_created: %u", ccx.stats.n_glues_created);
5741 #error("n_null_glues: %u", ccx.stats.n_null_glues);
5742 #error("n_real_glues: %u", ccx.stats.n_real_glues);
5744 for timing: {ident: str, time: int} in *ccx.stats.fn_times {
5745 #error("time: %s took %d ms", timing.ident, timing.time);
5748 ret (llmod, link_meta);
5754 // indent-tabs-mode: nil
5755 // c-basic-offset: 4
5756 // buffer-file-coding-system: utf-8-unix