1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 * # Translation of Expressions
14 * Public entry points:
16 * - `trans_into(bcx, expr, dest) -> bcx`: evaluates an expression,
17 * storing the result into `dest`. This is the preferred form, if you
20 * - `trans(bcx, expr) -> DatumBlock`: evaluates an expression, yielding
21 * `Datum` with the result. You can then store the datum, inspect
22 * the value, etc. This may introduce temporaries if the datum is a
25 * - `trans_to_lvalue(bcx, expr, "...") -> DatumBlock`: evaluates an
26 * expression and ensures that the result has a cleanup associated with it,
27 * creating a temporary stack slot if necessary.
29 * - `trans_local_var -> Datum`: looks up a local variable or upvar.
31 * See doc.rs for more comments.
34 #![allow(non_camel_case_types)]
39 use metadata::csearch;
41 use middle::lang_items::MallocFnLangItem;
42 use middle::mem_categorization::Typer;
44 use middle::trans::_match;
45 use middle::trans::adt;
46 use middle::trans::asm;
47 use middle::trans::base::*;
48 use middle::trans::base;
49 use middle::trans::build::*;
50 use middle::trans::callee;
51 use middle::trans::cleanup;
52 use middle::trans::cleanup::CleanupMethods;
53 use middle::trans::closure;
54 use middle::trans::common::*;
55 use middle::trans::consts;
56 use middle::trans::controlflow;
57 use middle::trans::datum::*;
58 use middle::trans::debuginfo;
59 use middle::trans::glue;
60 use middle::trans::machine;
61 use middle::trans::meth;
62 use middle::trans::inline;
63 use middle::trans::tvec;
64 use middle::trans::type_of;
65 use middle::ty::{struct_fields, tup_fields};
66 use middle::ty::{AutoDerefRef, AutoAddEnv, AutoUnsafe};
67 use middle::ty::{AutoPtr};
70 use middle::typeck::MethodCall;
71 use util::common::indenter;
72 use util::ppaux::Repr;
73 use util::nodemap::NodeMap;
74 use middle::trans::machine::{llsize_of, llsize_of_alloc};
75 use middle::trans::type_::Type;
79 use syntax::print::pprust::{expr_to_string};
85 // These are passed around by the code generating functions to track the
86 // destination of a computation's value.
88 #[deriving(PartialEq)]
95 pub fn to_string(&self, ccx: &CrateContext) -> String {
97 SaveIn(v) => format!("SaveIn({})", ccx.tn().val_to_string(v)),
98 Ignore => "Ignore".to_string()
103 pub fn trans_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
106 -> Block<'blk, 'tcx> {
108 * This function is equivalent to `trans(bcx, expr).store_to_dest(dest)`
109 * but it may generate better optimized LLVM code.
114 if bcx.tcx().adjustments.borrow().contains_key(&expr.id) {
115 // use trans, which may be less efficient but
116 // which will perform the adjustments:
117 let datum = unpack_datum!(bcx, trans(bcx, expr));
118 return datum.store_to_dest(bcx, dest, expr.id)
121 debug!("trans_into() expr={}", expr.repr(bcx.tcx()));
122 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
124 bcx.fcx.push_ast_cleanup_scope(expr.id);
126 let kind = ty::expr_kind(bcx.tcx(), expr);
128 ty::LvalueExpr | ty::RvalueDatumExpr => {
129 trans_unadjusted(bcx, expr).store_to_dest(dest, expr.id)
131 ty::RvalueDpsExpr => {
132 trans_rvalue_dps_unadjusted(bcx, expr, dest)
134 ty::RvalueStmtExpr => {
135 trans_rvalue_stmt_unadjusted(bcx, expr)
139 bcx.fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id)
142 pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
144 -> DatumBlock<'blk, 'tcx, Expr> {
146 * Translates an expression, returning a datum (and new block)
147 * encapsulating the result. When possible, it is preferred to
148 * use `trans_into`, as that may avoid creating a temporary on
152 debug!("trans(expr={})", bcx.expr_to_string(expr));
157 fcx.push_ast_cleanup_scope(expr.id);
158 let datum = unpack_datum!(bcx, trans_unadjusted(bcx, expr));
159 let datum = unpack_datum!(bcx, apply_adjustments(bcx, expr, datum));
160 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id);
161 return DatumBlock::new(bcx, datum);
164 pub fn get_len(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
165 GEPi(bcx, fat_ptr, [0u, abi::slice_elt_len])
168 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
169 GEPi(bcx, fat_ptr, [0u, abi::slice_elt_base])
172 fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
175 -> DatumBlock<'blk, 'tcx, Expr> {
177 * Helper for trans that apply adjustments from `expr` to `datum`,
178 * which should be the unadjusted translation of `expr`.
182 let mut datum = datum;
183 let adjustment = match bcx.tcx().adjustments.borrow().find_copy(&expr.id) {
185 return DatumBlock::new(bcx, datum);
189 debug!("unadjusted datum for expr {}: {}",
190 expr.id, datum.to_string(bcx.ccx()));
193 datum = unpack_datum!(bcx, add_env(bcx, expr, datum));
195 AutoDerefRef(ref adj) => {
196 let (autoderefs, use_autoref) = match adj.autoref {
197 // Extracting a value from a box counts as a deref, but if we are
198 // just converting Box<[T, ..n]> to Box<[T]> we aren't really doing
199 // a deref (and wouldn't if we could treat Box like a normal struct).
200 Some(ty::AutoUnsizeUniq(..)) => (adj.autoderefs - 1, true),
201 // We are a bit paranoid about adjustments and thus might have a re-
202 // borrow here which merely derefs and then refs again (it might have
203 // a different region or mutability, but we don't care here. It might
204 // also be just in case we need to unsize. But if there are no nested
205 // adjustments then it should be a no-op).
206 Some(ty::AutoPtr(_, _, None)) if adj.autoderefs == 1 => {
207 match ty::get(datum.ty).sty {
208 // Don't skip a conversion from Box<T> to &T, etc.
210 let method_call = MethodCall::autoderef(expr.id, adj.autoderefs-1);
211 let method = bcx.tcx().method_map.borrow().find(&method_call).is_some();
213 // Don't skip an overloaded deref.
214 (adj.autoderefs, true)
216 (adj.autoderefs - 1, false)
219 _ => (adj.autoderefs, true),
222 _ => (adj.autoderefs, true)
227 let lval = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "auto_deref", expr.id));
228 datum = unpack_datum!(
229 bcx, deref_multiple(bcx, expr, lval.to_expr_datum(), autoderefs));
232 // (You might think there is a more elegant way to do this than a
233 // use_autoref bool, but then you remember that the borrow checker exists).
234 match (use_autoref, &adj.autoref) {
235 (true, &Some(ref a)) => {
236 datum = unpack_datum!(bcx, apply_autoref(a,
245 debug!("after adjustments, datum={}", datum.to_string(bcx.ccx()));
246 return DatumBlock::new(bcx, datum);
248 fn apply_autoref<'blk, 'tcx>(autoref: &ty::AutoRef,
249 bcx: Block<'blk, 'tcx>,
252 -> DatumBlock<'blk, 'tcx, Expr> {
254 let mut datum = datum;
256 let datum = match autoref {
257 &AutoPtr(_, _, ref a) | &AutoUnsafe(_, ref a) => {
260 &Some(box ref a) => datum = unpack_datum!(bcx,
261 apply_autoref(a, bcx, expr, datum)),
264 unpack_datum!(bcx, ref_ptr(bcx, expr, datum))
266 &ty::AutoUnsize(ref k) => {
267 debug!(" AutoUnsize");
268 unpack_datum!(bcx, unsize_expr(bcx, expr, datum, k))
271 &ty::AutoUnsizeUniq(ty::UnsizeLength(len)) => {
272 debug!(" AutoUnsizeUniq(UnsizeLength)");
273 unpack_datum!(bcx, unsize_unique_vec(bcx, expr, datum, len))
275 &ty::AutoUnsizeUniq(ref k) => {
276 debug!(" AutoUnsizeUniq");
277 unpack_datum!(bcx, unsize_unique_expr(bcx, expr, datum, k))
281 DatumBlock::new(bcx, datum)
284 fn ref_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
287 -> DatumBlock<'blk, 'tcx, Expr> {
288 if !ty::type_is_sized(bcx.tcx(), datum.ty) {
289 debug!("Taking address of unsized type {}",
290 bcx.ty_to_string(datum.ty));
291 ref_fat_ptr(bcx, expr, datum)
293 debug!("Taking address of sized type {}",
294 bcx.ty_to_string(datum.ty));
295 auto_ref(bcx, datum, expr)
299 // Retrieve the information we are losing (making dynamic) in an unsizing
301 // When making a dtor, we need to do different things depending on the
302 // ownership of the object.. mk_ty is a function for turning unsized_type
303 // into a type to be destructed. If we want to end up with a Box pointer,
304 // then mk_ty should make a Box pointer (T -> Box<T>), if we want a
305 // borrowed reference then it should be T -> &T.
306 fn unsized_info<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
307 kind: &ty::UnsizeKind,
310 mk_ty: |ty::t| -> ty::t) -> ValueRef {
312 &ty::UnsizeLength(len) => C_uint(bcx.ccx(), len),
313 &ty::UnsizeStruct(box ref k, tp_index) => match ty::get(unsized_ty).sty {
314 ty::ty_struct(_, ref substs) => {
315 let ty_substs = substs.types.get_slice(subst::TypeSpace);
316 // The dtor for a field treats it like a value, so mk_ty
317 // should just be the identity function.
318 unsized_info(bcx, k, id, ty_substs[tp_index], |t| t)
320 _ => bcx.sess().bug(format!("UnsizeStruct with bad sty: {}",
321 bcx.ty_to_string(unsized_ty)).as_slice())
323 &ty::UnsizeVtable(..) =>
325 meth::vtable_ptr(bcx, id, mk_ty(unsized_ty)),
326 Type::vtable_ptr(bcx.ccx()))
330 fn unsize_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
334 -> DatumBlock<'blk, 'tcx, Expr> {
336 let datum_ty = datum.ty;
337 let unsized_ty = ty::unsize_ty(tcx, datum_ty, k, expr.span);
338 let dest_ty = ty::mk_open(tcx, unsized_ty);
339 // Closures for extracting and manipulating the data and payload parts of
342 &ty::UnsizeStruct(..) =>
343 |bcx, val| PointerCast(bcx,
345 type_of::type_of(bcx.ccx(), unsized_ty).ptr_to()),
346 &ty::UnsizeLength(..) =>
347 |bcx, val| GEPi(bcx, val, [0u, 0u]),
348 &ty::UnsizeVtable(..) =>
349 |_bcx, val| PointerCast(bcx, val, Type::i8p(bcx.ccx()))
351 let info = |bcx, _val| unsized_info(bcx,
354 ty::deref_or_dont(datum_ty),
359 mutbl: ast::MutImmutable
361 into_fat_ptr(bcx, expr, datum, dest_ty, base, info)
364 fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
367 -> DatumBlock<'blk, 'tcx, Expr> {
369 let dest_ty = ty::close_type(tcx, datum.ty);
370 let base = |bcx, val| Load(bcx, get_dataptr(bcx, val));
371 let len = |bcx, val| Load(bcx, get_len(bcx, val));
372 into_fat_ptr(bcx, expr, datum, dest_ty, base, len)
375 fn into_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
379 base: |Block<'blk, 'tcx>, ValueRef| -> ValueRef,
380 info: |Block<'blk, 'tcx>, ValueRef| -> ValueRef)
381 -> DatumBlock<'blk, 'tcx, Expr> {
385 let lval = unpack_datum!(bcx,
386 datum.to_lvalue_datum(bcx, "into_fat_ptr", expr.id));
387 let base = base(bcx, lval.val);
388 let info = info(bcx, lval.val);
390 let scratch = rvalue_scratch_datum(bcx, dest_ty, "__fat_ptr");
391 Store(bcx, base, get_dataptr(bcx, scratch.val));
392 Store(bcx, info, get_len(bcx, scratch.val));
394 DatumBlock::new(bcx, scratch.to_expr_datum())
397 fn unsize_unique_vec<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
401 -> DatumBlock<'blk, 'tcx, Expr> {
405 let datum_ty = datum.ty;
407 let lval = unpack_datum!(bcx,
408 datum.to_lvalue_datum(bcx, "unsize_unique_vec", expr.id));
410 let ll_len = C_uint(bcx.ccx(), len);
411 let unit_ty = ty::sequence_element_type(tcx, ty::type_content(datum_ty));
412 let vec_ty = ty::mk_uniq(tcx, ty::mk_vec(tcx, unit_ty, None));
413 let scratch = rvalue_scratch_datum(bcx, vec_ty, "__unsize_unique");
417 C_null(type_of::type_of(bcx.ccx(), unit_ty).ptr_to()),
418 get_dataptr(bcx, scratch.val));
420 // Box<[(), ..n]> will not allocate, but ~[()] expects an
421 // allocation of n bytes, so we must allocate here (yuck).
422 let llty = type_of::type_of(bcx.ccx(), unit_ty);
423 if llsize_of_alloc(bcx.ccx(), llty) == 0 {
424 let ptr_unit_ty = type_of::type_of(bcx.ccx(), unit_ty).ptr_to();
425 let align = C_uint(bcx.ccx(), 8);
426 let alloc_result = malloc_raw_dyn(bcx, ptr_unit_ty, vec_ty, ll_len, align);
427 bcx = alloc_result.bcx;
428 let base = get_dataptr(bcx, scratch.val);
429 Store(bcx, alloc_result.val, base);
431 let base = get_dataptr(bcx, scratch.val);
432 let base = PointerCast(bcx,
434 type_of::type_of(bcx.ccx(), datum_ty).ptr_to());
435 bcx = lval.store_to(bcx, base);
439 Store(bcx, ll_len, get_len(bcx, scratch.val));
440 DatumBlock::new(bcx, scratch.to_expr_datum())
443 fn unsize_unique_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
447 -> DatumBlock<'blk, 'tcx, Expr> {
451 let datum_ty = datum.ty;
452 let unboxed_ty = match ty::get(datum_ty).sty {
454 _ => bcx.sess().bug(format!("Expected ty_uniq, found {}",
455 bcx.ty_to_string(datum_ty)).as_slice())
457 let result_ty = ty::mk_uniq(tcx, ty::unsize_ty(tcx, unboxed_ty, k, expr.span));
459 let lval = unpack_datum!(bcx,
460 datum.to_lvalue_datum(bcx, "unsize_unique_expr", expr.id));
462 let scratch = rvalue_scratch_datum(bcx, result_ty, "__uniq_fat_ptr");
463 let llbox_ty = type_of::type_of(bcx.ccx(), datum_ty);
464 let base = PointerCast(bcx, get_dataptr(bcx, scratch.val), llbox_ty.ptr_to());
465 bcx = lval.store_to(bcx, base);
467 let info = unsized_info(bcx, k, expr.id, unboxed_ty, |t| ty::mk_uniq(tcx, t));
468 Store(bcx, info, get_len(bcx, scratch.val));
470 let scratch = unpack_datum!(bcx,
471 scratch.to_expr_datum().to_lvalue_datum(bcx,
472 "fresh_uniq_fat_ptr",
475 DatumBlock::new(bcx, scratch.to_expr_datum())
478 fn add_env<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
481 -> DatumBlock<'blk, 'tcx, Expr> {
482 // This is not the most efficient thing possible; since closures
483 // are two words it'd be better if this were compiled in
484 // 'dest' mode, but I can't find a nice way to structure the
485 // code and keep it DRY that accommodates that use case at the
488 let closure_ty = expr_ty_adjusted(bcx, expr);
489 let fn_ptr = datum.to_llscalarish(bcx);
490 let def = ty::resolve_expr(bcx.tcx(), expr);
491 closure::make_closure_from_bare_fn(bcx, closure_ty, def, fn_ptr)
495 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
498 -> DatumBlock<'blk, 'tcx, Lvalue> {
500 * Translates an expression in "lvalue" mode -- meaning that it
501 * returns a reference to the memory that the expr represents.
503 * If this expression is an rvalue, this implies introducing a
504 * temporary. In other words, something like `x().f` is
505 * translated into roughly the equivalent of
507 * { tmp = x(); tmp.f }
511 let datum = unpack_datum!(bcx, trans(bcx, expr));
512 return datum.to_lvalue_datum(bcx, name, expr.id);
515 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
517 -> DatumBlock<'blk, 'tcx, Expr> {
519 * A version of `trans` that ignores adjustments. You almost
520 * certainly do not want to call this directly.
525 debug!("trans_unadjusted(expr={})", bcx.expr_to_string(expr));
526 let _indenter = indenter();
528 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
530 return match ty::expr_kind(bcx.tcx(), expr) {
531 ty::LvalueExpr | ty::RvalueDatumExpr => {
532 let datum = unpack_datum!(bcx, {
533 trans_datum_unadjusted(bcx, expr)
536 DatumBlock {bcx: bcx, datum: datum}
539 ty::RvalueStmtExpr => {
540 bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
541 nil(bcx, expr_ty(bcx, expr))
544 ty::RvalueDpsExpr => {
545 let ty = expr_ty(bcx, expr);
546 if type_is_zero_size(bcx.ccx(), ty) {
547 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
550 let scratch = rvalue_scratch_datum(bcx, ty, "");
551 bcx = trans_rvalue_dps_unadjusted(
552 bcx, expr, SaveIn(scratch.val));
554 // Note: this is not obviously a good idea. It causes
555 // immediate values to be loaded immediately after a
556 // return from a call or other similar expression,
557 // which in turn leads to alloca's having shorter
558 // lifetimes and hence larger stack frames. However,
559 // in turn it can lead to more register pressure.
560 // Still, in practice it seems to increase
561 // performance, since we have fewer problems with
563 let scratch = unpack_datum!(
564 bcx, scratch.to_appropriate_datum(bcx));
566 DatumBlock::new(bcx, scratch.to_expr_datum())
571 fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: ty::t)
572 -> DatumBlock<'blk, 'tcx, Expr> {
573 let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
574 let datum = immediate_rvalue(llval, ty);
575 DatumBlock::new(bcx, datum.to_expr_datum())
579 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
581 -> DatumBlock<'blk, 'tcx, Expr> {
584 let _icx = push_ctxt("trans_datum_unadjusted");
587 ast::ExprParen(ref e) => {
590 ast::ExprPath(_) => {
591 trans_def(bcx, expr, bcx.def(expr.id))
593 ast::ExprField(ref base, ident, _) => {
594 trans_rec_field(bcx, &**base, ident.node)
596 ast::ExprTupField(ref base, idx, _) => {
597 trans_rec_tup_field(bcx, &**base, idx.node)
599 ast::ExprIndex(ref base, ref idx) => {
600 trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id))
602 ast::ExprBox(_, ref contents) => {
603 // Special case for `Box<T>` and `Gc<T>`
604 let box_ty = expr_ty(bcx, expr);
605 let contents_ty = expr_ty(bcx, &**contents);
606 match ty::get(box_ty).sty {
608 let is_vec = match contents.node {
609 ast::ExprRepeat(..) | ast::ExprVec(..) => true,
610 ast::ExprLit(lit) => match lit.node {
611 ast::LitStr(..) => true,
618 // Special case for owned vectors.
619 fcx.push_ast_cleanup_scope(contents.id);
620 let datum = unpack_datum!(
621 bcx, tvec::trans_uniq_vec(bcx, expr, &**contents));
622 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, contents.id);
623 DatumBlock::new(bcx, datum)
625 trans_uniq_expr(bcx, box_ty, &**contents, contents_ty)
629 trans_managed_expr(bcx, box_ty, &**contents, contents_ty)
631 _ => bcx.sess().span_bug(expr.span,
632 "expected unique or managed box")
636 ast::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, (**lit).clone()),
637 ast::ExprBinary(op, ref lhs, ref rhs) => {
638 trans_binary(bcx, expr, op, &**lhs, &**rhs)
640 ast::ExprUnary(op, ref x) => {
641 trans_unary(bcx, expr, op, &**x)
643 ast::ExprAddrOf(_, ref x) => {
645 ast::ExprRepeat(..) | ast::ExprVec(..) => {
646 // Special case for slices.
647 fcx.push_ast_cleanup_scope(x.id);
648 let datum = unpack_datum!(
649 bcx, tvec::trans_slice_vec(bcx, expr, &**x));
650 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
651 DatumBlock::new(bcx, datum)
654 trans_addr_of(bcx, expr, &**x)
658 ast::ExprCast(ref val, _) => {
659 // Datum output mode means this is a scalar cast:
660 trans_imm_cast(bcx, &**val, expr.id)
663 bcx.tcx().sess.span_bug(
665 format!("trans_rvalue_datum_unadjusted reached \
666 fall-through case: {:?}",
667 expr.node).as_slice());
672 fn trans_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
674 get_idx: |&'blk ty::ctxt<'tcx>, &[ty::field]| -> uint)
675 -> DatumBlock<'blk, 'tcx, Expr> {
677 let _icx = push_ctxt("trans_rec_field");
679 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
680 let bare_ty = ty::unopen_type(base_datum.ty);
681 let repr = adt::represent_type(bcx.ccx(), bare_ty);
682 with_field_tys(bcx.tcx(), bare_ty, None, |discr, field_tys| {
683 let ix = get_idx(bcx.tcx(), field_tys);
684 let d = base_datum.get_element(
687 |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, ix));
689 if ty::type_is_sized(bcx.tcx(), d.ty) {
690 DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
692 let scratch = rvalue_scratch_datum(bcx, ty::mk_open(bcx.tcx(), d.ty), "");
693 Store(bcx, d.val, get_dataptr(bcx, scratch.val));
694 let info = Load(bcx, get_len(bcx, base_datum.val));
695 Store(bcx, info, get_len(bcx, scratch.val));
697 DatumBlock::new(bcx, scratch.to_expr_datum())
704 /// Translates `base.field`.
705 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
708 -> DatumBlock<'blk, 'tcx, Expr> {
709 trans_field(bcx, base, |tcx, field_tys| ty::field_idx_strict(tcx, field.name, field_tys))
712 /// Translates `base.<idx>`.
713 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
716 -> DatumBlock<'blk, 'tcx, Expr> {
717 trans_field(bcx, base, |_, _| idx)
720 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
721 index_expr: &ast::Expr,
724 method_call: MethodCall)
725 -> DatumBlock<'blk, 'tcx, Expr> {
726 //! Translates `base[idx]`.
728 let _icx = push_ctxt("trans_index");
732 // Check for overloaded index.
733 let method_ty = ccx.tcx()
737 .map(|method| method.ty);
738 let elt_datum = match method_ty {
740 let base_datum = unpack_datum!(bcx, trans(bcx, base));
742 // Translate index expression.
743 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
745 // Overloaded. Evaluate `trans_overloaded_op`, which will
746 // invoke the user's index() method, which basically yields
747 // a `&T` pointer. We can then proceed down the normal
748 // path (below) to dereference that `&T`.
751 trans_overloaded_op(bcx,
755 Some((ix_datum, idx.id)),
757 let ref_ty = ty::ty_fn_ret(monomorphize_type(bcx, method_ty));
758 let elt_ty = match ty::deref(ref_ty, true) {
760 bcx.tcx().sess.span_bug(index_expr.span,
761 "index method didn't return a \
762 dereferenceable type?!")
764 Some(elt_tm) => elt_tm.ty,
766 Datum::new(val, elt_ty, LvalueExpr)
769 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
773 // Translate index expression and cast to a suitable LLVM integer.
774 // Rust is less strict than LLVM in this regard.
775 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
776 let ix_val = ix_datum.to_llscalarish(bcx);
777 let ix_size = machine::llbitsize_of_real(bcx.ccx(),
779 let int_size = machine::llbitsize_of_real(bcx.ccx(),
782 if ix_size < int_size {
783 if ty::type_is_signed(expr_ty(bcx, idx)) {
784 SExt(bcx, ix_val, ccx.int_type())
785 } else { ZExt(bcx, ix_val, ccx.int_type()) }
786 } else if ix_size > int_size {
787 Trunc(bcx, ix_val, ccx.int_type())
795 ty::sequence_element_type(bcx.tcx(),
797 base::maybe_name_value(bcx.ccx(), vt.llunit_size, "unit_sz");
799 let (base, len) = base_datum.get_vec_base_and_len(bcx);
801 debug!("trans_index: base {}", bcx.val_to_string(base));
802 debug!("trans_index: len {}", bcx.val_to_string(len));
804 let bounds_check = ICmp(bcx, llvm::IntUGE, ix_val, len);
805 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
806 let expected = Call(bcx,
808 [bounds_check, C_bool(ccx, false)],
810 bcx = with_cond(bcx, expected, |bcx| {
811 controlflow::trans_fail_bounds_check(bcx,
816 let elt = InBoundsGEP(bcx, base, [ix_val]);
817 let elt = PointerCast(bcx, elt, vt.llunit_ty.ptr_to());
818 Datum::new(elt, vt.unit_ty, LvalueExpr)
822 DatumBlock::new(bcx, elt_datum)
825 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
826 ref_expr: &ast::Expr,
828 -> DatumBlock<'blk, 'tcx, Expr> {
829 //! Translates a reference to a path.
831 let _icx = push_ctxt("trans_def_lvalue");
833 def::DefFn(..) | def::DefStaticMethod(..) |
834 def::DefStruct(_) | def::DefVariant(..) => {
835 trans_def_fn_unadjusted(bcx, ref_expr, def)
837 def::DefStatic(did, _) => {
838 // There are three things that may happen here:
839 // 1) If the static item is defined in this crate, it will be
840 // translated using `get_item_val`, and we return a pointer to
842 // 2) If the static item is defined in another crate, but is
843 // marked inlineable, then it will be inlined into this crate
844 // and then translated with `get_item_val`. Again, we return a
845 // pointer to the result.
846 // 3) If the static item is defined in another crate and is not
847 // marked inlineable, then we add (or reuse) a declaration of
848 // an external global, and return a pointer to that.
849 let const_ty = expr_ty(bcx, ref_expr);
851 fn get_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, did: ast::DefId, const_ty: ty::t)
853 // For external constants, we don't inline.
854 if did.krate == ast::LOCAL_CRATE {
855 // Case 1 or 2. (The inlining in case 2 produces a new
856 // DefId in LOCAL_CRATE.)
858 // The LLVM global has the type of its initializer,
859 // which may not be equal to the enum's type for
861 let val = base::get_item_val(bcx.ccx(), did.node);
862 let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to();
863 PointerCast(bcx, val, pty)
866 match bcx.ccx().extern_const_values().borrow().find(&did) {
867 None => {} // Continue.
874 let llty = type_of::type_of(bcx.ccx(), const_ty);
875 let symbol = csearch::get_symbol(
876 &bcx.ccx().sess().cstore,
878 let llval = symbol.as_slice().with_c_str(|buf| {
879 llvm::LLVMAddGlobal(bcx.ccx().llmod(),
883 bcx.ccx().extern_const_values().borrow_mut()
889 // The DefId produced by `maybe_instantiate_inline`
890 // may be in the LOCAL_CRATE or not.
891 let did = inline::maybe_instantiate_inline(bcx.ccx(), did);
892 let val = get_val(bcx, did, const_ty);
893 DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr))
896 DatumBlock::new(bcx, trans_local_var(bcx, def).to_expr_datum())
901 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
903 -> Block<'blk, 'tcx> {
905 let _icx = push_ctxt("trans_rvalue_stmt");
907 if bcx.unreachable.get() {
912 ast::ExprParen(ref e) => {
913 trans_into(bcx, &**e, Ignore)
915 ast::ExprBreak(label_opt) => {
916 controlflow::trans_break(bcx, expr.id, label_opt)
918 ast::ExprAgain(label_opt) => {
919 controlflow::trans_cont(bcx, expr.id, label_opt)
921 ast::ExprRet(ex) => {
922 controlflow::trans_ret(bcx, ex)
924 ast::ExprWhile(ref cond, ref body, _) => {
925 controlflow::trans_while(bcx, expr.id, &**cond, &**body)
927 ast::ExprForLoop(ref pat, ref head, ref body, _) => {
928 controlflow::trans_for(bcx,
934 ast::ExprLoop(ref body, _) => {
935 controlflow::trans_loop(bcx, expr.id, &**body)
937 ast::ExprAssign(ref dst, ref src) => {
938 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
940 if ty::type_needs_drop(bcx.tcx(), dst_datum.ty) {
941 // If there are destructors involved, make sure we
942 // are copying from an rvalue, since that cannot possible
943 // alias an lvalue. We are concerned about code like:
951 // where e.g. a : Option<Foo> and a.b :
952 // Option<Foo>. In that case, freeing `a` before the
953 // assignment may also free `a.b`!
955 // We could avoid this intermediary with some analysis
956 // to determine whether `dst` may possibly own `src`.
957 let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
958 let src_datum = unpack_datum!(
959 bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
960 bcx = glue::drop_ty(bcx, dst_datum.val, dst_datum.ty);
961 src_datum.store_to(bcx, dst_datum.val)
963 trans_into(bcx, &**src, SaveIn(dst_datum.to_llref()))
966 ast::ExprAssignOp(op, ref dst, ref src) => {
967 trans_assign_op(bcx, expr, op, &**dst, src.clone())
969 ast::ExprInlineAsm(ref a) => {
970 asm::trans_inline_asm(bcx, a)
973 bcx.tcx().sess.span_bug(
975 format!("trans_rvalue_stmt_unadjusted reached \
976 fall-through case: {:?}",
977 expr.node).as_slice());
982 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
985 -> Block<'blk, 'tcx> {
986 let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
991 ast::ExprParen(ref e) => {
992 trans_into(bcx, &**e, dest)
994 ast::ExprPath(_) => {
995 trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
997 ast::ExprIf(ref cond, ref thn, els) => {
998 controlflow::trans_if(bcx, expr.id, &**cond, thn.clone(), els, dest)
1000 ast::ExprMatch(ref discr, ref arms) => {
1001 _match::trans_match(bcx, expr, &**discr, arms.as_slice(), dest)
1003 ast::ExprBlock(ref blk) => {
1004 controlflow::trans_block(bcx, &**blk, dest)
1006 ast::ExprStruct(_, ref fields, base) => {
1014 ast::ExprTup(ref args) => {
1015 let numbered_fields: Vec<(uint, Gc<ast::Expr>)> =
1016 args.iter().enumerate().map(|(i, arg)| (i, *arg)).collect();
1017 trans_adt(bcx, expr_ty(bcx, expr), 0, numbered_fields.as_slice(), None, dest)
1019 ast::ExprLit(lit) => {
1021 ast::LitStr(ref s, _) => {
1022 tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1027 .span_bug(expr.span,
1028 "trans_rvalue_dps_unadjusted shouldn't be \
1029 translating this type of literal")
1033 ast::ExprVec(..) | ast::ExprRepeat(..) => {
1034 tvec::trans_fixed_vstore(bcx, expr, dest)
1036 ast::ExprFnBlock(_, ref decl, ref body) |
1037 ast::ExprProc(ref decl, ref body) => {
1038 let expr_ty = expr_ty(bcx, expr);
1039 let store = ty::ty_closure_store(expr_ty);
1040 debug!("translating block function {} with type {}",
1041 expr_to_string(expr), expr_ty.repr(tcx));
1042 closure::trans_expr_fn(bcx, store, &**decl, &**body, expr.id, dest)
1044 ast::ExprUnboxedFn(_, _, decl, body) => {
1045 closure::trans_unboxed_closure(bcx, &*decl, &*body, expr.id, dest)
1047 ast::ExprCall(ref f, ref args) => {
1048 if bcx.tcx().is_method_call(expr.id) {
1049 trans_overloaded_call(bcx,
1055 callee::trans_call(bcx,
1058 callee::ArgExprs(args.as_slice()),
1062 ast::ExprMethodCall(_, _, ref args) => {
1063 callee::trans_method_call(bcx,
1066 callee::ArgExprs(args.as_slice()),
1069 ast::ExprBinary(_, ref lhs, ref rhs) => {
1070 // if not overloaded, would be RvalueDatumExpr
1071 let lhs = unpack_datum!(bcx, trans(bcx, &**lhs));
1072 let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs));
1073 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs,
1074 Some((rhs_datum, rhs.id)), Some(dest)).bcx
1076 ast::ExprUnary(_, ref subexpr) => {
1077 // if not overloaded, would be RvalueDatumExpr
1078 let arg = unpack_datum!(bcx, trans(bcx, &**subexpr));
1079 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id),
1080 arg, None, Some(dest)).bcx
1082 ast::ExprIndex(ref base, ref idx) => {
1083 // if not overloaded, would be RvalueDatumExpr
1084 let base = unpack_datum!(bcx, trans(bcx, &**base));
1085 let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx));
1086 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
1087 Some((idx_datum, idx.id)), Some(dest)).bcx
1089 ast::ExprCast(ref val, _) => {
1090 // DPS output mode means this is a trait cast:
1091 if ty::type_is_trait(node_id_type(bcx, expr.id)) {
1092 let datum = unpack_datum!(bcx, trans(bcx, &**val));
1093 meth::trans_trait_cast(bcx, datum, expr.id, dest)
1095 bcx.tcx().sess.span_bug(expr.span,
1096 "expr_cast of non-trait");
1099 ast::ExprAssignOp(op, ref dst, ref src) => {
1100 trans_assign_op(bcx, expr, op, &**dst, src.clone())
1103 bcx.tcx().sess.span_bug(
1105 format!("trans_rvalue_dps_unadjusted reached fall-through \
1107 expr.node).as_slice());
1112 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1113 ref_expr: &ast::Expr,
1116 -> Block<'blk, 'tcx> {
1117 let _icx = push_ctxt("trans_def_dps_unadjusted");
1119 let lldest = match dest {
1120 SaveIn(lldest) => lldest,
1121 Ignore => { return bcx; }
1125 def::DefVariant(tid, vid, _) => {
1126 let variant_info = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
1127 if variant_info.args.len() > 0u {
1129 let llfn = callee::trans_fn_ref(bcx, vid, ExprId(ref_expr.id));
1130 Store(bcx, llfn, lldest);
1134 let ty = expr_ty(bcx, ref_expr);
1135 let repr = adt::represent_type(bcx.ccx(), ty);
1136 adt::trans_set_discr(bcx, &*repr, lldest,
1137 variant_info.disr_val);
1141 def::DefStruct(_) => {
1142 let ty = expr_ty(bcx, ref_expr);
1143 match ty::get(ty).sty {
1144 ty::ty_struct(did, _) if ty::has_dtor(bcx.tcx(), did) => {
1145 let repr = adt::represent_type(bcx.ccx(), ty);
1146 adt::trans_set_discr(bcx, &*repr, lldest, 0);
1153 bcx.tcx().sess.span_bug(ref_expr.span, format!(
1154 "Non-DPS def {:?} referened by {}",
1155 def, bcx.node_id_to_string(ref_expr.id)).as_slice());
1160 fn trans_def_fn_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1161 ref_expr: &ast::Expr,
1163 -> DatumBlock<'blk, 'tcx, Expr> {
1164 let _icx = push_ctxt("trans_def_datum_unadjusted");
1166 let llfn = match def {
1167 def::DefFn(did, _) |
1168 def::DefStruct(did) | def::DefVariant(_, did, _) |
1169 def::DefStaticMethod(did, def::FromImpl(_), _) => {
1170 callee::trans_fn_ref(bcx, did, ExprId(ref_expr.id))
1172 def::DefStaticMethod(impl_did, def::FromTrait(trait_did), _) => {
1173 meth::trans_static_method_callee(bcx, impl_did,
1174 trait_did, ref_expr.id)
1177 bcx.tcx().sess.span_bug(ref_expr.span, format!(
1178 "trans_def_fn_unadjusted invoked on: {:?} for {}",
1180 ref_expr.repr(bcx.tcx())).as_slice());
1184 let fn_ty = expr_ty(bcx, ref_expr);
1185 DatumBlock::new(bcx, Datum::new(llfn, fn_ty, RvalueExpr(Rvalue::new(ByValue))))
1188 pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1192 * Translates a reference to a local variable or argument.
1193 * This always results in an lvalue datum.
1196 let _icx = push_ctxt("trans_local_var");
1199 def::DefUpvar(nid, _, _, _) => {
1200 // Can't move upvars, so this is never a ZeroMemLastUse.
1201 let local_ty = node_id_type(bcx, nid);
1202 match bcx.fcx.llupvars.borrow().find(&nid) {
1203 Some(&val) => Datum::new(val, local_ty, Lvalue),
1205 bcx.sess().bug(format!(
1206 "trans_local_var: no llval for upvar {:?} found",
1211 def::DefArg(nid, _) => {
1212 take_local(bcx, &*bcx.fcx.llargs.borrow(), nid)
1214 def::DefLocal(nid, _) | def::DefBinding(nid, _) => {
1215 take_local(bcx, &*bcx.fcx.lllocals.borrow(), nid)
1218 bcx.sess().unimpl(format!(
1219 "unsupported def type in trans_local_var: {:?}",
1224 fn take_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1225 table: &NodeMap<Datum<Lvalue>>,
1228 let datum = match table.find(&nid) {
1231 bcx.sess().bug(format!(
1232 "trans_local_var: no datum for local/arg {:?} found",
1236 debug!("take_local(nid={:?}, v={}, ty={})",
1237 nid, bcx.val_to_string(datum.val), bcx.ty_to_string(datum.ty));
1242 pub fn with_field_tys<R>(tcx: &ty::ctxt,
1244 node_id_opt: Option<ast::NodeId>,
1245 op: |ty::Disr, (&[ty::field])| -> R)
1248 * Helper for enumerating the field types of structs, enums, or records.
1249 * The optional node ID here is the node ID of the path identifying the enum
1250 * variant in use. If none, this cannot possibly an enum variant (so, if it
1251 * is and `node_id_opt` is none, this function fails).
1254 match ty::get(ty).sty {
1255 ty::ty_struct(did, ref substs) => {
1256 op(0, struct_fields(tcx, did, substs).as_slice())
1259 ty::ty_tup(ref v) => {
1260 op(0, tup_fields(v.as_slice()).as_slice())
1263 ty::ty_enum(_, ref substs) => {
1264 // We want the *variant* ID here, not the enum ID.
1267 tcx.sess.bug(format!(
1268 "cannot get field types from the enum type {} \
1270 ty.repr(tcx)).as_slice());
1273 let def = tcx.def_map.borrow().get_copy(&node_id);
1275 def::DefVariant(enum_id, variant_id, _) => {
1276 let variant_info = ty::enum_variant_with_id(
1277 tcx, enum_id, variant_id);
1278 op(variant_info.disr_val,
1284 tcx.sess.bug("resolve didn't map this expr to a \
1293 tcx.sess.bug(format!(
1294 "cannot get field types from the type {}",
1295 ty.repr(tcx)).as_slice());
1300 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1301 fields: &[ast::Field],
1302 base: Option<Gc<ast::Expr>>,
1303 expr_span: codemap::Span,
1305 dest: Dest) -> Block<'blk, 'tcx> {
1306 let _icx = push_ctxt("trans_rec");
1308 let ty = node_id_type(bcx, id);
1309 let tcx = bcx.tcx();
1310 with_field_tys(tcx, ty, Some(id), |discr, field_tys| {
1311 let mut need_base = Vec::from_elem(field_tys.len(), true);
1313 let numbered_fields = fields.iter().map(|field| {
1315 field_tys.iter().position(|field_ty|
1316 field_ty.ident.name == field.ident.node.name);
1319 *need_base.get_mut(i) = false;
1323 tcx.sess.span_bug(field.span,
1324 "Couldn't find field in struct type")
1327 }).collect::<Vec<_>>();
1328 let optbase = match base {
1329 Some(base_expr) => {
1330 let mut leftovers = Vec::new();
1331 for (i, b) in need_base.iter().enumerate() {
1333 leftovers.push((i, field_tys[i].mt.ty))
1336 Some(StructBaseInfo {expr: base_expr,
1337 fields: leftovers })
1340 if need_base.iter().any(|b| *b) {
1341 tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1347 trans_adt(bcx, ty, discr, numbered_fields.as_slice(), optbase, dest)
1352 * Information that `trans_adt` needs in order to fill in the fields
1353 * of a struct copied from a base struct (e.g., from an expression
1354 * like `Foo { a: b, ..base }`.
1356 * Note that `fields` may be empty; the base expression must always be
1357 * evaluated for side-effects.
1359 pub struct StructBaseInfo {
1360 /// The base expression; will be evaluated after all explicit fields.
1361 expr: Gc<ast::Expr>,
1362 /// The indices of fields to copy paired with their types.
1363 fields: Vec<(uint, ty::t)> }
1366 * Constructs an ADT instance:
1368 * - `fields` should be a list of field indices paired with the
1369 * expression to store into that field. The initializers will be
1370 * evaluated in the order specified by `fields`.
1372 * - `optbase` contains information on the base struct (if any) from
1373 * which remaining fields are copied; see comments on `StructBaseInfo`.
1375 pub fn trans_adt<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1378 fields: &[(uint, Gc<ast::Expr>)],
1379 optbase: Option<StructBaseInfo>,
1380 dest: Dest) -> Block<'blk, 'tcx> {
1381 let _icx = push_ctxt("trans_adt");
1383 let repr = adt::represent_type(bcx.ccx(), ty);
1385 // If we don't care about the result, just make a
1386 // temporary stack slot
1387 let addr = match dest {
1389 Ignore => alloc_ty(bcx, ty, "temp"),
1392 // This scope holds intermediates that must be cleaned should
1393 // failure occur before the ADT as a whole is ready.
1394 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1396 // First we trans the base, if we have one, to the dest
1397 for base in optbase.iter() {
1398 assert_eq!(discr, 0);
1400 match ty::expr_kind(bcx.tcx(), &*base.expr) {
1402 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base"));
1403 for &(i, t) in base.fields.iter() {
1404 let datum = base_datum.get_element(
1405 bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i));
1406 assert!(ty::type_is_sized(bcx.tcx(), datum.ty));
1407 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1408 bcx = datum.store_to(bcx, dest);
1411 ty::RvalueDpsExpr | ty::RvalueDatumExpr => {
1412 bcx = trans_into(bcx, &*base.expr, SaveIn(addr));
1414 ty::RvalueStmtExpr => bcx.tcx().sess.bug("unexpected expr kind for struct base expr")
1418 // Now, we just overwrite the fields we've explicitly specified
1419 for &(i, ref e) in fields.iter() {
1420 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1421 let e_ty = expr_ty_adjusted(bcx, &**e);
1422 bcx = trans_into(bcx, &**e, SaveIn(dest));
1423 let scope = cleanup::CustomScope(custom_cleanup_scope);
1424 fcx.schedule_lifetime_end(scope, dest);
1425 fcx.schedule_drop_mem(scope, dest, e_ty);
1428 adt::trans_set_discr(bcx, &*repr, addr, discr);
1430 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1432 // If we don't care about the result drop the temporary we made
1436 bcx = glue::drop_ty(bcx, addr, ty);
1437 base::call_lifetime_end(bcx, addr);
1444 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1447 -> DatumBlock<'blk, 'tcx, Expr> {
1448 // must not be a string constant, that is a RvalueDpsExpr
1449 let _icx = push_ctxt("trans_immediate_lit");
1450 let ty = expr_ty(bcx, expr);
1451 let v = consts::const_lit(bcx.ccx(), expr, lit);
1452 immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1455 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1458 sub_expr: &ast::Expr)
1459 -> DatumBlock<'blk, 'tcx, Expr> {
1460 let ccx = bcx.ccx();
1462 let _icx = push_ctxt("trans_unary_datum");
1464 let method_call = MethodCall::expr(expr.id);
1466 // The only overloaded operator that is translated to a datum
1467 // is an overloaded deref, since it is always yields a `&T`.
1468 // Otherwise, we should be in the RvalueDpsExpr path.
1470 op == ast::UnDeref ||
1471 !ccx.tcx().method_map.borrow().contains_key(&method_call));
1473 let un_ty = expr_ty(bcx, expr);
1477 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1478 let llresult = Not(bcx, datum.to_llscalarish(bcx));
1479 immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1482 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1483 let val = datum.to_llscalarish(bcx);
1485 if ty::type_is_fp(un_ty) {
1491 immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1494 trans_managed_expr(bcx, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1497 trans_uniq_expr(bcx, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1500 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1501 deref_once(bcx, expr, datum, method_call)
1506 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1508 contents: &ast::Expr,
1510 -> DatumBlock<'blk, 'tcx, Expr> {
1511 let _icx = push_ctxt("trans_uniq_expr");
1513 assert!(ty::type_is_sized(bcx.tcx(), contents_ty));
1514 let llty = type_of::type_of(bcx.ccx(), contents_ty);
1515 let size = llsize_of(bcx.ccx(), llty);
1516 let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty) as uint);
1517 let llty_ptr = llty.ptr_to();
1518 let Result { bcx, val } = malloc_raw_dyn(bcx, llty_ptr, box_ty, size, align);
1519 // Unique boxes do not allocate for zero-size types. The standard library
1520 // may assume that `free` is never called on the pointer returned for
1521 // `Box<ZeroSizeType>`.
1522 let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1523 trans_into(bcx, contents, SaveIn(val))
1525 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1526 fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1527 val, cleanup::HeapExchange, contents_ty);
1528 let bcx = trans_into(bcx, contents, SaveIn(val));
1529 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1532 immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1535 fn trans_managed_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1537 contents: &ast::Expr,
1539 -> DatumBlock<'blk, 'tcx, Expr> {
1540 let _icx = push_ctxt("trans_managed_expr");
1542 let ty = type_of::type_of(bcx.ccx(), contents_ty);
1543 let Result {bcx, val: bx} = malloc_raw_dyn_managed(bcx, contents_ty, MallocFnLangItem,
1544 llsize_of(bcx.ccx(), ty));
1545 let body = GEPi(bcx, bx, [0u, abi::box_field_body]);
1547 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1548 fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1549 bx, cleanup::HeapManaged, contents_ty);
1550 let bcx = trans_into(bcx, contents, SaveIn(body));
1551 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1552 immediate_rvalue_bcx(bcx, bx, box_ty).to_expr_datumblock()
1555 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1557 subexpr: &ast::Expr)
1558 -> DatumBlock<'blk, 'tcx, Expr> {
1559 let _icx = push_ctxt("trans_addr_of");
1561 let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1562 match ty::get(sub_datum.ty).sty {
1564 // Opened DST value, close to a fat pointer
1565 debug!("Closing fat pointer {}", bcx.ty_to_string(sub_datum.ty));
1567 let scratch = rvalue_scratch_datum(bcx,
1568 ty::close_type(bcx.tcx(), sub_datum.ty),
1570 let base = Load(bcx, get_dataptr(bcx, sub_datum.val));
1571 Store(bcx, base, get_dataptr(bcx, scratch.val));
1573 let len = Load(bcx, get_len(bcx, sub_datum.val));
1574 Store(bcx, len, get_len(bcx, scratch.val));
1576 DatumBlock::new(bcx, scratch.to_expr_datum())
1579 // Sized value, ref to a thin pointer
1580 let ty = expr_ty(bcx, expr);
1581 immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1586 // Important to get types for both lhs and rhs, because one might be _|_
1587 // and the other not.
1588 fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1589 binop_expr: &ast::Expr,
1596 -> DatumBlock<'blk, 'tcx, Expr> {
1597 let _icx = push_ctxt("trans_eager_binop");
1599 let tcx = bcx.tcx();
1600 let is_simd = ty::type_is_simd(tcx, lhs_t);
1602 if ty::type_is_bot(lhs_t) { rhs_t }
1603 else if is_simd { ty::simd_type(tcx, lhs_t) }
1606 let is_float = ty::type_is_fp(intype);
1607 let is_signed = ty::type_is_signed(intype);
1609 let rhs = base::cast_shift_expr_rhs(bcx, op, lhs, rhs);
1612 let val = match op {
1614 if is_float { FAdd(bcx, lhs, rhs) }
1615 else { Add(bcx, lhs, rhs) }
1618 if is_float { FSub(bcx, lhs, rhs) }
1619 else { Sub(bcx, lhs, rhs) }
1622 if is_float { FMul(bcx, lhs, rhs) }
1623 else { Mul(bcx, lhs, rhs) }
1629 // Only zero-check integers; fp /0 is NaN
1630 bcx = base::fail_if_zero_or_overflows(bcx, binop_expr.span,
1631 op, lhs, rhs, rhs_t);
1643 // Only zero-check integers; fp %0 is NaN
1644 bcx = base::fail_if_zero_or_overflows(bcx, binop_expr.span,
1645 op, lhs, rhs, rhs_t);
1653 ast::BiBitOr => Or(bcx, lhs, rhs),
1654 ast::BiBitAnd => And(bcx, lhs, rhs),
1655 ast::BiBitXor => Xor(bcx, lhs, rhs),
1656 ast::BiShl => Shl(bcx, lhs, rhs),
1660 } else { LShr(bcx, lhs, rhs) }
1662 ast::BiEq | ast::BiNe | ast::BiLt | ast::BiGe | ast::BiLe | ast::BiGt => {
1663 if ty::type_is_bot(rhs_t) {
1664 C_bool(bcx.ccx(), false)
1665 } else if ty::type_is_scalar(rhs_t) {
1666 unpack_result!(bcx, base::compare_scalar_types(bcx, lhs, rhs, rhs_t, op))
1668 base::compare_simd_types(bcx, lhs, rhs, intype, ty::simd_size(tcx, lhs_t), op)
1670 bcx.tcx().sess.span_bug(binop_expr.span, "comparison operator unsupported for type")
1674 bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1678 immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1681 // refinement types would obviate the need for this
1682 enum lazy_binop_ty {
1687 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1688 binop_expr: &ast::Expr,
1692 -> DatumBlock<'blk, 'tcx, Expr> {
1693 let _icx = push_ctxt("trans_lazy_binop");
1694 let binop_ty = expr_ty(bcx, binop_expr);
1697 let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1698 let lhs = lhs.to_llscalarish(past_lhs);
1700 if past_lhs.unreachable.get() {
1701 return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1704 let join = fcx.new_id_block("join", binop_expr.id);
1705 let before_rhs = fcx.new_id_block("before_rhs", b.id);
1708 lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb),
1709 lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb)
1712 let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1713 let rhs = rhs.to_llscalarish(past_rhs);
1715 if past_rhs.unreachable.get() {
1716 return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1719 Br(past_rhs, join.llbb);
1720 let phi = Phi(join, Type::i1(bcx.ccx()), [lhs, rhs],
1721 [past_lhs.llbb, past_rhs.llbb]);
1723 return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1726 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1731 -> DatumBlock<'blk, 'tcx, Expr> {
1732 let _icx = push_ctxt("trans_binary");
1733 let ccx = bcx.ccx();
1735 // if overloaded, would be RvalueDpsExpr
1736 assert!(!ccx.tcx().method_map.borrow().contains_key(&MethodCall::expr(expr.id)));
1740 trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1743 trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1747 let lhs_datum = unpack_datum!(bcx, trans(bcx, lhs));
1748 let rhs_datum = unpack_datum!(bcx, trans(bcx, rhs));
1749 let binop_ty = expr_ty(bcx, expr);
1751 debug!("trans_binary (expr {}): lhs_datum={}",
1753 lhs_datum.to_string(ccx));
1754 let lhs_ty = lhs_datum.ty;
1755 let lhs = lhs_datum.to_llscalarish(bcx);
1757 debug!("trans_binary (expr {}): rhs_datum={}",
1759 rhs_datum.to_string(ccx));
1760 let rhs_ty = rhs_datum.ty;
1761 let rhs = rhs_datum.to_llscalarish(bcx);
1762 trans_eager_binop(bcx, expr, binop_ty, op,
1763 lhs_ty, lhs, rhs_ty, rhs)
1768 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1770 method_call: MethodCall,
1772 rhs: Option<(Datum<Expr>, ast::NodeId)>,
1774 -> Result<'blk, 'tcx> {
1775 let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
1776 callee::trans_call_inner(bcx,
1777 Some(expr_info(expr)),
1778 monomorphize_type(bcx, method_ty),
1779 |bcx, arg_cleanup_scope| {
1780 meth::trans_method_callee(bcx,
1785 callee::ArgOverloadedOp(lhs, rhs),
1789 fn trans_overloaded_call<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1791 callee: Gc<ast::Expr>,
1792 args: &[Gc<ast::Expr>],
1794 -> Block<'blk, 'tcx> {
1795 let method_call = MethodCall::expr(expr.id);
1796 let method_type = bcx.tcx()
1801 let mut all_args = vec!(callee);
1802 all_args.push_all(args);
1804 callee::trans_call_inner(bcx,
1805 Some(expr_info(expr)),
1806 monomorphize_type(bcx,
1808 |bcx, arg_cleanup_scope| {
1809 meth::trans_method_callee(
1815 callee::ArgOverloadedCall(
1816 all_args.as_slice()),
1821 fn int_cast(bcx: Block,
1827 let _icx = push_ctxt("int_cast");
1829 let srcsz = llvm::LLVMGetIntTypeWidth(llsrctype.to_ref());
1830 let dstsz = llvm::LLVMGetIntTypeWidth(lldsttype.to_ref());
1831 return if dstsz == srcsz {
1832 BitCast(bcx, llsrc, lldsttype)
1833 } else if srcsz > dstsz {
1834 TruncOrBitCast(bcx, llsrc, lldsttype)
1836 SExtOrBitCast(bcx, llsrc, lldsttype)
1838 ZExtOrBitCast(bcx, llsrc, lldsttype)
1843 fn float_cast(bcx: Block,
1848 let _icx = push_ctxt("float_cast");
1849 let srcsz = llsrctype.float_width();
1850 let dstsz = lldsttype.float_width();
1851 return if dstsz > srcsz {
1852 FPExt(bcx, llsrc, lldsttype)
1853 } else if srcsz > dstsz {
1854 FPTrunc(bcx, llsrc, lldsttype)
1858 #[deriving(PartialEq)]
1859 pub enum cast_kind {
1867 pub fn cast_type_kind(tcx: &ty::ctxt, t: ty::t) -> cast_kind {
1868 match ty::get(t).sty {
1869 ty::ty_char => cast_integral,
1870 ty::ty_float(..) => cast_float,
1871 ty::ty_rptr(_, mt) | ty::ty_ptr(mt) => {
1872 if ty::type_is_sized(tcx, mt.ty) {
1878 ty::ty_bare_fn(..) => cast_pointer,
1879 ty::ty_int(..) => cast_integral,
1880 ty::ty_uint(..) => cast_integral,
1881 ty::ty_bool => cast_integral,
1882 ty::ty_enum(..) => cast_enum,
1887 fn cast_is_noop(t_in: ty::t, t_out: ty::t) -> bool {
1888 if ty::type_is_boxed(t_in) || ty::type_is_boxed(t_out) {
1892 match (ty::deref(t_in, true), ty::deref(t_out, true)) {
1893 (Some(ty::mt{ ty: t_in, .. }), Some(ty::mt{ ty: t_out, .. })) => {
1900 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1903 -> DatumBlock<'blk, 'tcx, Expr> {
1904 let _icx = push_ctxt("trans_cast");
1906 let ccx = bcx.ccx();
1908 let t_in = expr_ty(bcx, expr);
1909 let t_out = node_id_type(bcx, id);
1910 let k_in = cast_type_kind(bcx.tcx(), t_in);
1911 let k_out = cast_type_kind(bcx.tcx(), t_out);
1912 let s_in = k_in == cast_integral && ty::type_is_signed(t_in);
1913 let ll_t_in = type_of::arg_type_of(ccx, t_in);
1914 let ll_t_out = type_of::arg_type_of(ccx, t_out);
1916 // Convert the value to be cast into a ValueRef, either by-ref or
1917 // by-value as appropriate given its type:
1918 let mut datum = unpack_datum!(bcx, trans(bcx, expr));
1920 if cast_is_noop(datum.ty, t_out) {
1922 return DatumBlock::new(bcx, datum);
1925 let newval = match (k_in, k_out) {
1926 (cast_integral, cast_integral) => {
1927 let llexpr = datum.to_llscalarish(bcx);
1928 int_cast(bcx, ll_t_out, ll_t_in, llexpr, s_in)
1930 (cast_float, cast_float) => {
1931 let llexpr = datum.to_llscalarish(bcx);
1932 float_cast(bcx, ll_t_out, ll_t_in, llexpr)
1934 (cast_integral, cast_float) => {
1935 let llexpr = datum.to_llscalarish(bcx);
1937 SIToFP(bcx, llexpr, ll_t_out)
1938 } else { UIToFP(bcx, llexpr, ll_t_out) }
1940 (cast_float, cast_integral) => {
1941 let llexpr = datum.to_llscalarish(bcx);
1942 if ty::type_is_signed(t_out) {
1943 FPToSI(bcx, llexpr, ll_t_out)
1944 } else { FPToUI(bcx, llexpr, ll_t_out) }
1946 (cast_integral, cast_pointer) => {
1947 let llexpr = datum.to_llscalarish(bcx);
1948 IntToPtr(bcx, llexpr, ll_t_out)
1950 (cast_pointer, cast_integral) => {
1951 let llexpr = datum.to_llscalarish(bcx);
1952 PtrToInt(bcx, llexpr, ll_t_out)
1954 (cast_pointer, cast_pointer) => {
1955 let llexpr = datum.to_llscalarish(bcx);
1956 PointerCast(bcx, llexpr, ll_t_out)
1958 (cast_enum, cast_integral) |
1959 (cast_enum, cast_float) => {
1961 let repr = adt::represent_type(ccx, t_in);
1962 let datum = unpack_datum!(
1963 bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
1964 let llexpr_ptr = datum.to_llref();
1966 adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
1968 cast_integral => int_cast(bcx, ll_t_out,
1969 val_ty(lldiscrim_a),
1971 cast_float => SIToFP(bcx, lldiscrim_a, ll_t_out),
1973 ccx.sess().bug(format!("translating unsupported cast: \
1974 {} ({:?}) -> {} ({:?})",
1975 t_in.repr(bcx.tcx()),
1977 t_out.repr(bcx.tcx()),
1982 _ => ccx.sess().bug(format!("translating unsupported cast: \
1983 {} ({:?}) -> {} ({:?})",
1984 t_in.repr(bcx.tcx()),
1986 t_out.repr(bcx.tcx()),
1989 return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
1992 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1997 -> Block<'blk, 'tcx> {
1998 let _icx = push_ctxt("trans_assign_op");
2001 debug!("trans_assign_op(expr={})", bcx.expr_to_string(expr));
2003 // User-defined operator methods cannot be used with `+=` etc right now
2004 assert!(!bcx.tcx().method_map.borrow().contains_key(&MethodCall::expr(expr.id)));
2006 // Evaluate LHS (destination), which should be an lvalue
2007 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2008 assert!(!ty::type_needs_drop(bcx.tcx(), dst_datum.ty));
2009 let dst_ty = dst_datum.ty;
2010 let dst = load_ty(bcx, dst_datum.val, dst_datum.ty);
2013 let rhs_datum = unpack_datum!(bcx, trans(bcx, &*src));
2014 let rhs_ty = rhs_datum.ty;
2015 let rhs = rhs_datum.to_llscalarish(bcx);
2017 // Perform computation and store the result
2018 let result_datum = unpack_datum!(
2019 bcx, trans_eager_binop(bcx, expr, dst_datum.ty, op,
2020 dst_ty, dst, rhs_ty, rhs));
2021 return result_datum.store_to(bcx, dst_datum.val);
2024 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2027 -> DatumBlock<'blk, 'tcx, Expr> {
2030 // Ensure cleanup of `datum` if not already scheduled and obtain
2031 // a "by ref" pointer.
2032 let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2034 // Compute final type. Note that we are loose with the region and
2035 // mutability, since those things don't matter in trans.
2036 let referent_ty = lv_datum.ty;
2037 let ptr_ty = ty::mk_imm_rptr(bcx.tcx(), ty::ReStatic, referent_ty);
2040 let llref = lv_datum.to_llref();
2042 // Construct the resulting datum, using what was the "by ref"
2043 // ValueRef of type `referent_ty` to be the "by value" ValueRef
2044 // of type `&referent_ty`.
2045 DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(ByValue))))
2048 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2052 -> DatumBlock<'blk, 'tcx, Expr> {
2054 let mut datum = datum;
2055 for i in range(0, times) {
2056 let method_call = MethodCall::autoderef(expr.id, i);
2057 datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2059 DatumBlock { bcx: bcx, datum: datum }
2062 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2065 method_call: MethodCall)
2066 -> DatumBlock<'blk, 'tcx, Expr> {
2067 let ccx = bcx.ccx();
2069 debug!("deref_once(expr={}, datum={}, method_call={})",
2070 expr.repr(bcx.tcx()),
2071 datum.to_string(ccx),
2076 // Check for overloaded deref.
2077 let method_ty = ccx.tcx().method_map.borrow()
2078 .find(&method_call).map(|method| method.ty);
2079 let datum = match method_ty {
2080 Some(method_ty) => {
2081 // Overloaded. Evaluate `trans_overloaded_op`, which will
2082 // invoke the user's deref() method, which basically
2083 // converts from the `Smaht<T>` pointer that we have into
2084 // a `&T` pointer. We can then proceed down the normal
2085 // path (below) to dereference that `&T`.
2086 let datum = match method_call.adjustment {
2087 // Always perform an AutoPtr when applying an overloaded auto-deref
2088 typeck::AutoDeref(_) => unpack_datum!(bcx, auto_ref(bcx, datum, expr)),
2092 let ref_ty = ty::ty_fn_ret(monomorphize_type(bcx, method_ty));
2093 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2095 unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2096 datum, None, Some(SaveIn(scratch.val))));
2097 scratch.to_expr_datum()
2100 // Not overloaded. We already have a pointer we know how to deref.
2105 let r = match ty::get(datum.ty).sty {
2106 ty::ty_uniq(content_ty) => {
2107 if ty::type_is_sized(bcx.tcx(), content_ty) {
2108 deref_owned_pointer(bcx, expr, datum, content_ty)
2110 // A fat pointer and an opened DST value have the same
2111 // represenation just different types. Since there is no
2112 // temporary for `*e` here (because it is unsized), we cannot
2113 // emulate the sized object code path for running drop glue and
2114 // free. Instead, we schedule cleanup for `e`, turning it into
2116 let datum = unpack_datum!(
2117 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2119 let datum = Datum::new(datum.val, ty::mk_open(bcx.tcx(), content_ty), LvalueExpr);
2120 DatumBlock::new(bcx, datum)
2124 ty::ty_box(content_ty) => {
2125 let datum = unpack_datum!(
2126 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2127 let llptrref = datum.to_llref();
2128 let llptr = Load(bcx, llptrref);
2129 let llbody = GEPi(bcx, llptr, [0u, abi::box_field_body]);
2130 DatumBlock::new(bcx, Datum::new(llbody, content_ty, LvalueExpr))
2133 ty::ty_ptr(ty::mt { ty: content_ty, .. }) |
2134 ty::ty_rptr(_, ty::mt { ty: content_ty, .. }) => {
2135 if ty::type_is_sized(bcx.tcx(), content_ty) {
2136 let ptr = datum.to_llscalarish(bcx);
2138 // Always generate an lvalue datum, even if datum.mode is
2139 // an rvalue. This is because datum.mode is only an
2140 // rvalue for non-owning pointers like &T or *T, in which
2141 // case cleanup *is* scheduled elsewhere, by the true
2142 // owner (or, in the case of *T, by the user).
2143 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr))
2145 // A fat pointer and an opened DST value have the same represenation
2146 // just different types.
2147 DatumBlock::new(bcx, Datum::new(datum.val,
2148 ty::mk_open(bcx.tcx(), content_ty),
2154 bcx.tcx().sess.span_bug(
2156 format!("deref invoked on expr of illegal type {}",
2157 datum.ty.repr(bcx.tcx())).as_slice());
2161 debug!("deref_once(expr={}, method_call={}, result={})",
2162 expr.id, method_call, r.datum.to_string(ccx));
2166 fn deref_owned_pointer<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2170 -> DatumBlock<'blk, 'tcx, Expr> {
2172 * We microoptimize derefs of owned pointers a bit here.
2173 * Basically, the idea is to make the deref of an rvalue
2174 * result in an rvalue. This helps to avoid intermediate stack
2175 * slots in the resulting LLVM. The idea here is that, if the
2176 * `Box<T>` pointer is an rvalue, then we can schedule a *shallow*
2177 * free of the `Box<T>` pointer, and then return a ByRef rvalue
2178 * into the pointer. Because the free is shallow, it is legit
2179 * to return an rvalue, because we know that the contents are
2180 * not yet scheduled to be freed. The language rules ensure that the
2181 * contents will be used (or moved) before the free occurs.
2185 RvalueExpr(Rvalue { mode: ByRef }) => {
2186 let scope = cleanup::temporary_scope(bcx.tcx(), expr.id);
2187 let ptr = Load(bcx, datum.val);
2188 if !type_is_zero_size(bcx.ccx(), content_ty) {
2189 bcx.fcx.schedule_free_value(scope, ptr, cleanup::HeapExchange, content_ty);
2192 RvalueExpr(Rvalue { mode: ByValue }) => {
2193 let scope = cleanup::temporary_scope(bcx.tcx(), expr.id);
2194 if !type_is_zero_size(bcx.ccx(), content_ty) {
2195 bcx.fcx.schedule_free_value(scope, datum.val, cleanup::HeapExchange,
2202 // If we had an rvalue in, we produce an rvalue out.
2203 let (llptr, kind) = match datum.kind {
2205 (Load(bcx, datum.val), LvalueExpr)
2207 RvalueExpr(Rvalue { mode: ByRef }) => {
2208 (Load(bcx, datum.val), RvalueExpr(Rvalue::new(ByRef)))
2210 RvalueExpr(Rvalue { mode: ByValue }) => {
2211 (datum.val, RvalueExpr(Rvalue::new(ByRef)))
2215 let datum = Datum { ty: content_ty, val: llptr, kind: kind };
2216 DatumBlock { bcx: bcx, datum: datum }