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::subst::Subst;
45 use middle::trans::_match;
46 use middle::trans::adt;
47 use middle::trans::asm;
48 use middle::trans::base::*;
49 use middle::trans::base;
50 use middle::trans::build::*;
51 use middle::trans::callee;
52 use middle::trans::cleanup;
53 use middle::trans::cleanup::CleanupMethods;
54 use middle::trans::closure;
55 use middle::trans::common::*;
56 use middle::trans::consts;
57 use middle::trans::controlflow;
58 use middle::trans::datum::*;
59 use middle::trans::debuginfo;
60 use middle::trans::glue;
61 use middle::trans::machine;
62 use middle::trans::meth;
63 use middle::trans::inline;
64 use middle::trans::tvec;
65 use middle::trans::type_of;
66 use middle::ty::{struct_fields, tup_fields};
67 use middle::ty::{AutoDerefRef, AutoAddEnv, AutoUnsafe};
68 use middle::ty::{AutoPtr};
71 use middle::typeck::MethodCall;
72 use util::common::indenter;
73 use util::ppaux::Repr;
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(ty::TyTrait { def_id: def_id, substs: ref substs, .. }, _) => {
324 let substs = substs.with_self_ty(unsized_ty);
326 Rc::new(ty::TraitRef { def_id: def_id,
329 trait_ref.subst(bcx.tcx(), &bcx.fcx.param_substs.substs);
330 let box_ty = mk_ty(unsized_ty);
332 meth::get_vtable(bcx, box_ty, trait_ref),
333 Type::vtable_ptr(bcx.ccx()))
338 fn unsize_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
342 -> DatumBlock<'blk, 'tcx, Expr> {
344 let datum_ty = datum.ty;
345 let unsized_ty = ty::unsize_ty(tcx, datum_ty, k, expr.span);
346 let dest_ty = ty::mk_open(tcx, unsized_ty);
347 // Closures for extracting and manipulating the data and payload parts of
350 &ty::UnsizeStruct(..) =>
351 |bcx, val| PointerCast(bcx,
353 type_of::type_of(bcx.ccx(), unsized_ty).ptr_to()),
354 &ty::UnsizeLength(..) =>
355 |bcx, val| GEPi(bcx, val, [0u, 0u]),
356 &ty::UnsizeVtable(..) =>
357 |_bcx, val| PointerCast(bcx, val, Type::i8p(bcx.ccx()))
359 let info = |bcx, _val| unsized_info(bcx,
362 ty::deref_or_dont(datum_ty),
367 mutbl: ast::MutImmutable
369 into_fat_ptr(bcx, expr, datum, dest_ty, base, info)
372 fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
375 -> DatumBlock<'blk, 'tcx, Expr> {
377 let dest_ty = ty::close_type(tcx, datum.ty);
378 let base = |bcx, val| Load(bcx, get_dataptr(bcx, val));
379 let len = |bcx, val| Load(bcx, get_len(bcx, val));
380 into_fat_ptr(bcx, expr, datum, dest_ty, base, len)
383 fn into_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
387 base: |Block<'blk, 'tcx>, ValueRef| -> ValueRef,
388 info: |Block<'blk, 'tcx>, ValueRef| -> ValueRef)
389 -> DatumBlock<'blk, 'tcx, Expr> {
393 let lval = unpack_datum!(bcx,
394 datum.to_lvalue_datum(bcx, "into_fat_ptr", expr.id));
395 let base = base(bcx, lval.val);
396 let info = info(bcx, lval.val);
398 let scratch = rvalue_scratch_datum(bcx, dest_ty, "__fat_ptr");
399 Store(bcx, base, get_dataptr(bcx, scratch.val));
400 Store(bcx, info, get_len(bcx, scratch.val));
402 DatumBlock::new(bcx, scratch.to_expr_datum())
405 fn unsize_unique_vec<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
409 -> DatumBlock<'blk, 'tcx, Expr> {
413 let datum_ty = datum.ty;
415 let lval = unpack_datum!(bcx,
416 datum.to_lvalue_datum(bcx, "unsize_unique_vec", expr.id));
418 let ll_len = C_uint(bcx.ccx(), len);
419 let unit_ty = ty::sequence_element_type(tcx, ty::type_content(datum_ty));
420 let vec_ty = ty::mk_uniq(tcx, ty::mk_vec(tcx, unit_ty, None));
421 let scratch = rvalue_scratch_datum(bcx, vec_ty, "__unsize_unique");
423 let base = get_dataptr(bcx, scratch.val);
424 let base = PointerCast(bcx,
426 type_of::type_of(bcx.ccx(), datum_ty).ptr_to());
427 bcx = lval.store_to(bcx, base);
429 Store(bcx, ll_len, get_len(bcx, scratch.val));
430 DatumBlock::new(bcx, scratch.to_expr_datum())
433 fn unsize_unique_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
437 -> DatumBlock<'blk, 'tcx, Expr> {
441 let datum_ty = datum.ty;
442 let unboxed_ty = match ty::get(datum_ty).sty {
444 _ => bcx.sess().bug(format!("Expected ty_uniq, found {}",
445 bcx.ty_to_string(datum_ty)).as_slice())
447 let result_ty = ty::mk_uniq(tcx, ty::unsize_ty(tcx, unboxed_ty, k, expr.span));
449 let lval = unpack_datum!(bcx,
450 datum.to_lvalue_datum(bcx, "unsize_unique_expr", expr.id));
452 let scratch = rvalue_scratch_datum(bcx, result_ty, "__uniq_fat_ptr");
453 let llbox_ty = type_of::type_of(bcx.ccx(), datum_ty);
454 let base = PointerCast(bcx, get_dataptr(bcx, scratch.val), llbox_ty.ptr_to());
455 bcx = lval.store_to(bcx, base);
457 let info = unsized_info(bcx, k, expr.id, unboxed_ty, |t| ty::mk_uniq(tcx, t));
458 Store(bcx, info, get_len(bcx, scratch.val));
460 let scratch = unpack_datum!(bcx,
461 scratch.to_expr_datum().to_lvalue_datum(bcx,
462 "fresh_uniq_fat_ptr",
465 DatumBlock::new(bcx, scratch.to_expr_datum())
468 fn add_env<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
471 -> DatumBlock<'blk, 'tcx, Expr> {
472 // This is not the most efficient thing possible; since closures
473 // are two words it'd be better if this were compiled in
474 // 'dest' mode, but I can't find a nice way to structure the
475 // code and keep it DRY that accommodates that use case at the
478 let closure_ty = expr_ty_adjusted(bcx, expr);
479 let fn_ptr = datum.to_llscalarish(bcx);
480 let def = ty::resolve_expr(bcx.tcx(), expr);
481 closure::make_closure_from_bare_fn(bcx, closure_ty, def, fn_ptr)
485 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
488 -> DatumBlock<'blk, 'tcx, Lvalue> {
490 * Translates an expression in "lvalue" mode -- meaning that it
491 * returns a reference to the memory that the expr represents.
493 * If this expression is an rvalue, this implies introducing a
494 * temporary. In other words, something like `x().f` is
495 * translated into roughly the equivalent of
497 * { tmp = x(); tmp.f }
501 let datum = unpack_datum!(bcx, trans(bcx, expr));
502 return datum.to_lvalue_datum(bcx, name, expr.id);
505 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
507 -> DatumBlock<'blk, 'tcx, Expr> {
509 * A version of `trans` that ignores adjustments. You almost
510 * certainly do not want to call this directly.
515 debug!("trans_unadjusted(expr={})", bcx.expr_to_string(expr));
516 let _indenter = indenter();
518 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
520 return match ty::expr_kind(bcx.tcx(), expr) {
521 ty::LvalueExpr | ty::RvalueDatumExpr => {
522 let datum = unpack_datum!(bcx, {
523 trans_datum_unadjusted(bcx, expr)
526 DatumBlock {bcx: bcx, datum: datum}
529 ty::RvalueStmtExpr => {
530 bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
531 nil(bcx, expr_ty(bcx, expr))
534 ty::RvalueDpsExpr => {
535 let ty = expr_ty(bcx, expr);
536 if type_is_zero_size(bcx.ccx(), ty) {
537 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
540 let scratch = rvalue_scratch_datum(bcx, ty, "");
541 bcx = trans_rvalue_dps_unadjusted(
542 bcx, expr, SaveIn(scratch.val));
544 // Note: this is not obviously a good idea. It causes
545 // immediate values to be loaded immediately after a
546 // return from a call or other similar expression,
547 // which in turn leads to alloca's having shorter
548 // lifetimes and hence larger stack frames. However,
549 // in turn it can lead to more register pressure.
550 // Still, in practice it seems to increase
551 // performance, since we have fewer problems with
553 let scratch = unpack_datum!(
554 bcx, scratch.to_appropriate_datum(bcx));
556 DatumBlock::new(bcx, scratch.to_expr_datum())
561 fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: ty::t)
562 -> DatumBlock<'blk, 'tcx, Expr> {
563 let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
564 let datum = immediate_rvalue(llval, ty);
565 DatumBlock::new(bcx, datum.to_expr_datum())
569 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
571 -> DatumBlock<'blk, 'tcx, Expr> {
574 let _icx = push_ctxt("trans_datum_unadjusted");
577 ast::ExprParen(ref e) => {
580 ast::ExprPath(_) => {
581 trans_def(bcx, expr, bcx.def(expr.id))
583 ast::ExprField(ref base, ident, _) => {
584 trans_rec_field(bcx, &**base, ident.node)
586 ast::ExprTupField(ref base, idx, _) => {
587 trans_rec_tup_field(bcx, &**base, idx.node)
589 ast::ExprIndex(ref base, ref idx) => {
590 trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id))
592 ast::ExprBox(_, ref contents) => {
593 // Special case for `Box<T>` and `Gc<T>`
594 let box_ty = expr_ty(bcx, expr);
595 let contents_ty = expr_ty(bcx, &**contents);
596 match ty::get(box_ty).sty {
598 trans_uniq_expr(bcx, box_ty, &**contents, contents_ty)
601 trans_managed_expr(bcx, box_ty, &**contents, contents_ty)
603 _ => bcx.sess().span_bug(expr.span,
604 "expected unique or managed box")
608 ast::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, &**lit),
609 ast::ExprBinary(op, ref lhs, ref rhs) => {
610 trans_binary(bcx, expr, op, &**lhs, &**rhs)
612 ast::ExprUnary(op, ref x) => {
613 trans_unary(bcx, expr, op, &**x)
615 ast::ExprAddrOf(_, ref x) => {
617 ast::ExprRepeat(..) | ast::ExprVec(..) => {
618 // Special case for slices.
619 fcx.push_ast_cleanup_scope(x.id);
620 let datum = unpack_datum!(
621 bcx, tvec::trans_slice_vec(bcx, expr, &**x));
622 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
623 DatumBlock::new(bcx, datum)
626 trans_addr_of(bcx, expr, &**x)
630 ast::ExprCast(ref val, _) => {
631 // Datum output mode means this is a scalar cast:
632 trans_imm_cast(bcx, &**val, expr.id)
635 bcx.tcx().sess.span_bug(
637 format!("trans_rvalue_datum_unadjusted reached \
638 fall-through case: {:?}",
639 expr.node).as_slice());
644 fn trans_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
646 get_idx: |&'blk ty::ctxt<'tcx>, &[ty::field]| -> uint)
647 -> DatumBlock<'blk, 'tcx, Expr> {
649 let _icx = push_ctxt("trans_rec_field");
651 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
652 let bare_ty = ty::unopen_type(base_datum.ty);
653 let repr = adt::represent_type(bcx.ccx(), bare_ty);
654 with_field_tys(bcx.tcx(), bare_ty, None, |discr, field_tys| {
655 let ix = get_idx(bcx.tcx(), field_tys);
656 let d = base_datum.get_element(
659 |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, ix));
661 if ty::type_is_sized(bcx.tcx(), d.ty) {
662 DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
664 let scratch = rvalue_scratch_datum(bcx, ty::mk_open(bcx.tcx(), d.ty), "");
665 Store(bcx, d.val, get_dataptr(bcx, scratch.val));
666 let info = Load(bcx, get_len(bcx, base_datum.val));
667 Store(bcx, info, get_len(bcx, scratch.val));
669 DatumBlock::new(bcx, scratch.to_expr_datum())
676 /// Translates `base.field`.
677 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
680 -> DatumBlock<'blk, 'tcx, Expr> {
681 trans_field(bcx, base, |tcx, field_tys| ty::field_idx_strict(tcx, field.name, field_tys))
684 /// Translates `base.<idx>`.
685 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
688 -> DatumBlock<'blk, 'tcx, Expr> {
689 trans_field(bcx, base, |_, _| idx)
692 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
693 index_expr: &ast::Expr,
696 method_call: MethodCall)
697 -> DatumBlock<'blk, 'tcx, Expr> {
698 //! Translates `base[idx]`.
700 let _icx = push_ctxt("trans_index");
704 // Check for overloaded index.
705 let method_ty = ccx.tcx()
709 .map(|method| method.ty);
710 let elt_datum = match method_ty {
712 let base_datum = unpack_datum!(bcx, trans(bcx, base));
714 // Translate index expression.
715 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
717 // Overloaded. Evaluate `trans_overloaded_op`, which will
718 // invoke the user's index() method, which basically yields
719 // a `&T` pointer. We can then proceed down the normal
720 // path (below) to dereference that `&T`.
723 trans_overloaded_op(bcx,
727 Some((ix_datum, idx.id)),
729 let ref_ty = ty::ty_fn_ret(monomorphize_type(bcx, method_ty));
730 let elt_ty = match ty::deref(ref_ty, true) {
732 bcx.tcx().sess.span_bug(index_expr.span,
733 "index method didn't return a \
734 dereferenceable type?!")
736 Some(elt_tm) => elt_tm.ty,
738 Datum::new(val, elt_ty, LvalueExpr)
741 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
745 // Translate index expression and cast to a suitable LLVM integer.
746 // Rust is less strict than LLVM in this regard.
747 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
748 let ix_val = ix_datum.to_llscalarish(bcx);
749 let ix_size = machine::llbitsize_of_real(bcx.ccx(),
751 let int_size = machine::llbitsize_of_real(bcx.ccx(),
754 if ix_size < int_size {
755 if ty::type_is_signed(expr_ty(bcx, idx)) {
756 SExt(bcx, ix_val, ccx.int_type())
757 } else { ZExt(bcx, ix_val, ccx.int_type()) }
758 } else if ix_size > int_size {
759 Trunc(bcx, ix_val, ccx.int_type())
767 ty::sequence_element_type(bcx.tcx(),
769 base::maybe_name_value(bcx.ccx(), vt.llunit_size, "unit_sz");
771 let (base, len) = base_datum.get_vec_base_and_len(bcx);
773 debug!("trans_index: base {}", bcx.val_to_string(base));
774 debug!("trans_index: len {}", bcx.val_to_string(len));
776 let bounds_check = ICmp(bcx, llvm::IntUGE, ix_val, len);
777 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
778 let expected = Call(bcx,
780 [bounds_check, C_bool(ccx, false)],
782 bcx = with_cond(bcx, expected, |bcx| {
783 controlflow::trans_fail_bounds_check(bcx,
788 let elt = InBoundsGEP(bcx, base, [ix_val]);
789 let elt = PointerCast(bcx, elt, vt.llunit_ty.ptr_to());
790 Datum::new(elt, vt.unit_ty, LvalueExpr)
794 DatumBlock::new(bcx, elt_datum)
797 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
798 ref_expr: &ast::Expr,
800 -> DatumBlock<'blk, 'tcx, Expr> {
801 //! Translates a reference to a path.
803 let _icx = push_ctxt("trans_def_lvalue");
805 def::DefFn(..) | def::DefStaticMethod(..) |
806 def::DefStruct(_) | def::DefVariant(..) => {
807 trans_def_fn_unadjusted(bcx, ref_expr, def)
809 def::DefStatic(did, _) => {
810 // There are three things that may happen here:
811 // 1) If the static item is defined in this crate, it will be
812 // translated using `get_item_val`, and we return a pointer to
814 // 2) If the static item is defined in another crate, but is
815 // marked inlineable, then it will be inlined into this crate
816 // and then translated with `get_item_val`. Again, we return a
817 // pointer to the result.
818 // 3) If the static item is defined in another crate and is not
819 // marked inlineable, then we add (or reuse) a declaration of
820 // an external global, and return a pointer to that.
821 let const_ty = expr_ty(bcx, ref_expr);
823 fn get_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, did: ast::DefId, const_ty: ty::t)
825 // For external constants, we don't inline.
826 if did.krate == ast::LOCAL_CRATE {
827 // Case 1 or 2. (The inlining in case 2 produces a new
828 // DefId in LOCAL_CRATE.)
830 // The LLVM global has the type of its initializer,
831 // which may not be equal to the enum's type for
833 let val = base::get_item_val(bcx.ccx(), did.node);
834 let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to();
835 PointerCast(bcx, val, pty)
838 match bcx.ccx().extern_const_values().borrow().find(&did) {
839 None => {} // Continue.
846 let llty = type_of::type_of(bcx.ccx(), const_ty);
847 let symbol = csearch::get_symbol(
848 &bcx.ccx().sess().cstore,
850 let llval = symbol.as_slice().with_c_str(|buf| {
851 llvm::LLVMAddGlobal(bcx.ccx().llmod(),
855 bcx.ccx().extern_const_values().borrow_mut()
861 // The DefId produced by `maybe_instantiate_inline`
862 // may be in the LOCAL_CRATE or not.
863 let did = inline::maybe_instantiate_inline(bcx.ccx(), did);
864 let val = get_val(bcx, did, const_ty);
865 DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr))
868 DatumBlock::new(bcx, trans_local_var(bcx, def).to_expr_datum())
873 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
875 -> Block<'blk, 'tcx> {
877 let _icx = push_ctxt("trans_rvalue_stmt");
879 if bcx.unreachable.get() {
884 ast::ExprParen(ref e) => {
885 trans_into(bcx, &**e, Ignore)
887 ast::ExprBreak(label_opt) => {
888 controlflow::trans_break(bcx, expr.id, label_opt)
890 ast::ExprAgain(label_opt) => {
891 controlflow::trans_cont(bcx, expr.id, label_opt)
893 ast::ExprRet(ref ex) => {
894 controlflow::trans_ret(bcx, ex.as_ref().map(|e| &**e))
896 ast::ExprWhile(ref cond, ref body, _) => {
897 controlflow::trans_while(bcx, expr.id, &**cond, &**body)
899 ast::ExprForLoop(ref pat, ref head, ref body, _) => {
900 controlflow::trans_for(bcx,
906 ast::ExprLoop(ref body, _) => {
907 controlflow::trans_loop(bcx, expr.id, &**body)
909 ast::ExprAssign(ref dst, ref src) => {
910 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
912 if ty::type_needs_drop(bcx.tcx(), dst_datum.ty) {
913 // If there are destructors involved, make sure we
914 // are copying from an rvalue, since that cannot possible
915 // alias an lvalue. We are concerned about code like:
923 // where e.g. a : Option<Foo> and a.b :
924 // Option<Foo>. In that case, freeing `a` before the
925 // assignment may also free `a.b`!
927 // We could avoid this intermediary with some analysis
928 // to determine whether `dst` may possibly own `src`.
929 let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
930 let src_datum = unpack_datum!(
931 bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
932 bcx = glue::drop_ty(bcx, dst_datum.val, dst_datum.ty);
933 src_datum.store_to(bcx, dst_datum.val)
935 trans_into(bcx, &**src, SaveIn(dst_datum.to_llref()))
938 ast::ExprAssignOp(op, ref dst, ref src) => {
939 trans_assign_op(bcx, expr, op, &**dst, &**src)
941 ast::ExprInlineAsm(ref a) => {
942 asm::trans_inline_asm(bcx, a)
945 bcx.tcx().sess.span_bug(
947 format!("trans_rvalue_stmt_unadjusted reached \
948 fall-through case: {:?}",
949 expr.node).as_slice());
954 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
957 -> Block<'blk, 'tcx> {
958 let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
963 ast::ExprParen(ref e) => {
964 trans_into(bcx, &**e, dest)
966 ast::ExprPath(_) => {
967 trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
969 ast::ExprIf(ref cond, ref thn, ref els) => {
970 controlflow::trans_if(bcx, expr.id, &**cond, &**thn, els.as_ref().map(|e| &**e), dest)
972 ast::ExprMatch(ref discr, ref arms) => {
973 _match::trans_match(bcx, expr, &**discr, arms.as_slice(), dest)
975 ast::ExprBlock(ref blk) => {
976 controlflow::trans_block(bcx, &**blk, dest)
978 ast::ExprStruct(_, ref fields, ref base) => {
981 base.as_ref().map(|e| &**e),
986 ast::ExprTup(ref args) => {
987 let numbered_fields: Vec<(uint, &ast::Expr)> =
988 args.iter().enumerate().map(|(i, arg)| (i, &**arg)).collect();
989 trans_adt(bcx, expr_ty(bcx, expr), 0, numbered_fields.as_slice(), None, dest)
991 ast::ExprLit(ref lit) => {
993 ast::LitStr(ref s, _) => {
994 tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1000 "trans_rvalue_dps_unadjusted shouldn't be \
1001 translating this type of literal")
1005 ast::ExprVec(..) | ast::ExprRepeat(..) => {
1006 tvec::trans_fixed_vstore(bcx, expr, dest)
1008 ast::ExprFnBlock(_, ref decl, ref body) |
1009 ast::ExprProc(ref decl, ref body) => {
1010 let expr_ty = expr_ty(bcx, expr);
1011 let store = ty::ty_closure_store(expr_ty);
1012 debug!("translating block function {} with type {}",
1013 expr_to_string(expr), expr_ty.repr(tcx));
1014 closure::trans_expr_fn(bcx, store, &**decl, &**body, expr.id, dest)
1016 ast::ExprUnboxedFn(_, _, ref decl, ref body) => {
1017 closure::trans_unboxed_closure(bcx, &**decl, &**body, expr.id, dest)
1019 ast::ExprCall(ref f, ref args) => {
1020 if bcx.tcx().is_method_call(expr.id) {
1021 trans_overloaded_call(bcx,
1027 callee::trans_call(bcx,
1030 callee::ArgExprs(args.as_slice()),
1034 ast::ExprMethodCall(_, _, ref args) => {
1035 callee::trans_method_call(bcx,
1038 callee::ArgExprs(args.as_slice()),
1041 ast::ExprBinary(_, ref lhs, ref rhs) => {
1042 // if not overloaded, would be RvalueDatumExpr
1043 let lhs = unpack_datum!(bcx, trans(bcx, &**lhs));
1044 let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs));
1045 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs,
1046 Some((rhs_datum, rhs.id)), Some(dest)).bcx
1048 ast::ExprUnary(_, ref subexpr) => {
1049 // if not overloaded, would be RvalueDatumExpr
1050 let arg = unpack_datum!(bcx, trans(bcx, &**subexpr));
1051 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id),
1052 arg, None, Some(dest)).bcx
1054 ast::ExprIndex(ref base, ref idx) => {
1055 // if not overloaded, would be RvalueDatumExpr
1056 let base = unpack_datum!(bcx, trans(bcx, &**base));
1057 let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx));
1058 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
1059 Some((idx_datum, idx.id)), Some(dest)).bcx
1061 ast::ExprCast(ref val, _) => {
1062 // DPS output mode means this is a trait cast:
1063 if ty::type_is_trait(node_id_type(bcx, expr.id)) {
1065 bcx.tcx().object_cast_map.borrow()
1067 .map(|t| (*t).clone())
1070 trait_ref.subst(bcx.tcx(), &bcx.fcx.param_substs.substs);
1071 let datum = unpack_datum!(bcx, trans(bcx, &**val));
1072 meth::trans_trait_cast(bcx, datum, expr.id,
1075 bcx.tcx().sess.span_bug(expr.span,
1076 "expr_cast of non-trait");
1079 ast::ExprAssignOp(op, ref dst, ref src) => {
1080 trans_assign_op(bcx, expr, op, &**dst, &**src)
1083 bcx.tcx().sess.span_bug(
1085 format!("trans_rvalue_dps_unadjusted reached fall-through \
1087 expr.node).as_slice());
1092 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1093 ref_expr: &ast::Expr,
1096 -> Block<'blk, 'tcx> {
1097 let _icx = push_ctxt("trans_def_dps_unadjusted");
1099 let lldest = match dest {
1100 SaveIn(lldest) => lldest,
1101 Ignore => { return bcx; }
1105 def::DefVariant(tid, vid, _) => {
1106 let variant_info = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
1107 if variant_info.args.len() > 0u {
1109 let llfn = callee::trans_fn_ref(bcx, vid, ExprId(ref_expr.id));
1110 Store(bcx, llfn, lldest);
1114 let ty = expr_ty(bcx, ref_expr);
1115 let repr = adt::represent_type(bcx.ccx(), ty);
1116 adt::trans_set_discr(bcx, &*repr, lldest,
1117 variant_info.disr_val);
1121 def::DefStruct(_) => {
1122 let ty = expr_ty(bcx, ref_expr);
1123 match ty::get(ty).sty {
1124 ty::ty_struct(did, _) if ty::has_dtor(bcx.tcx(), did) => {
1125 let repr = adt::represent_type(bcx.ccx(), ty);
1126 adt::trans_set_discr(bcx, &*repr, lldest, 0);
1133 bcx.tcx().sess.span_bug(ref_expr.span, format!(
1134 "Non-DPS def {:?} referened by {}",
1135 def, bcx.node_id_to_string(ref_expr.id)).as_slice());
1140 fn trans_def_fn_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1141 ref_expr: &ast::Expr,
1143 -> DatumBlock<'blk, 'tcx, Expr> {
1144 let _icx = push_ctxt("trans_def_datum_unadjusted");
1146 let llfn = match def {
1147 def::DefFn(did, _) |
1148 def::DefStruct(did) | def::DefVariant(_, did, _) |
1149 def::DefStaticMethod(did, def::FromImpl(_), _) => {
1150 callee::trans_fn_ref(bcx, did, ExprId(ref_expr.id))
1152 def::DefStaticMethod(impl_did, def::FromTrait(trait_did), _) => {
1153 meth::trans_static_method_callee(bcx, impl_did,
1154 trait_did, ref_expr.id)
1157 bcx.tcx().sess.span_bug(ref_expr.span, format!(
1158 "trans_def_fn_unadjusted invoked on: {:?} for {}",
1160 ref_expr.repr(bcx.tcx())).as_slice());
1164 let fn_ty = expr_ty(bcx, ref_expr);
1165 DatumBlock::new(bcx, Datum::new(llfn, fn_ty, RvalueExpr(Rvalue::new(ByValue))))
1168 pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1172 * Translates a reference to a local variable or argument.
1173 * This always results in an lvalue datum.
1176 let _icx = push_ctxt("trans_local_var");
1179 def::DefUpvar(nid, _, _, _) => {
1180 // Can't move upvars, so this is never a ZeroMemLastUse.
1181 let local_ty = node_id_type(bcx, nid);
1182 match bcx.fcx.llupvars.borrow().find(&nid) {
1183 Some(&val) => Datum::new(val, local_ty, Lvalue),
1185 bcx.sess().bug(format!(
1186 "trans_local_var: no llval for upvar {:?} found",
1191 def::DefLocal(nid, _) => {
1192 let datum = match bcx.fcx.lllocals.borrow().find(&nid) {
1195 bcx.sess().bug(format!(
1196 "trans_local_var: no datum for local/arg {:?} found",
1200 debug!("take_local(nid={:?}, v={}, ty={})",
1201 nid, bcx.val_to_string(datum.val), bcx.ty_to_string(datum.ty));
1205 bcx.sess().unimpl(format!(
1206 "unsupported def type in trans_local_var: {:?}",
1212 pub fn with_field_tys<R>(tcx: &ty::ctxt,
1214 node_id_opt: Option<ast::NodeId>,
1215 op: |ty::Disr, (&[ty::field])| -> R)
1218 * Helper for enumerating the field types of structs, enums, or records.
1219 * The optional node ID here is the node ID of the path identifying the enum
1220 * variant in use. If none, this cannot possibly an enum variant (so, if it
1221 * is and `node_id_opt` is none, this function fails).
1224 match ty::get(ty).sty {
1225 ty::ty_struct(did, ref substs) => {
1226 op(0, struct_fields(tcx, did, substs).as_slice())
1229 ty::ty_tup(ref v) => {
1230 op(0, tup_fields(v.as_slice()).as_slice())
1233 ty::ty_enum(_, ref substs) => {
1234 // We want the *variant* ID here, not the enum ID.
1237 tcx.sess.bug(format!(
1238 "cannot get field types from the enum type {} \
1240 ty.repr(tcx)).as_slice());
1243 let def = tcx.def_map.borrow().get_copy(&node_id);
1245 def::DefVariant(enum_id, variant_id, _) => {
1246 let variant_info = ty::enum_variant_with_id(
1247 tcx, enum_id, variant_id);
1248 op(variant_info.disr_val,
1254 tcx.sess.bug("resolve didn't map this expr to a \
1263 tcx.sess.bug(format!(
1264 "cannot get field types from the type {}",
1265 ty.repr(tcx)).as_slice());
1270 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1271 fields: &[ast::Field],
1272 base: Option<&ast::Expr>,
1273 expr_span: codemap::Span,
1275 dest: Dest) -> Block<'blk, 'tcx> {
1276 let _icx = push_ctxt("trans_rec");
1278 let ty = node_id_type(bcx, id);
1279 let tcx = bcx.tcx();
1280 with_field_tys(tcx, ty, Some(id), |discr, field_tys| {
1281 let mut need_base = Vec::from_elem(field_tys.len(), true);
1283 let numbered_fields = fields.iter().map(|field| {
1285 field_tys.iter().position(|field_ty|
1286 field_ty.ident.name == field.ident.node.name);
1289 *need_base.get_mut(i) = false;
1293 tcx.sess.span_bug(field.span,
1294 "Couldn't find field in struct type")
1297 }).collect::<Vec<_>>();
1298 let optbase = match base {
1299 Some(base_expr) => {
1300 let mut leftovers = Vec::new();
1301 for (i, b) in need_base.iter().enumerate() {
1303 leftovers.push((i, field_tys[i].mt.ty))
1306 Some(StructBaseInfo {expr: base_expr,
1307 fields: leftovers })
1310 if need_base.iter().any(|b| *b) {
1311 tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1317 trans_adt(bcx, ty, discr, numbered_fields.as_slice(), optbase, dest)
1322 * Information that `trans_adt` needs in order to fill in the fields
1323 * of a struct copied from a base struct (e.g., from an expression
1324 * like `Foo { a: b, ..base }`.
1326 * Note that `fields` may be empty; the base expression must always be
1327 * evaluated for side-effects.
1329 pub struct StructBaseInfo<'a> {
1330 /// The base expression; will be evaluated after all explicit fields.
1331 expr: &'a ast::Expr,
1332 /// The indices of fields to copy paired with their types.
1333 fields: Vec<(uint, ty::t)>
1337 * Constructs an ADT instance:
1339 * - `fields` should be a list of field indices paired with the
1340 * expression to store into that field. The initializers will be
1341 * evaluated in the order specified by `fields`.
1343 * - `optbase` contains information on the base struct (if any) from
1344 * which remaining fields are copied; see comments on `StructBaseInfo`.
1346 pub fn trans_adt<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1349 fields: &[(uint, &ast::Expr)],
1350 optbase: Option<StructBaseInfo>,
1351 dest: Dest) -> Block<'blk, 'tcx> {
1352 let _icx = push_ctxt("trans_adt");
1354 let repr = adt::represent_type(bcx.ccx(), ty);
1356 // If we don't care about the result, just make a
1357 // temporary stack slot
1358 let addr = match dest {
1360 Ignore => alloc_ty(bcx, ty, "temp"),
1363 // This scope holds intermediates that must be cleaned should
1364 // failure occur before the ADT as a whole is ready.
1365 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1367 // First we trans the base, if we have one, to the dest
1368 for base in optbase.iter() {
1369 assert_eq!(discr, 0);
1371 match ty::expr_kind(bcx.tcx(), &*base.expr) {
1372 ty::RvalueDpsExpr | ty::RvalueDatumExpr if !ty::type_needs_drop(bcx.tcx(), ty) => {
1373 bcx = trans_into(bcx, &*base.expr, SaveIn(addr));
1375 ty::RvalueStmtExpr => bcx.tcx().sess.bug("unexpected expr kind for struct base expr"),
1377 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base"));
1378 for &(i, t) in base.fields.iter() {
1379 let datum = base_datum.get_element(
1380 bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i));
1381 assert!(ty::type_is_sized(bcx.tcx(), datum.ty));
1382 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1383 bcx = datum.store_to(bcx, dest);
1389 // Now, we just overwrite the fields we've explicitly specified
1390 for &(i, ref e) in fields.iter() {
1391 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1392 let e_ty = expr_ty_adjusted(bcx, &**e);
1393 bcx = trans_into(bcx, &**e, SaveIn(dest));
1394 let scope = cleanup::CustomScope(custom_cleanup_scope);
1395 fcx.schedule_lifetime_end(scope, dest);
1396 fcx.schedule_drop_mem(scope, dest, e_ty);
1399 adt::trans_set_discr(bcx, &*repr, addr, discr);
1401 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1403 // If we don't care about the result drop the temporary we made
1407 bcx = glue::drop_ty(bcx, addr, ty);
1408 base::call_lifetime_end(bcx, addr);
1415 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1418 -> DatumBlock<'blk, 'tcx, Expr> {
1419 // must not be a string constant, that is a RvalueDpsExpr
1420 let _icx = push_ctxt("trans_immediate_lit");
1421 let ty = expr_ty(bcx, expr);
1422 let v = consts::const_lit(bcx.ccx(), expr, lit);
1423 immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1426 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1429 sub_expr: &ast::Expr)
1430 -> DatumBlock<'blk, 'tcx, Expr> {
1431 let ccx = bcx.ccx();
1433 let _icx = push_ctxt("trans_unary_datum");
1435 let method_call = MethodCall::expr(expr.id);
1437 // The only overloaded operator that is translated to a datum
1438 // is an overloaded deref, since it is always yields a `&T`.
1439 // Otherwise, we should be in the RvalueDpsExpr path.
1441 op == ast::UnDeref ||
1442 !ccx.tcx().method_map.borrow().contains_key(&method_call));
1444 let un_ty = expr_ty(bcx, expr);
1448 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1449 let llresult = Not(bcx, datum.to_llscalarish(bcx));
1450 immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1453 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1454 let val = datum.to_llscalarish(bcx);
1456 if ty::type_is_fp(un_ty) {
1462 immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1465 trans_managed_expr(bcx, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1468 trans_uniq_expr(bcx, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1471 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1472 deref_once(bcx, expr, datum, method_call)
1477 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1479 contents: &ast::Expr,
1481 -> DatumBlock<'blk, 'tcx, Expr> {
1482 let _icx = push_ctxt("trans_uniq_expr");
1484 assert!(ty::type_is_sized(bcx.tcx(), contents_ty));
1485 let llty = type_of::type_of(bcx.ccx(), contents_ty);
1486 let size = llsize_of(bcx.ccx(), llty);
1487 let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty) as uint);
1488 let llty_ptr = llty.ptr_to();
1489 let Result { bcx, val } = malloc_raw_dyn(bcx, llty_ptr, box_ty, size, align);
1490 // Unique boxes do not allocate for zero-size types. The standard library
1491 // may assume that `free` is never called on the pointer returned for
1492 // `Box<ZeroSizeType>`.
1493 let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1494 trans_into(bcx, contents, SaveIn(val))
1496 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1497 fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1498 val, cleanup::HeapExchange, contents_ty);
1499 let bcx = trans_into(bcx, contents, SaveIn(val));
1500 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1503 immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1506 fn trans_managed_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1508 contents: &ast::Expr,
1510 -> DatumBlock<'blk, 'tcx, Expr> {
1511 let _icx = push_ctxt("trans_managed_expr");
1513 let ty = type_of::type_of(bcx.ccx(), contents_ty);
1514 let Result {bcx, val: bx} = malloc_raw_dyn_managed(bcx, contents_ty, MallocFnLangItem,
1515 llsize_of(bcx.ccx(), ty));
1516 let body = GEPi(bcx, bx, [0u, abi::box_field_body]);
1518 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1519 fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1520 bx, cleanup::HeapManaged, contents_ty);
1521 let bcx = trans_into(bcx, contents, SaveIn(body));
1522 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1523 immediate_rvalue_bcx(bcx, bx, box_ty).to_expr_datumblock()
1526 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1528 subexpr: &ast::Expr)
1529 -> DatumBlock<'blk, 'tcx, Expr> {
1530 let _icx = push_ctxt("trans_addr_of");
1532 let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1533 match ty::get(sub_datum.ty).sty {
1535 // Opened DST value, close to a fat pointer
1536 debug!("Closing fat pointer {}", bcx.ty_to_string(sub_datum.ty));
1538 let scratch = rvalue_scratch_datum(bcx,
1539 ty::close_type(bcx.tcx(), sub_datum.ty),
1541 let base = Load(bcx, get_dataptr(bcx, sub_datum.val));
1542 Store(bcx, base, get_dataptr(bcx, scratch.val));
1544 let len = Load(bcx, get_len(bcx, sub_datum.val));
1545 Store(bcx, len, get_len(bcx, scratch.val));
1547 DatumBlock::new(bcx, scratch.to_expr_datum())
1550 // Sized value, ref to a thin pointer
1551 let ty = expr_ty(bcx, expr);
1552 immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1557 // Important to get types for both lhs and rhs, because one might be _|_
1558 // and the other not.
1559 fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1560 binop_expr: &ast::Expr,
1567 -> DatumBlock<'blk, 'tcx, Expr> {
1568 let _icx = push_ctxt("trans_eager_binop");
1570 let tcx = bcx.tcx();
1571 let is_simd = ty::type_is_simd(tcx, lhs_t);
1573 if ty::type_is_bot(lhs_t) { rhs_t }
1574 else if is_simd { ty::simd_type(tcx, lhs_t) }
1577 let is_float = ty::type_is_fp(intype);
1578 let is_signed = ty::type_is_signed(intype);
1580 let rhs = base::cast_shift_expr_rhs(bcx, op, lhs, rhs);
1583 let val = match op {
1585 if is_float { FAdd(bcx, lhs, rhs) }
1586 else { Add(bcx, lhs, rhs) }
1589 if is_float { FSub(bcx, lhs, rhs) }
1590 else { Sub(bcx, lhs, rhs) }
1593 if is_float { FMul(bcx, lhs, rhs) }
1594 else { Mul(bcx, lhs, rhs) }
1600 // Only zero-check integers; fp /0 is NaN
1601 bcx = base::fail_if_zero_or_overflows(bcx, binop_expr.span,
1602 op, lhs, rhs, rhs_t);
1614 // Only zero-check integers; fp %0 is NaN
1615 bcx = base::fail_if_zero_or_overflows(bcx, binop_expr.span,
1616 op, lhs, rhs, rhs_t);
1624 ast::BiBitOr => Or(bcx, lhs, rhs),
1625 ast::BiBitAnd => And(bcx, lhs, rhs),
1626 ast::BiBitXor => Xor(bcx, lhs, rhs),
1627 ast::BiShl => Shl(bcx, lhs, rhs),
1631 } else { LShr(bcx, lhs, rhs) }
1633 ast::BiEq | ast::BiNe | ast::BiLt | ast::BiGe | ast::BiLe | ast::BiGt => {
1634 if ty::type_is_bot(rhs_t) {
1635 C_bool(bcx.ccx(), false)
1636 } else if ty::type_is_scalar(rhs_t) {
1637 unpack_result!(bcx, base::compare_scalar_types(bcx, lhs, rhs, rhs_t, op))
1639 base::compare_simd_types(bcx, lhs, rhs, intype, ty::simd_size(tcx, lhs_t), op)
1641 bcx.tcx().sess.span_bug(binop_expr.span, "comparison operator unsupported for type")
1645 bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1649 immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1652 // refinement types would obviate the need for this
1653 enum lazy_binop_ty {
1658 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1659 binop_expr: &ast::Expr,
1663 -> DatumBlock<'blk, 'tcx, Expr> {
1664 let _icx = push_ctxt("trans_lazy_binop");
1665 let binop_ty = expr_ty(bcx, binop_expr);
1668 let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1669 let lhs = lhs.to_llscalarish(past_lhs);
1671 if past_lhs.unreachable.get() {
1672 return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1675 let join = fcx.new_id_block("join", binop_expr.id);
1676 let before_rhs = fcx.new_id_block("before_rhs", b.id);
1679 lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb),
1680 lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb)
1683 let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1684 let rhs = rhs.to_llscalarish(past_rhs);
1686 if past_rhs.unreachable.get() {
1687 return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1690 Br(past_rhs, join.llbb);
1691 let phi = Phi(join, Type::i1(bcx.ccx()), [lhs, rhs],
1692 [past_lhs.llbb, past_rhs.llbb]);
1694 return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1697 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1702 -> DatumBlock<'blk, 'tcx, Expr> {
1703 let _icx = push_ctxt("trans_binary");
1704 let ccx = bcx.ccx();
1706 // if overloaded, would be RvalueDpsExpr
1707 assert!(!ccx.tcx().method_map.borrow().contains_key(&MethodCall::expr(expr.id)));
1711 trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1714 trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1718 let lhs_datum = unpack_datum!(bcx, trans(bcx, lhs));
1719 let rhs_datum = unpack_datum!(bcx, trans(bcx, rhs));
1720 let binop_ty = expr_ty(bcx, expr);
1722 debug!("trans_binary (expr {}): lhs_datum={}",
1724 lhs_datum.to_string(ccx));
1725 let lhs_ty = lhs_datum.ty;
1726 let lhs = lhs_datum.to_llscalarish(bcx);
1728 debug!("trans_binary (expr {}): rhs_datum={}",
1730 rhs_datum.to_string(ccx));
1731 let rhs_ty = rhs_datum.ty;
1732 let rhs = rhs_datum.to_llscalarish(bcx);
1733 trans_eager_binop(bcx, expr, binop_ty, op,
1734 lhs_ty, lhs, rhs_ty, rhs)
1739 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1741 method_call: MethodCall,
1743 rhs: Option<(Datum<Expr>, ast::NodeId)>,
1745 -> Result<'blk, 'tcx> {
1746 let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
1747 callee::trans_call_inner(bcx,
1748 Some(expr_info(expr)),
1749 monomorphize_type(bcx, method_ty),
1750 |bcx, arg_cleanup_scope| {
1751 meth::trans_method_callee(bcx,
1756 callee::ArgOverloadedOp(lhs, rhs),
1760 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1762 callee: &'a ast::Expr,
1763 args: &'a [P<ast::Expr>],
1765 -> Block<'blk, 'tcx> {
1766 let method_call = MethodCall::expr(expr.id);
1767 let method_type = bcx.tcx()
1772 let mut all_args = vec!(callee);
1773 all_args.extend(args.iter().map(|e| &**e));
1775 callee::trans_call_inner(bcx,
1776 Some(expr_info(expr)),
1777 monomorphize_type(bcx,
1779 |bcx, arg_cleanup_scope| {
1780 meth::trans_method_callee(
1786 callee::ArgOverloadedCall(all_args),
1791 fn int_cast(bcx: Block,
1797 let _icx = push_ctxt("int_cast");
1799 let srcsz = llvm::LLVMGetIntTypeWidth(llsrctype.to_ref());
1800 let dstsz = llvm::LLVMGetIntTypeWidth(lldsttype.to_ref());
1801 return if dstsz == srcsz {
1802 BitCast(bcx, llsrc, lldsttype)
1803 } else if srcsz > dstsz {
1804 TruncOrBitCast(bcx, llsrc, lldsttype)
1806 SExtOrBitCast(bcx, llsrc, lldsttype)
1808 ZExtOrBitCast(bcx, llsrc, lldsttype)
1813 fn float_cast(bcx: Block,
1818 let _icx = push_ctxt("float_cast");
1819 let srcsz = llsrctype.float_width();
1820 let dstsz = lldsttype.float_width();
1821 return if dstsz > srcsz {
1822 FPExt(bcx, llsrc, lldsttype)
1823 } else if srcsz > dstsz {
1824 FPTrunc(bcx, llsrc, lldsttype)
1828 #[deriving(PartialEq)]
1829 pub enum cast_kind {
1837 pub fn cast_type_kind(tcx: &ty::ctxt, t: ty::t) -> cast_kind {
1838 match ty::get(t).sty {
1839 ty::ty_char => cast_integral,
1840 ty::ty_float(..) => cast_float,
1841 ty::ty_rptr(_, mt) | ty::ty_ptr(mt) => {
1842 if ty::type_is_sized(tcx, mt.ty) {
1848 ty::ty_bare_fn(..) => cast_pointer,
1849 ty::ty_int(..) => cast_integral,
1850 ty::ty_uint(..) => cast_integral,
1851 ty::ty_bool => cast_integral,
1852 ty::ty_enum(..) => cast_enum,
1857 fn cast_is_noop(t_in: ty::t, t_out: ty::t) -> bool {
1858 if ty::type_is_boxed(t_in) || ty::type_is_boxed(t_out) {
1862 match (ty::deref(t_in, true), ty::deref(t_out, true)) {
1863 (Some(ty::mt{ ty: t_in, .. }), Some(ty::mt{ ty: t_out, .. })) => {
1870 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1873 -> DatumBlock<'blk, 'tcx, Expr> {
1874 let _icx = push_ctxt("trans_cast");
1876 let ccx = bcx.ccx();
1878 let t_in = expr_ty(bcx, expr);
1879 let t_out = node_id_type(bcx, id);
1880 let k_in = cast_type_kind(bcx.tcx(), t_in);
1881 let k_out = cast_type_kind(bcx.tcx(), t_out);
1882 let s_in = k_in == cast_integral && ty::type_is_signed(t_in);
1883 let ll_t_in = type_of::arg_type_of(ccx, t_in);
1884 let ll_t_out = type_of::arg_type_of(ccx, t_out);
1886 // Convert the value to be cast into a ValueRef, either by-ref or
1887 // by-value as appropriate given its type:
1888 let mut datum = unpack_datum!(bcx, trans(bcx, expr));
1890 if cast_is_noop(datum.ty, t_out) {
1892 return DatumBlock::new(bcx, datum);
1895 let newval = match (k_in, k_out) {
1896 (cast_integral, cast_integral) => {
1897 let llexpr = datum.to_llscalarish(bcx);
1898 int_cast(bcx, ll_t_out, ll_t_in, llexpr, s_in)
1900 (cast_float, cast_float) => {
1901 let llexpr = datum.to_llscalarish(bcx);
1902 float_cast(bcx, ll_t_out, ll_t_in, llexpr)
1904 (cast_integral, cast_float) => {
1905 let llexpr = datum.to_llscalarish(bcx);
1907 SIToFP(bcx, llexpr, ll_t_out)
1908 } else { UIToFP(bcx, llexpr, ll_t_out) }
1910 (cast_float, cast_integral) => {
1911 let llexpr = datum.to_llscalarish(bcx);
1912 if ty::type_is_signed(t_out) {
1913 FPToSI(bcx, llexpr, ll_t_out)
1914 } else { FPToUI(bcx, llexpr, ll_t_out) }
1916 (cast_integral, cast_pointer) => {
1917 let llexpr = datum.to_llscalarish(bcx);
1918 IntToPtr(bcx, llexpr, ll_t_out)
1920 (cast_pointer, cast_integral) => {
1921 let llexpr = datum.to_llscalarish(bcx);
1922 PtrToInt(bcx, llexpr, ll_t_out)
1924 (cast_pointer, cast_pointer) => {
1925 let llexpr = datum.to_llscalarish(bcx);
1926 PointerCast(bcx, llexpr, ll_t_out)
1928 (cast_enum, cast_integral) |
1929 (cast_enum, cast_float) => {
1931 let repr = adt::represent_type(ccx, t_in);
1932 let datum = unpack_datum!(
1933 bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
1934 let llexpr_ptr = datum.to_llref();
1936 adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
1938 cast_integral => int_cast(bcx, ll_t_out,
1939 val_ty(lldiscrim_a),
1941 cast_float => SIToFP(bcx, lldiscrim_a, ll_t_out),
1943 ccx.sess().bug(format!("translating unsupported cast: \
1944 {} ({:?}) -> {} ({:?})",
1945 t_in.repr(bcx.tcx()),
1947 t_out.repr(bcx.tcx()),
1952 _ => ccx.sess().bug(format!("translating unsupported cast: \
1953 {} ({:?}) -> {} ({:?})",
1954 t_in.repr(bcx.tcx()),
1956 t_out.repr(bcx.tcx()),
1959 return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
1962 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1967 -> Block<'blk, 'tcx> {
1968 let _icx = push_ctxt("trans_assign_op");
1971 debug!("trans_assign_op(expr={})", bcx.expr_to_string(expr));
1973 // User-defined operator methods cannot be used with `+=` etc right now
1974 assert!(!bcx.tcx().method_map.borrow().contains_key(&MethodCall::expr(expr.id)));
1976 // Evaluate LHS (destination), which should be an lvalue
1977 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
1978 assert!(!ty::type_needs_drop(bcx.tcx(), dst_datum.ty));
1979 let dst_ty = dst_datum.ty;
1980 let dst = load_ty(bcx, dst_datum.val, dst_datum.ty);
1983 let rhs_datum = unpack_datum!(bcx, trans(bcx, &*src));
1984 let rhs_ty = rhs_datum.ty;
1985 let rhs = rhs_datum.to_llscalarish(bcx);
1987 // Perform computation and store the result
1988 let result_datum = unpack_datum!(
1989 bcx, trans_eager_binop(bcx, expr, dst_datum.ty, op,
1990 dst_ty, dst, rhs_ty, rhs));
1991 return result_datum.store_to(bcx, dst_datum.val);
1994 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1997 -> DatumBlock<'blk, 'tcx, Expr> {
2000 // Ensure cleanup of `datum` if not already scheduled and obtain
2001 // a "by ref" pointer.
2002 let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2004 // Compute final type. Note that we are loose with the region and
2005 // mutability, since those things don't matter in trans.
2006 let referent_ty = lv_datum.ty;
2007 let ptr_ty = ty::mk_imm_rptr(bcx.tcx(), ty::ReStatic, referent_ty);
2010 let llref = lv_datum.to_llref();
2012 // Construct the resulting datum, using what was the "by ref"
2013 // ValueRef of type `referent_ty` to be the "by value" ValueRef
2014 // of type `&referent_ty`.
2015 DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(ByValue))))
2018 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2022 -> DatumBlock<'blk, 'tcx, Expr> {
2024 let mut datum = datum;
2025 for i in range(0, times) {
2026 let method_call = MethodCall::autoderef(expr.id, i);
2027 datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2029 DatumBlock { bcx: bcx, datum: datum }
2032 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2035 method_call: MethodCall)
2036 -> DatumBlock<'blk, 'tcx, Expr> {
2037 let ccx = bcx.ccx();
2039 debug!("deref_once(expr={}, datum={}, method_call={})",
2040 expr.repr(bcx.tcx()),
2041 datum.to_string(ccx),
2046 // Check for overloaded deref.
2047 let method_ty = ccx.tcx().method_map.borrow()
2048 .find(&method_call).map(|method| method.ty);
2049 let datum = match method_ty {
2050 Some(method_ty) => {
2051 // Overloaded. Evaluate `trans_overloaded_op`, which will
2052 // invoke the user's deref() method, which basically
2053 // converts from the `Smaht<T>` pointer that we have into
2054 // a `&T` pointer. We can then proceed down the normal
2055 // path (below) to dereference that `&T`.
2056 let datum = match method_call.adjustment {
2057 // Always perform an AutoPtr when applying an overloaded auto-deref
2058 typeck::AutoDeref(_) => unpack_datum!(bcx, auto_ref(bcx, datum, expr)),
2062 let ref_ty = ty::ty_fn_ret(monomorphize_type(bcx, method_ty));
2063 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2065 unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2066 datum, None, Some(SaveIn(scratch.val))));
2067 scratch.to_expr_datum()
2070 // Not overloaded. We already have a pointer we know how to deref.
2075 let r = match ty::get(datum.ty).sty {
2076 ty::ty_uniq(content_ty) => {
2077 if ty::type_is_sized(bcx.tcx(), content_ty) {
2078 deref_owned_pointer(bcx, expr, datum, content_ty)
2080 // A fat pointer and an opened DST value have the same
2081 // represenation just different types. Since there is no
2082 // temporary for `*e` here (because it is unsized), we cannot
2083 // emulate the sized object code path for running drop glue and
2084 // free. Instead, we schedule cleanup for `e`, turning it into
2086 let datum = unpack_datum!(
2087 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2089 let datum = Datum::new(datum.val, ty::mk_open(bcx.tcx(), content_ty), LvalueExpr);
2090 DatumBlock::new(bcx, datum)
2094 ty::ty_box(content_ty) => {
2095 let datum = unpack_datum!(
2096 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2097 let llptrref = datum.to_llref();
2098 let llptr = Load(bcx, llptrref);
2099 let llbody = GEPi(bcx, llptr, [0u, abi::box_field_body]);
2100 DatumBlock::new(bcx, Datum::new(llbody, content_ty, LvalueExpr))
2103 ty::ty_ptr(ty::mt { ty: content_ty, .. }) |
2104 ty::ty_rptr(_, ty::mt { ty: content_ty, .. }) => {
2105 if ty::type_is_sized(bcx.tcx(), content_ty) {
2106 let ptr = datum.to_llscalarish(bcx);
2108 // Always generate an lvalue datum, even if datum.mode is
2109 // an rvalue. This is because datum.mode is only an
2110 // rvalue for non-owning pointers like &T or *T, in which
2111 // case cleanup *is* scheduled elsewhere, by the true
2112 // owner (or, in the case of *T, by the user).
2113 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr))
2115 // A fat pointer and an opened DST value have the same represenation
2116 // just different types.
2117 DatumBlock::new(bcx, Datum::new(datum.val,
2118 ty::mk_open(bcx.tcx(), content_ty),
2124 bcx.tcx().sess.span_bug(
2126 format!("deref invoked on expr of illegal type {}",
2127 datum.ty.repr(bcx.tcx())).as_slice());
2131 debug!("deref_once(expr={}, method_call={}, result={})",
2132 expr.id, method_call, r.datum.to_string(ccx));
2136 fn deref_owned_pointer<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2140 -> DatumBlock<'blk, 'tcx, Expr> {
2142 * We microoptimize derefs of owned pointers a bit here.
2143 * Basically, the idea is to make the deref of an rvalue
2144 * result in an rvalue. This helps to avoid intermediate stack
2145 * slots in the resulting LLVM. The idea here is that, if the
2146 * `Box<T>` pointer is an rvalue, then we can schedule a *shallow*
2147 * free of the `Box<T>` pointer, and then return a ByRef rvalue
2148 * into the pointer. Because the free is shallow, it is legit
2149 * to return an rvalue, because we know that the contents are
2150 * not yet scheduled to be freed. The language rules ensure that the
2151 * contents will be used (or moved) before the free occurs.
2155 RvalueExpr(Rvalue { mode: ByRef }) => {
2156 let scope = cleanup::temporary_scope(bcx.tcx(), expr.id);
2157 let ptr = Load(bcx, datum.val);
2158 if !type_is_zero_size(bcx.ccx(), content_ty) {
2159 bcx.fcx.schedule_free_value(scope, ptr, cleanup::HeapExchange, content_ty);
2162 RvalueExpr(Rvalue { mode: ByValue }) => {
2163 let scope = cleanup::temporary_scope(bcx.tcx(), expr.id);
2164 if !type_is_zero_size(bcx.ccx(), content_ty) {
2165 bcx.fcx.schedule_free_value(scope, datum.val, cleanup::HeapExchange,
2172 // If we had an rvalue in, we produce an rvalue out.
2173 let (llptr, kind) = match datum.kind {
2175 (Load(bcx, datum.val), LvalueExpr)
2177 RvalueExpr(Rvalue { mode: ByRef }) => {
2178 (Load(bcx, datum.val), RvalueExpr(Rvalue::new(ByRef)))
2180 RvalueExpr(Rvalue { mode: ByValue }) => {
2181 (datum.val, RvalueExpr(Rvalue::new(ByRef)))
2185 let datum = Datum { ty: content_ty, val: llptr, kind: kind };
2186 DatumBlock { bcx: bcx, datum: datum }