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.
11 //! # Translation of Expressions
13 //! Public entry points:
15 //! - `trans_into(bcx, expr, dest) -> bcx`: evaluates an expression,
16 //! storing the result into `dest`. This is the preferred form, if you
19 //! - `trans(bcx, expr) -> DatumBlock`: evaluates an expression, yielding
20 //! `Datum` with the result. You can then store the datum, inspect
21 //! the value, etc. This may introduce temporaries if the datum is a
24 //! - `trans_to_lvalue(bcx, expr, "...") -> DatumBlock`: evaluates an
25 //! expression and ensures that the result has a cleanup associated with it,
26 //! creating a temporary stack slot if necessary.
28 //! - `trans_local_var -> Datum`: looks up a local variable or upvar.
30 //! See doc.rs for more comments.
32 #![allow(non_camel_case_types)]
34 pub use self::cast_kind::*;
35 pub use self::Dest::*;
36 use self::lazy_binop_ty::*;
39 use llvm::{mod, ValueRef};
41 use middle::mem_categorization::Typer;
42 use middle::subst::{mod, Subst};
43 use trans::{_match, adt, asm, base, callee, closure, consts, controlflow};
46 use trans::cleanup::{mod, CleanupMethods};
56 use middle::ty::{struct_fields, tup_fields};
57 use middle::ty::{AdjustDerefRef, AdjustAddEnv, AutoUnsafe};
58 use middle::ty::{AutoPtr};
59 use middle::ty::{mod, Ty};
60 use middle::ty::MethodCall;
61 use util::common::indenter;
62 use util::ppaux::Repr;
63 use trans::machine::{llsize_of, llsize_of_alloc};
64 use trans::type_::Type;
66 use syntax::{ast, ast_util, codemap};
67 use syntax::print::pprust::{expr_to_string};
73 // These are passed around by the code generating functions to track the
74 // destination of a computation's value.
76 #[deriving(Copy, PartialEq)]
83 pub fn to_string(&self, ccx: &CrateContext) -> String {
85 SaveIn(v) => format!("SaveIn({})", ccx.tn().val_to_string(v)),
86 Ignore => "Ignore".to_string()
91 /// This function is equivalent to `trans(bcx, expr).store_to_dest(dest)` but it may generate
92 /// better optimized LLVM code.
93 pub fn trans_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
96 -> Block<'blk, 'tcx> {
99 if bcx.tcx().adjustments.borrow().contains_key(&expr.id) {
100 // use trans, which may be less efficient but
101 // which will perform the adjustments:
102 let datum = unpack_datum!(bcx, trans(bcx, expr));
103 return datum.store_to_dest(bcx, dest, expr.id)
106 debug!("trans_into() expr={}", expr.repr(bcx.tcx()));
108 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
112 bcx.fcx.push_ast_cleanup_scope(cleanup_debug_loc);
114 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
115 let kind = ty::expr_kind(bcx.tcx(), expr);
117 ty::LvalueExpr | ty::RvalueDatumExpr => {
118 trans_unadjusted(bcx, expr).store_to_dest(dest, expr.id)
120 ty::RvalueDpsExpr => {
121 trans_rvalue_dps_unadjusted(bcx, expr, dest)
123 ty::RvalueStmtExpr => {
124 trans_rvalue_stmt_unadjusted(bcx, expr)
128 bcx.fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id)
131 /// Translates an expression, returning a datum (and new block) encapsulating the result. When
132 /// possible, it is preferred to use `trans_into`, as that may avoid creating a temporary on the
134 pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
136 -> DatumBlock<'blk, 'tcx, Expr> {
137 debug!("trans(expr={})", bcx.expr_to_string(expr));
142 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
146 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
147 let datum = unpack_datum!(bcx, trans_unadjusted(bcx, expr));
148 let datum = unpack_datum!(bcx, apply_adjustments(bcx, expr, datum));
149 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id);
150 return DatumBlock::new(bcx, datum);
153 pub fn get_len(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
154 GEPi(bcx, fat_ptr, &[0u, abi::FAT_PTR_EXTRA])
157 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
158 GEPi(bcx, fat_ptr, &[0u, abi::FAT_PTR_ADDR])
161 /// Helper for trans that apply adjustments from `expr` to `datum`, which should be the unadjusted
162 /// translation of `expr`.
163 fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
165 datum: Datum<'tcx, Expr>)
166 -> DatumBlock<'blk, 'tcx, Expr> {
168 let mut datum = datum;
169 let adjustment = match bcx.tcx().adjustments.borrow().get(&expr.id).cloned() {
171 return DatumBlock::new(bcx, datum);
175 debug!("unadjusted datum for expr {}: {}, adjustment={}",
176 expr.repr(bcx.tcx()),
177 datum.to_string(bcx.ccx()),
178 adjustment.repr(bcx.tcx()));
180 AdjustAddEnv(..) => {
181 datum = unpack_datum!(bcx, add_env(bcx, expr, datum));
183 AdjustDerefRef(ref adj) => {
184 let (autoderefs, use_autoref) = match adj.autoref {
185 // Extracting a value from a box counts as a deref, but if we are
186 // just converting Box<[T, ..n]> to Box<[T]> we aren't really doing
187 // a deref (and wouldn't if we could treat Box like a normal struct).
188 Some(ty::AutoUnsizeUniq(..)) => (adj.autoderefs - 1, true),
189 // We are a bit paranoid about adjustments and thus might have a re-
190 // borrow here which merely derefs and then refs again (it might have
191 // a different region or mutability, but we don't care here. It might
192 // also be just in case we need to unsize. But if there are no nested
193 // adjustments then it should be a no-op).
194 Some(ty::AutoPtr(_, _, None)) if adj.autoderefs == 1 => {
196 // Don't skip a conversion from Box<T> to &T, etc.
198 let method_call = MethodCall::autoderef(expr.id, adj.autoderefs-1);
199 let method = bcx.tcx().method_map.borrow().get(&method_call).is_some();
201 // Don't skip an overloaded deref.
202 (adj.autoderefs, true)
204 (adj.autoderefs - 1, false)
207 _ => (adj.autoderefs, true),
210 _ => (adj.autoderefs, true)
215 let lval = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "auto_deref", expr.id));
216 datum = unpack_datum!(
217 bcx, deref_multiple(bcx, expr, lval.to_expr_datum(), autoderefs));
220 // (You might think there is a more elegant way to do this than a
221 // use_autoref bool, but then you remember that the borrow checker exists).
222 if let (true, &Some(ref a)) = (use_autoref, &adj.autoref) {
223 datum = unpack_datum!(bcx, apply_autoref(a,
230 debug!("after adjustments, datum={}", datum.to_string(bcx.ccx()));
231 return DatumBlock::new(bcx, datum);
233 fn apply_autoref<'blk, 'tcx>(autoref: &ty::AutoRef<'tcx>,
234 bcx: Block<'blk, 'tcx>,
236 datum: Datum<'tcx, Expr>)
237 -> DatumBlock<'blk, 'tcx, Expr> {
239 let mut datum = datum;
241 let datum = match autoref {
242 &AutoPtr(_, _, ref a) | &AutoUnsafe(_, ref a) => {
245 &Some(box ref a) => {
246 datum = unpack_datum!(bcx, apply_autoref(a, bcx, expr, datum));
250 unpack_datum!(bcx, ref_ptr(bcx, expr, datum))
252 &ty::AutoUnsize(ref k) => {
253 debug!(" AutoUnsize");
254 unpack_datum!(bcx, unsize_expr(bcx, expr, datum, k))
257 &ty::AutoUnsizeUniq(ty::UnsizeLength(len)) => {
258 debug!(" AutoUnsizeUniq(UnsizeLength)");
259 unpack_datum!(bcx, unsize_unique_vec(bcx, expr, datum, len))
261 &ty::AutoUnsizeUniq(ref k) => {
262 debug!(" AutoUnsizeUniq");
263 unpack_datum!(bcx, unsize_unique_expr(bcx, expr, datum, k))
267 DatumBlock::new(bcx, datum)
270 fn ref_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
272 datum: Datum<'tcx, Expr>)
273 -> DatumBlock<'blk, 'tcx, Expr> {
274 debug!("ref_ptr(expr={}, datum={})",
275 expr.repr(bcx.tcx()),
276 datum.to_string(bcx.ccx()));
278 if !ty::type_is_sized(bcx.tcx(), datum.ty) {
279 debug!("Taking address of unsized type {}",
280 bcx.ty_to_string(datum.ty));
281 ref_fat_ptr(bcx, expr, datum)
283 debug!("Taking address of sized type {}",
284 bcx.ty_to_string(datum.ty));
285 auto_ref(bcx, datum, expr)
289 // Retrieve the information we are losing (making dynamic) in an unsizing
291 // When making a dtor, we need to do different things depending on the
292 // ownership of the object.. mk_ty is a function for turning `unadjusted_ty`
293 // into a type to be destructed. If we want to end up with a Box pointer,
294 // then mk_ty should make a Box pointer (T -> Box<T>), if we want a
295 // borrowed reference then it should be T -> &T.
296 // FIXME(#19596) unbox `mk_ty`
297 fn unsized_info<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
298 kind: &ty::UnsizeKind<'tcx>,
300 unadjusted_ty: Ty<'tcx>,
301 mk_ty: |Ty<'tcx>| -> Ty<'tcx>) -> ValueRef {
302 debug!("unsized_info(kind={}, id={}, unadjusted_ty={})",
303 kind, id, unadjusted_ty.repr(bcx.tcx()));
305 &ty::UnsizeLength(len) => C_uint(bcx.ccx(), len),
306 &ty::UnsizeStruct(box ref k, tp_index) => match unadjusted_ty.sty {
307 ty::ty_struct(_, ref substs) => {
308 let ty_substs = substs.types.get_slice(subst::TypeSpace);
309 // The dtor for a field treats it like a value, so mk_ty
310 // should just be the identity function.
311 unsized_info(bcx, k, id, ty_substs[tp_index], |t| t)
313 _ => bcx.sess().bug(format!("UnsizeStruct with bad sty: {}",
314 bcx.ty_to_string(unadjusted_ty)).as_slice())
316 &ty::UnsizeVtable(ty::TyTrait { ref principal, .. }, _) => {
317 let substs = principal.substs().with_self_ty(unadjusted_ty).erase_regions();
319 Rc::new(ty::Binder(ty::TraitRef { def_id: principal.def_id(),
321 let trait_ref = trait_ref.subst(bcx.tcx(), bcx.fcx.param_substs);
322 let box_ty = mk_ty(unadjusted_ty);
324 meth::get_vtable(bcx, box_ty, trait_ref),
325 Type::vtable_ptr(bcx.ccx()))
330 fn unsize_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
332 datum: Datum<'tcx, Expr>,
333 k: &ty::UnsizeKind<'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 debug!("unsized_ty={}", unsized_ty.repr(bcx.tcx()));
339 let dest_ty = ty::mk_open(tcx, unsized_ty);
340 debug!("dest_ty={}", unsized_ty.repr(bcx.tcx()));
341 // Closures for extracting and manipulating the data and payload parts of
343 let info = |: bcx, _val| unsized_info(bcx,
351 mutbl: ast::MutImmutable
354 ty::UnsizeStruct(..) =>
355 into_fat_ptr(bcx, expr, datum, dest_ty, |bcx, val| {
356 PointerCast(bcx, val, type_of::type_of(bcx.ccx(), unsized_ty).ptr_to())
358 ty::UnsizeLength(..) =>
359 into_fat_ptr(bcx, expr, datum, dest_ty, |bcx, val| {
360 GEPi(bcx, val, &[0u, 0u])
362 ty::UnsizeVtable(..) =>
363 into_fat_ptr(bcx, expr, datum, dest_ty, |_bcx, val| {
364 PointerCast(bcx, val, Type::i8p(bcx.ccx()))
369 fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
371 datum: Datum<'tcx, Expr>)
372 -> DatumBlock<'blk, 'tcx, Expr> {
374 let dest_ty = ty::close_type(tcx, datum.ty);
375 let base = |: bcx, val| Load(bcx, get_dataptr(bcx, val));
376 let len = |: bcx, val| Load(bcx, get_len(bcx, val));
377 into_fat_ptr(bcx, expr, datum, dest_ty, base, len)
380 fn into_fat_ptr<'blk, 'tcx, F, G>(bcx: Block<'blk, 'tcx>,
382 datum: Datum<'tcx, Expr>,
386 -> DatumBlock<'blk, 'tcx, Expr> where
387 F: FnOnce(Block<'blk, 'tcx>, ValueRef) -> ValueRef,
388 G: FnOnce(Block<'blk, 'tcx>, ValueRef) -> ValueRef,
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>,
407 datum: Datum<'tcx, Expr>,
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>,
435 datum: Datum<'tcx, Expr>,
436 k: &ty::UnsizeKind<'tcx>)
437 -> DatumBlock<'blk, 'tcx, Expr> {
441 let datum_ty = datum.ty;
442 let unboxed_ty = match 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>,
470 datum: Datum<'tcx, Expr>)
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 /// Translates an expression in "lvalue" mode -- meaning that it returns a reference to the memory
486 /// that the expr represents.
488 /// If this expression is an rvalue, this implies introducing a temporary. In other words,
489 /// something like `x().f` is translated into roughly the equivalent of
491 /// { tmp = x(); tmp.f }
492 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
495 -> DatumBlock<'blk, 'tcx, Lvalue> {
497 let datum = unpack_datum!(bcx, trans(bcx, expr));
498 return datum.to_lvalue_datum(bcx, name, expr.id);
501 /// A version of `trans` that ignores adjustments. You almost certainly do not want to call this
503 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
505 -> DatumBlock<'blk, 'tcx, Expr> {
508 debug!("trans_unadjusted(expr={})", bcx.expr_to_string(expr));
509 let _indenter = indenter();
511 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
513 return match ty::expr_kind(bcx.tcx(), expr) {
514 ty::LvalueExpr | ty::RvalueDatumExpr => {
515 let datum = unpack_datum!(bcx, {
516 trans_datum_unadjusted(bcx, expr)
519 DatumBlock {bcx: bcx, datum: datum}
522 ty::RvalueStmtExpr => {
523 bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
524 nil(bcx, expr_ty(bcx, expr))
527 ty::RvalueDpsExpr => {
528 let ty = expr_ty(bcx, expr);
529 if type_is_zero_size(bcx.ccx(), ty) {
530 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
533 let scratch = rvalue_scratch_datum(bcx, ty, "");
534 bcx = trans_rvalue_dps_unadjusted(
535 bcx, expr, SaveIn(scratch.val));
537 // Note: this is not obviously a good idea. It causes
538 // immediate values to be loaded immediately after a
539 // return from a call or other similar expression,
540 // which in turn leads to alloca's having shorter
541 // lifetimes and hence larger stack frames. However,
542 // in turn it can lead to more register pressure.
543 // Still, in practice it seems to increase
544 // performance, since we have fewer problems with
546 let scratch = unpack_datum!(
547 bcx, scratch.to_appropriate_datum(bcx));
549 DatumBlock::new(bcx, scratch.to_expr_datum())
554 fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: Ty<'tcx>)
555 -> DatumBlock<'blk, 'tcx, Expr> {
556 let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
557 let datum = immediate_rvalue(llval, ty);
558 DatumBlock::new(bcx, datum.to_expr_datum())
562 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
564 -> DatumBlock<'blk, 'tcx, Expr> {
567 let _icx = push_ctxt("trans_datum_unadjusted");
570 ast::ExprParen(ref e) => {
573 ast::ExprPath(_) => {
574 trans_def(bcx, expr, bcx.def(expr.id))
576 ast::ExprField(ref base, ident) => {
577 trans_rec_field(bcx, &**base, ident.node)
579 ast::ExprTupField(ref base, idx) => {
580 trans_rec_tup_field(bcx, &**base, idx.node)
582 ast::ExprIndex(ref base, ref idx) => {
583 trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id))
585 ast::ExprSlice(ref base, ref start, ref end, _) => {
586 let _icx = push_ctxt("trans_slice");
589 let method_call = MethodCall::expr(expr.id);
590 let method_ty = ccx.tcx()
594 .map(|method| method.ty);
595 let base_datum = unpack_datum!(bcx, trans(bcx, &**base));
597 let mut args = vec![];
598 start.as_ref().map(|e| args.push((unpack_datum!(bcx, trans(bcx, &**e)), e.id)));
599 end.as_ref().map(|e| args.push((unpack_datum!(bcx, trans(bcx, &**e)), e.id)));
601 let result_ty = ty::ty_fn_ret(monomorphize_type(bcx, method_ty.unwrap())).unwrap();
602 let scratch = rvalue_scratch_datum(bcx, result_ty, "trans_slice");
605 trans_overloaded_op(bcx,
610 Some(SaveIn(scratch.val)),
612 DatumBlock::new(bcx, scratch.to_expr_datum())
614 ast::ExprBox(_, ref contents) => {
615 // Special case for `Box<T>`
616 let box_ty = expr_ty(bcx, expr);
617 let contents_ty = expr_ty(bcx, &**contents);
620 trans_uniq_expr(bcx, box_ty, &**contents, contents_ty)
622 _ => bcx.sess().span_bug(expr.span,
623 "expected unique box")
627 ast::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, &**lit),
628 ast::ExprBinary(op, ref lhs, ref rhs) => {
629 trans_binary(bcx, expr, op, &**lhs, &**rhs)
631 ast::ExprUnary(op, ref x) => {
632 trans_unary(bcx, expr, op, &**x)
634 ast::ExprAddrOf(_, ref x) => {
636 ast::ExprRepeat(..) | ast::ExprVec(..) => {
637 // Special case for slices.
638 let cleanup_debug_loc =
639 debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
643 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
644 let datum = unpack_datum!(
645 bcx, tvec::trans_slice_vec(bcx, expr, &**x));
646 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
647 DatumBlock::new(bcx, datum)
650 trans_addr_of(bcx, expr, &**x)
654 ast::ExprCast(ref val, _) => {
655 // Datum output mode means this is a scalar cast:
656 trans_imm_cast(bcx, &**val, expr.id)
659 bcx.tcx().sess.span_bug(
661 format!("trans_rvalue_datum_unadjusted reached \
662 fall-through case: {}",
663 expr.node).as_slice());
668 fn trans_field<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
671 -> DatumBlock<'blk, 'tcx, Expr> where
672 F: FnOnce(&'blk ty::ctxt<'tcx>, &[ty::field<'tcx>]) -> uint,
675 let _icx = push_ctxt("trans_rec_field");
677 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
678 let bare_ty = ty::unopen_type(base_datum.ty);
679 let repr = adt::represent_type(bcx.ccx(), bare_ty);
680 with_field_tys(bcx.tcx(), bare_ty, None, move |discr, field_tys| {
681 let ix = get_idx(bcx.tcx(), field_tys);
682 let d = base_datum.get_element(
685 |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, ix));
687 if ty::type_is_sized(bcx.tcx(), d.ty) {
688 DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
690 let scratch = rvalue_scratch_datum(bcx, ty::mk_open(bcx.tcx(), d.ty), "");
691 Store(bcx, d.val, get_dataptr(bcx, scratch.val));
692 let info = Load(bcx, get_len(bcx, base_datum.val));
693 Store(bcx, info, get_len(bcx, scratch.val));
695 DatumBlock::new(bcx, scratch.to_expr_datum())
702 /// Translates `base.field`.
703 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
706 -> DatumBlock<'blk, 'tcx, Expr> {
707 trans_field(bcx, base, |tcx, field_tys| ty::field_idx_strict(tcx, field.name, field_tys))
710 /// Translates `base.<idx>`.
711 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
714 -> DatumBlock<'blk, 'tcx, Expr> {
715 trans_field(bcx, base, |_, _| idx)
718 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
719 index_expr: &ast::Expr,
722 method_call: MethodCall)
723 -> DatumBlock<'blk, 'tcx, Expr> {
724 //! Translates `base[idx]`.
726 let _icx = push_ctxt("trans_index");
730 // Check for overloaded index.
731 let method_ty = ccx.tcx()
735 .map(|method| method.ty);
736 let elt_datum = match method_ty {
738 let base_datum = unpack_datum!(bcx, trans(bcx, base));
740 // Translate index expression.
741 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
743 let ref_ty = ty::ty_fn_ret(monomorphize_type(bcx, method_ty)).unwrap();
744 let elt_ty = match ty::deref(ref_ty, true) {
746 bcx.tcx().sess.span_bug(index_expr.span,
747 "index method didn't return a \
748 dereferenceable type?!")
750 Some(elt_tm) => elt_tm.ty,
753 // Overloaded. Evaluate `trans_overloaded_op`, which will
754 // invoke the user's index() method, which basically yields
755 // a `&T` pointer. We can then proceed down the normal
756 // path (below) to dereference that `&T`.
757 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_index_elt");
759 trans_overloaded_op(bcx,
763 vec![(ix_datum, idx.id)],
764 Some(SaveIn(scratch.val)),
766 let datum = scratch.to_expr_datum();
767 if ty::type_is_sized(bcx.tcx(), elt_ty) {
768 Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr)
770 Datum::new(datum.val, ty::mk_open(bcx.tcx(), elt_ty), LvalueExpr)
774 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
778 // Translate index expression and cast to a suitable LLVM integer.
779 // Rust is less strict than LLVM in this regard.
780 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
781 let ix_val = ix_datum.to_llscalarish(bcx);
782 let ix_size = machine::llbitsize_of_real(bcx.ccx(),
784 let int_size = machine::llbitsize_of_real(bcx.ccx(),
787 if ix_size < int_size {
788 if ty::type_is_signed(expr_ty(bcx, idx)) {
789 SExt(bcx, ix_val, ccx.int_type())
790 } else { ZExt(bcx, ix_val, ccx.int_type()) }
791 } else if ix_size > int_size {
792 Trunc(bcx, ix_val, ccx.int_type())
800 ty::sequence_element_type(bcx.tcx(),
802 base::maybe_name_value(bcx.ccx(), vt.llunit_size, "unit_sz");
804 let (base, len) = base_datum.get_vec_base_and_len(bcx);
806 debug!("trans_index: base {}", bcx.val_to_string(base));
807 debug!("trans_index: len {}", bcx.val_to_string(len));
809 let bounds_check = ICmp(bcx, llvm::IntUGE, ix_val, len);
810 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
811 let expected = Call(bcx,
813 &[bounds_check, C_bool(ccx, false)],
815 bcx = with_cond(bcx, expected, |bcx| {
816 controlflow::trans_fail_bounds_check(bcx,
821 let elt = InBoundsGEP(bcx, base, &[ix_val]);
822 let elt = PointerCast(bcx, elt, vt.llunit_ty.ptr_to());
823 Datum::new(elt, vt.unit_ty, LvalueExpr)
827 DatumBlock::new(bcx, elt_datum)
830 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
831 ref_expr: &ast::Expr,
833 -> DatumBlock<'blk, 'tcx, Expr> {
834 //! Translates a reference to a path.
836 let _icx = push_ctxt("trans_def_lvalue");
838 def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) |
839 def::DefStruct(_) | def::DefVariant(..) => {
840 trans_def_fn_unadjusted(bcx, ref_expr, def)
842 def::DefStatic(did, _) => {
843 // There are two things that may happen here:
844 // 1) If the static item is defined in this crate, it will be
845 // translated using `get_item_val`, and we return a pointer to
847 // 2) If the static item is defined in another crate then we add
848 // (or reuse) a declaration of an external global, and return a
850 let const_ty = expr_ty(bcx, ref_expr);
852 fn get_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, did: ast::DefId,
853 const_ty: Ty<'tcx>) -> ValueRef {
854 // For external constants, we don't inline.
855 if did.krate == ast::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 base::get_extern_const(bcx.ccx(), did, const_ty)
869 let val = get_val(bcx, did, const_ty);
870 DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr))
872 def::DefConst(did) => {
873 // First, inline any external constants into the local crate so we
874 // can be sure to get the LLVM value corresponding to it.
875 let did = inline::maybe_instantiate_inline(bcx.ccx(), did);
876 if did.krate != ast::LOCAL_CRATE {
877 bcx.tcx().sess.span_bug(ref_expr.span,
878 "cross crate constant could not \
881 let val = base::get_item_val(bcx.ccx(), did.node);
883 // Next, we need to crate a ByRef rvalue datum to return. We can't
884 // use the normal .to_ref_datum() function because the type of
885 // `val` is not actually the same as `const_ty`.
887 // To get around this, we make a custom alloca slot with the
888 // appropriate type (const_ty), and then we cast it to a pointer of
889 // typeof(val), store the value, and then hand this slot over to
890 // the datum infrastructure.
891 let const_ty = expr_ty(bcx, ref_expr);
892 let llty = type_of::type_of(bcx.ccx(), const_ty);
893 let slot = alloca(bcx, llty, "const");
894 let pty = Type::from_ref(unsafe { llvm::LLVMTypeOf(val) }).ptr_to();
895 Store(bcx, val, PointerCast(bcx, slot, pty));
897 let datum = Datum::new(slot, const_ty, Rvalue::new(ByRef));
898 DatumBlock::new(bcx, datum.to_expr_datum())
901 DatumBlock::new(bcx, trans_local_var(bcx, def).to_expr_datum())
906 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
908 -> Block<'blk, 'tcx> {
910 let _icx = push_ctxt("trans_rvalue_stmt");
912 if bcx.unreachable.get() {
916 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
919 ast::ExprParen(ref e) => {
920 trans_into(bcx, &**e, Ignore)
922 ast::ExprBreak(label_opt) => {
923 controlflow::trans_break(bcx, expr.id, label_opt)
925 ast::ExprAgain(label_opt) => {
926 controlflow::trans_cont(bcx, expr.id, label_opt)
928 ast::ExprRet(ref ex) => {
929 controlflow::trans_ret(bcx, ex.as_ref().map(|e| &**e))
931 ast::ExprWhile(ref cond, ref body, _) => {
932 controlflow::trans_while(bcx, expr.id, &**cond, &**body)
934 ast::ExprForLoop(ref pat, ref head, ref body, _) => {
935 controlflow::trans_for(bcx,
941 ast::ExprLoop(ref body, _) => {
942 controlflow::trans_loop(bcx, expr.id, &**body)
944 ast::ExprAssign(ref dst, ref src) => {
945 let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
946 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
948 if ty::type_needs_drop(bcx.tcx(), dst_datum.ty) {
949 // If there are destructors involved, make sure we
950 // are copying from an rvalue, since that cannot possible
951 // alias an lvalue. We are concerned about code like:
959 // where e.g. a : Option<Foo> and a.b :
960 // Option<Foo>. In that case, freeing `a` before the
961 // assignment may also free `a.b`!
963 // We could avoid this intermediary with some analysis
964 // to determine whether `dst` may possibly own `src`.
965 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
966 let src_datum = unpack_datum!(
967 bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
968 bcx = glue::drop_ty(bcx,
971 Some(NodeInfo { id: expr.id, span: expr.span }));
972 src_datum.store_to(bcx, dst_datum.val)
974 src_datum.store_to(bcx, dst_datum.val)
977 ast::ExprAssignOp(op, ref dst, ref src) => {
978 trans_assign_op(bcx, expr, op, &**dst, &**src)
980 ast::ExprInlineAsm(ref a) => {
981 asm::trans_inline_asm(bcx, a)
984 bcx.tcx().sess.span_bug(
986 format!("trans_rvalue_stmt_unadjusted reached \
987 fall-through case: {}",
988 expr.node).as_slice());
993 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
996 -> Block<'blk, 'tcx> {
997 let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
1001 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
1004 ast::ExprParen(ref e) => {
1005 trans_into(bcx, &**e, dest)
1007 ast::ExprPath(_) => {
1008 trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
1010 ast::ExprIf(ref cond, ref thn, ref els) => {
1011 controlflow::trans_if(bcx, expr.id, &**cond, &**thn, els.as_ref().map(|e| &**e), dest)
1013 ast::ExprMatch(ref discr, ref arms, _) => {
1014 _match::trans_match(bcx, expr, &**discr, arms.as_slice(), dest)
1016 ast::ExprBlock(ref blk) => {
1017 controlflow::trans_block(bcx, &**blk, dest)
1019 ast::ExprStruct(_, ref fields, ref base) => {
1022 base.as_ref().map(|e| &**e),
1027 ast::ExprTup(ref args) => {
1028 let numbered_fields: Vec<(uint, &ast::Expr)> =
1029 args.iter().enumerate().map(|(i, arg)| (i, &**arg)).collect();
1033 numbered_fields.as_slice(),
1036 Some(NodeInfo { id: expr.id, span: expr.span }))
1038 ast::ExprLit(ref lit) => {
1040 ast::LitStr(ref s, _) => {
1041 tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1046 .span_bug(expr.span,
1047 "trans_rvalue_dps_unadjusted shouldn't be \
1048 translating this type of literal")
1052 ast::ExprVec(..) | ast::ExprRepeat(..) => {
1053 tvec::trans_fixed_vstore(bcx, expr, dest)
1055 ast::ExprClosure(_, _, ref decl, ref body) => {
1056 // Check the side-table to see whether this is an unboxed
1057 // closure or an older, legacy style closure. Store this
1058 // into a variable to ensure the the RefCell-lock is
1059 // released before we recurse.
1060 let is_unboxed_closure =
1061 bcx.tcx().unboxed_closures.borrow().contains_key(&ast_util::local_def(expr.id));
1062 if is_unboxed_closure {
1063 closure::trans_unboxed_closure(bcx, &**decl, &**body, expr.id, dest)
1065 let expr_ty = expr_ty(bcx, expr);
1066 let store = ty::ty_closure_store(expr_ty);
1067 debug!("translating block function {} with type {}",
1068 expr_to_string(expr), expr_ty.repr(tcx));
1069 closure::trans_expr_fn(bcx, store, &**decl, &**body, expr.id, dest)
1072 ast::ExprCall(ref f, ref args) => {
1073 if bcx.tcx().is_method_call(expr.id) {
1074 trans_overloaded_call(bcx,
1080 callee::trans_call(bcx,
1083 callee::ArgExprs(args.as_slice()),
1087 ast::ExprMethodCall(_, _, ref args) => {
1088 callee::trans_method_call(bcx,
1091 callee::ArgExprs(args.as_slice()),
1094 ast::ExprBinary(op, ref lhs, ref rhs) => {
1095 // if not overloaded, would be RvalueDatumExpr
1096 let lhs = unpack_datum!(bcx, trans(bcx, &**lhs));
1097 let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs));
1098 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs,
1099 vec![(rhs_datum, rhs.id)], Some(dest),
1100 !ast_util::is_by_value_binop(op)).bcx
1102 ast::ExprUnary(op, ref subexpr) => {
1103 // if not overloaded, would be RvalueDatumExpr
1104 let arg = unpack_datum!(bcx, trans(bcx, &**subexpr));
1105 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id),
1106 arg, Vec::new(), Some(dest), !ast_util::is_by_value_unop(op)).bcx
1108 ast::ExprIndex(ref base, ref idx) => {
1109 // if not overloaded, would be RvalueDatumExpr
1110 let base = unpack_datum!(bcx, trans(bcx, &**base));
1111 let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx));
1112 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
1113 vec![(idx_datum, idx.id)], Some(dest), true).bcx
1115 ast::ExprCast(ref val, _) => {
1116 // DPS output mode means this is a trait cast:
1117 if ty::type_is_trait(node_id_type(bcx, expr.id)) {
1119 bcx.tcx().object_cast_map.borrow()
1121 .map(|t| (*t).clone())
1123 let trait_ref = trait_ref.subst(bcx.tcx(), bcx.fcx.param_substs);
1124 let datum = unpack_datum!(bcx, trans(bcx, &**val));
1125 meth::trans_trait_cast(bcx, datum, expr.id,
1128 bcx.tcx().sess.span_bug(expr.span,
1129 "expr_cast of non-trait");
1132 ast::ExprAssignOp(op, ref dst, ref src) => {
1133 trans_assign_op(bcx, expr, op, &**dst, &**src)
1136 bcx.tcx().sess.span_bug(
1138 format!("trans_rvalue_dps_unadjusted reached fall-through \
1140 expr.node).as_slice());
1145 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1146 ref_expr: &ast::Expr,
1149 -> Block<'blk, 'tcx> {
1150 let _icx = push_ctxt("trans_def_dps_unadjusted");
1152 let lldest = match dest {
1153 SaveIn(lldest) => lldest,
1154 Ignore => { return bcx; }
1158 def::DefVariant(tid, vid, _) => {
1159 let variant_info = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
1160 if variant_info.args.len() > 0u {
1162 let llfn = callee::trans_fn_ref(bcx, vid, ExprId(ref_expr.id));
1163 Store(bcx, llfn, lldest);
1167 let ty = expr_ty(bcx, ref_expr);
1168 let repr = adt::represent_type(bcx.ccx(), ty);
1169 adt::trans_set_discr(bcx, &*repr, lldest,
1170 variant_info.disr_val);
1174 def::DefStruct(_) => {
1175 let ty = expr_ty(bcx, ref_expr);
1177 ty::ty_struct(did, _) if ty::has_dtor(bcx.tcx(), did) => {
1178 let repr = adt::represent_type(bcx.ccx(), ty);
1179 adt::trans_set_discr(bcx, &*repr, lldest, 0);
1186 bcx.tcx().sess.span_bug(ref_expr.span, format!(
1187 "Non-DPS def {} referened by {}",
1188 def, bcx.node_id_to_string(ref_expr.id)).as_slice());
1193 fn trans_def_fn_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1194 ref_expr: &ast::Expr,
1196 -> DatumBlock<'blk, 'tcx, Expr> {
1197 let _icx = push_ctxt("trans_def_datum_unadjusted");
1199 let llfn = match def {
1200 def::DefFn(did, _) |
1201 def::DefStruct(did) | def::DefVariant(_, did, _) |
1202 def::DefStaticMethod(did, def::FromImpl(_)) |
1203 def::DefMethod(did, _, def::FromImpl(_)) => {
1204 callee::trans_fn_ref(bcx, did, ExprId(ref_expr.id))
1206 def::DefStaticMethod(impl_did, def::FromTrait(trait_did)) |
1207 def::DefMethod(impl_did, _, def::FromTrait(trait_did)) => {
1208 meth::trans_static_method_callee(bcx, impl_did,
1209 trait_did, ref_expr.id)
1212 bcx.tcx().sess.span_bug(ref_expr.span, format!(
1213 "trans_def_fn_unadjusted invoked on: {} for {}",
1215 ref_expr.repr(bcx.tcx())).as_slice());
1219 let fn_ty = expr_ty(bcx, ref_expr);
1220 DatumBlock::new(bcx, Datum::new(llfn, fn_ty, RvalueExpr(Rvalue::new(ByValue))))
1223 /// Translates a reference to a local variable or argument. This always results in an lvalue datum.
1224 pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1226 -> Datum<'tcx, Lvalue> {
1227 let _icx = push_ctxt("trans_local_var");
1230 def::DefUpvar(nid, _, _) => {
1231 // Can't move upvars, so this is never a ZeroMemLastUse.
1232 let local_ty = node_id_type(bcx, nid);
1233 match bcx.fcx.llupvars.borrow().get(&nid) {
1234 Some(&val) => Datum::new(val, local_ty, Lvalue),
1236 bcx.sess().bug(format!(
1237 "trans_local_var: no llval for upvar {} found",
1242 def::DefLocal(nid) => {
1243 let datum = match bcx.fcx.lllocals.borrow().get(&nid) {
1246 bcx.sess().bug(format!(
1247 "trans_local_var: no datum for local/arg {} found",
1251 debug!("take_local(nid={}, v={}, ty={})",
1252 nid, bcx.val_to_string(datum.val), bcx.ty_to_string(datum.ty));
1256 bcx.sess().unimpl(format!(
1257 "unsupported def type in trans_local_var: {}",
1263 /// Helper for enumerating the field types of structs, enums, or records. The optional node ID here
1264 /// is the node ID of the path identifying the enum variant in use. If none, this cannot possibly
1265 /// an enum variant (so, if it is and `node_id_opt` is none, this function panics).
1266 pub fn with_field_tys<'tcx, R, F>(tcx: &ty::ctxt<'tcx>,
1268 node_id_opt: Option<ast::NodeId>,
1271 F: FnOnce(ty::Disr, &[ty::field<'tcx>]) -> R,
1274 ty::ty_struct(did, ref substs) => {
1275 op(0, struct_fields(tcx, did, substs).as_slice())
1278 ty::ty_tup(ref v) => {
1279 op(0, tup_fields(v.as_slice()).as_slice())
1282 ty::ty_enum(_, ref substs) => {
1283 // We want the *variant* ID here, not the enum ID.
1286 tcx.sess.bug(format!(
1287 "cannot get field types from the enum type {} \
1289 ty.repr(tcx)).as_slice());
1292 let def = tcx.def_map.borrow()[node_id].clone();
1294 def::DefVariant(enum_id, variant_id, _) => {
1295 let variant_info = ty::enum_variant_with_id(
1296 tcx, enum_id, variant_id);
1297 op(variant_info.disr_val,
1303 tcx.sess.bug("resolve didn't map this expr to a \
1312 tcx.sess.bug(format!(
1313 "cannot get field types from the type {}",
1314 ty.repr(tcx)).as_slice());
1319 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1320 fields: &[ast::Field],
1321 base: Option<&ast::Expr>,
1322 expr_span: codemap::Span,
1323 expr_id: ast::NodeId,
1324 dest: Dest) -> Block<'blk, 'tcx> {
1325 let _icx = push_ctxt("trans_rec");
1327 let ty = node_id_type(bcx, expr_id);
1328 let tcx = bcx.tcx();
1329 with_field_tys(tcx, ty, Some(expr_id), |discr, field_tys| {
1330 let mut need_base = Vec::from_elem(field_tys.len(), true);
1332 let numbered_fields = fields.iter().map(|field| {
1334 field_tys.iter().position(|field_ty|
1335 field_ty.name == field.ident.node.name);
1338 need_base[i] = false;
1342 tcx.sess.span_bug(field.span,
1343 "Couldn't find field in struct type")
1346 }).collect::<Vec<_>>();
1347 let optbase = match base {
1348 Some(base_expr) => {
1349 let mut leftovers = Vec::new();
1350 for (i, b) in need_base.iter().enumerate() {
1352 leftovers.push((i, field_tys[i].mt.ty))
1355 Some(StructBaseInfo {expr: base_expr,
1356 fields: leftovers })
1359 if need_base.iter().any(|b| *b) {
1360 tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1369 numbered_fields.as_slice(),
1372 Some(NodeInfo { id: expr_id, span: expr_span }))
1376 /// Information that `trans_adt` needs in order to fill in the fields
1377 /// of a struct copied from a base struct (e.g., from an expression
1378 /// like `Foo { a: b, ..base }`.
1380 /// Note that `fields` may be empty; the base expression must always be
1381 /// evaluated for side-effects.
1382 pub struct StructBaseInfo<'a, 'tcx> {
1383 /// The base expression; will be evaluated after all explicit fields.
1384 expr: &'a ast::Expr,
1385 /// The indices of fields to copy paired with their types.
1386 fields: Vec<(uint, Ty<'tcx>)>
1389 /// Constructs an ADT instance:
1391 /// - `fields` should be a list of field indices paired with the
1392 /// expression to store into that field. The initializers will be
1393 /// evaluated in the order specified by `fields`.
1395 /// - `optbase` contains information on the base struct (if any) from
1396 /// which remaining fields are copied; see comments on `StructBaseInfo`.
1397 pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1400 fields: &[(uint, &ast::Expr)],
1401 optbase: Option<StructBaseInfo<'a, 'tcx>>,
1403 source_location: Option<NodeInfo>)
1404 -> Block<'blk, 'tcx> {
1405 let _icx = push_ctxt("trans_adt");
1407 let repr = adt::represent_type(bcx.ccx(), ty);
1409 match source_location {
1410 Some(src_loc) => debuginfo::set_source_location(bcx.fcx,
1416 // If we don't care about the result, just make a
1417 // temporary stack slot
1418 let addr = match dest {
1420 Ignore => alloc_ty(bcx, ty, "temp"),
1423 // This scope holds intermediates that must be cleaned should
1424 // panic occur before the ADT as a whole is ready.
1425 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1427 // First we trans the base, if we have one, to the dest
1428 for base in optbase.iter() {
1429 assert_eq!(discr, 0);
1431 match ty::expr_kind(bcx.tcx(), &*base.expr) {
1432 ty::RvalueDpsExpr | ty::RvalueDatumExpr if !ty::type_needs_drop(bcx.tcx(), ty) => {
1433 bcx = trans_into(bcx, &*base.expr, SaveIn(addr));
1435 ty::RvalueStmtExpr => bcx.tcx().sess.bug("unexpected expr kind for struct base expr"),
1437 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base"));
1438 for &(i, t) in base.fields.iter() {
1439 let datum = base_datum.get_element(
1440 bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i));
1441 assert!(ty::type_is_sized(bcx.tcx(), datum.ty));
1442 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1443 bcx = datum.store_to(bcx, dest);
1449 match source_location {
1450 Some(src_loc) => debuginfo::set_source_location(bcx.fcx,
1456 if ty::type_is_simd(bcx.tcx(), ty) {
1457 // This is the constructor of a SIMD type, such types are
1458 // always primitive machine types and so do not have a
1459 // destructor or require any clean-up.
1460 let llty = type_of::type_of(bcx.ccx(), ty);
1462 // keep a vector as a register, and running through the field
1463 // `insertelement`ing them directly into that register
1464 // (i.e. avoid GEPi and `store`s to an alloca) .
1465 let mut vec_val = C_undef(llty);
1467 for &(i, ref e) in fields.iter() {
1468 let block_datum = trans(bcx, &**e);
1469 bcx = block_datum.bcx;
1470 let position = C_uint(bcx.ccx(), i);
1471 let value = block_datum.datum.to_llscalarish(bcx);
1472 vec_val = InsertElement(bcx, vec_val, value, position);
1474 Store(bcx, vec_val, addr);
1476 // Now, we just overwrite the fields we've explicitly specified
1477 for &(i, ref e) in fields.iter() {
1478 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1479 let e_ty = expr_ty_adjusted(bcx, &**e);
1480 bcx = trans_into(bcx, &**e, SaveIn(dest));
1481 let scope = cleanup::CustomScope(custom_cleanup_scope);
1482 fcx.schedule_lifetime_end(scope, dest);
1483 fcx.schedule_drop_mem(scope, dest, e_ty);
1487 adt::trans_set_discr(bcx, &*repr, addr, discr);
1489 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1491 // If we don't care about the result drop the temporary we made
1495 bcx = glue::drop_ty(bcx, addr, ty, source_location);
1496 base::call_lifetime_end(bcx, addr);
1503 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1506 -> DatumBlock<'blk, 'tcx, Expr> {
1507 // must not be a string constant, that is a RvalueDpsExpr
1508 let _icx = push_ctxt("trans_immediate_lit");
1509 let ty = expr_ty(bcx, expr);
1510 let v = consts::const_lit(bcx.ccx(), expr, lit);
1511 immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1514 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1517 sub_expr: &ast::Expr)
1518 -> DatumBlock<'blk, 'tcx, Expr> {
1519 let ccx = bcx.ccx();
1521 let _icx = push_ctxt("trans_unary_datum");
1523 let method_call = MethodCall::expr(expr.id);
1525 // The only overloaded operator that is translated to a datum
1526 // is an overloaded deref, since it is always yields a `&T`.
1527 // Otherwise, we should be in the RvalueDpsExpr path.
1529 op == ast::UnDeref ||
1530 !ccx.tcx().method_map.borrow().contains_key(&method_call));
1532 let un_ty = expr_ty(bcx, expr);
1536 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1537 let llresult = Not(bcx, datum.to_llscalarish(bcx));
1538 immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1541 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1542 let val = datum.to_llscalarish(bcx);
1544 if ty::type_is_fp(un_ty) {
1550 immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1553 trans_uniq_expr(bcx, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1556 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1557 deref_once(bcx, expr, datum, method_call)
1562 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1564 contents: &ast::Expr,
1565 contents_ty: Ty<'tcx>)
1566 -> DatumBlock<'blk, 'tcx, Expr> {
1567 let _icx = push_ctxt("trans_uniq_expr");
1569 assert!(ty::type_is_sized(bcx.tcx(), contents_ty));
1570 let llty = type_of::type_of(bcx.ccx(), contents_ty);
1571 let size = llsize_of(bcx.ccx(), llty);
1572 let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty));
1573 let llty_ptr = llty.ptr_to();
1574 let Result { bcx, val } = malloc_raw_dyn(bcx, llty_ptr, box_ty, size, align);
1575 // Unique boxes do not allocate for zero-size types. The standard library
1576 // may assume that `free` is never called on the pointer returned for
1577 // `Box<ZeroSizeType>`.
1578 let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1579 trans_into(bcx, contents, SaveIn(val))
1581 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1582 fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1583 val, cleanup::HeapExchange, contents_ty);
1584 let bcx = trans_into(bcx, contents, SaveIn(val));
1585 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1588 immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1591 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1593 subexpr: &ast::Expr)
1594 -> DatumBlock<'blk, 'tcx, Expr> {
1595 let _icx = push_ctxt("trans_addr_of");
1597 let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1598 match sub_datum.ty.sty {
1600 // Opened DST value, close to a fat pointer
1601 debug!("Closing fat pointer {}", bcx.ty_to_string(sub_datum.ty));
1603 let scratch = rvalue_scratch_datum(bcx,
1604 ty::close_type(bcx.tcx(), sub_datum.ty),
1606 let base = Load(bcx, get_dataptr(bcx, sub_datum.val));
1607 Store(bcx, base, get_dataptr(bcx, scratch.val));
1609 let len = Load(bcx, get_len(bcx, sub_datum.val));
1610 Store(bcx, len, get_len(bcx, scratch.val));
1612 DatumBlock::new(bcx, scratch.to_expr_datum())
1615 // Sized value, ref to a thin pointer
1616 let ty = expr_ty(bcx, expr);
1617 immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1622 // Important to get types for both lhs and rhs, because one might be _|_
1623 // and the other not.
1624 fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1625 binop_expr: &ast::Expr,
1632 -> DatumBlock<'blk, 'tcx, Expr> {
1633 let _icx = push_ctxt("trans_eager_binop");
1635 let tcx = bcx.tcx();
1636 let is_simd = ty::type_is_simd(tcx, lhs_t);
1638 if is_simd { ty::simd_type(tcx, lhs_t) }
1641 let is_float = ty::type_is_fp(intype);
1642 let is_signed = ty::type_is_signed(intype);
1644 let rhs = base::cast_shift_expr_rhs(bcx, op, lhs, rhs);
1647 let val = match op {
1649 if is_float { FAdd(bcx, lhs, rhs) }
1650 else { Add(bcx, lhs, rhs) }
1653 if is_float { FSub(bcx, lhs, rhs) }
1654 else { Sub(bcx, lhs, rhs) }
1657 if is_float { FMul(bcx, lhs, rhs) }
1658 else { Mul(bcx, lhs, rhs) }
1664 // Only zero-check integers; fp /0 is NaN
1665 bcx = base::fail_if_zero_or_overflows(bcx, binop_expr.span,
1666 op, lhs, rhs, rhs_t);
1678 // Only zero-check integers; fp %0 is NaN
1679 bcx = base::fail_if_zero_or_overflows(bcx, binop_expr.span,
1680 op, lhs, rhs, rhs_t);
1688 ast::BiBitOr => Or(bcx, lhs, rhs),
1689 ast::BiBitAnd => And(bcx, lhs, rhs),
1690 ast::BiBitXor => Xor(bcx, lhs, rhs),
1691 ast::BiShl => Shl(bcx, lhs, rhs),
1695 } else { LShr(bcx, lhs, rhs) }
1697 ast::BiEq | ast::BiNe | ast::BiLt | ast::BiGe | ast::BiLe | ast::BiGt => {
1698 if ty::type_is_scalar(rhs_t) {
1699 unpack_result!(bcx, base::compare_scalar_types(bcx, lhs, rhs, rhs_t, op))
1701 base::compare_simd_types(bcx, lhs, rhs, intype, ty::simd_size(tcx, lhs_t), op)
1703 bcx.tcx().sess.span_bug(binop_expr.span, "comparison operator unsupported for type")
1707 bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1711 immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1714 // refinement types would obviate the need for this
1715 enum lazy_binop_ty {
1720 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1721 binop_expr: &ast::Expr,
1725 -> DatumBlock<'blk, 'tcx, Expr> {
1726 let _icx = push_ctxt("trans_lazy_binop");
1727 let binop_ty = expr_ty(bcx, binop_expr);
1730 let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1731 let lhs = lhs.to_llscalarish(past_lhs);
1733 if past_lhs.unreachable.get() {
1734 return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1737 let join = fcx.new_id_block("join", binop_expr.id);
1738 let before_rhs = fcx.new_id_block("before_rhs", b.id);
1741 lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb),
1742 lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb)
1745 let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1746 let rhs = rhs.to_llscalarish(past_rhs);
1748 if past_rhs.unreachable.get() {
1749 return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1752 Br(past_rhs, join.llbb);
1753 let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1754 &[past_lhs.llbb, past_rhs.llbb]);
1756 return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1759 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1764 -> DatumBlock<'blk, 'tcx, Expr> {
1765 let _icx = push_ctxt("trans_binary");
1766 let ccx = bcx.ccx();
1768 // if overloaded, would be RvalueDpsExpr
1769 assert!(!ccx.tcx().method_map.borrow().contains_key(&MethodCall::expr(expr.id)));
1773 trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1776 trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1780 let lhs_datum = unpack_datum!(bcx, trans(bcx, lhs));
1781 let rhs_datum = unpack_datum!(bcx, trans(bcx, rhs));
1782 let binop_ty = expr_ty(bcx, expr);
1784 debug!("trans_binary (expr {}): lhs_datum={}",
1786 lhs_datum.to_string(ccx));
1787 let lhs_ty = lhs_datum.ty;
1788 let lhs = lhs_datum.to_llscalarish(bcx);
1790 debug!("trans_binary (expr {}): rhs_datum={}",
1792 rhs_datum.to_string(ccx));
1793 let rhs_ty = rhs_datum.ty;
1794 let rhs = rhs_datum.to_llscalarish(bcx);
1795 trans_eager_binop(bcx, expr, binop_ty, op,
1796 lhs_ty, lhs, rhs_ty, rhs)
1801 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1803 method_call: MethodCall,
1804 lhs: Datum<'tcx, Expr>,
1805 rhs: Vec<(Datum<'tcx, Expr>, ast::NodeId)>,
1808 -> Result<'blk, 'tcx> {
1809 let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
1810 callee::trans_call_inner(bcx,
1811 Some(expr_info(expr)),
1812 monomorphize_type(bcx, method_ty),
1813 |bcx, arg_cleanup_scope| {
1814 meth::trans_method_callee(bcx,
1819 callee::ArgOverloadedOp(lhs, rhs, autoref),
1823 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1825 callee: &'a ast::Expr,
1826 args: &'a [P<ast::Expr>],
1828 -> Block<'blk, 'tcx> {
1829 let method_call = MethodCall::expr(expr.id);
1830 let method_type = (*bcx.tcx()
1832 .borrow())[method_call]
1834 let mut all_args = vec!(callee);
1835 all_args.extend(args.iter().map(|e| &**e));
1837 callee::trans_call_inner(bcx,
1838 Some(expr_info(expr)),
1839 monomorphize_type(bcx,
1841 |bcx, arg_cleanup_scope| {
1842 meth::trans_method_callee(
1848 callee::ArgOverloadedCall(all_args),
1853 fn int_cast(bcx: Block,
1859 let _icx = push_ctxt("int_cast");
1861 let srcsz = llvm::LLVMGetIntTypeWidth(llsrctype.to_ref());
1862 let dstsz = llvm::LLVMGetIntTypeWidth(lldsttype.to_ref());
1863 return if dstsz == srcsz {
1864 BitCast(bcx, llsrc, lldsttype)
1865 } else if srcsz > dstsz {
1866 TruncOrBitCast(bcx, llsrc, lldsttype)
1868 SExtOrBitCast(bcx, llsrc, lldsttype)
1870 ZExtOrBitCast(bcx, llsrc, lldsttype)
1875 fn float_cast(bcx: Block,
1880 let _icx = push_ctxt("float_cast");
1881 let srcsz = llsrctype.float_width();
1882 let dstsz = lldsttype.float_width();
1883 return if dstsz > srcsz {
1884 FPExt(bcx, llsrc, lldsttype)
1885 } else if srcsz > dstsz {
1886 FPTrunc(bcx, llsrc, lldsttype)
1890 #[deriving(Copy, PartialEq, Show)]
1891 pub enum cast_kind {
1899 pub fn cast_type_kind<'tcx>(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>) -> cast_kind {
1901 ty::ty_char => cast_integral,
1902 ty::ty_float(..) => cast_float,
1903 ty::ty_rptr(_, mt) | ty::ty_ptr(mt) => {
1904 if ty::type_is_sized(tcx, mt.ty) {
1910 ty::ty_bare_fn(..) => cast_pointer,
1911 ty::ty_int(..) => cast_integral,
1912 ty::ty_uint(..) => cast_integral,
1913 ty::ty_bool => cast_integral,
1914 ty::ty_enum(..) => cast_enum,
1919 fn cast_is_noop<'tcx>(t_in: Ty<'tcx>, t_out: Ty<'tcx>) -> bool {
1920 match (ty::deref(t_in, true), ty::deref(t_out, true)) {
1921 (Some(ty::mt{ ty: t_in, .. }), Some(ty::mt{ ty: t_out, .. })) => {
1928 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1931 -> DatumBlock<'blk, 'tcx, Expr> {
1932 let _icx = push_ctxt("trans_cast");
1934 let ccx = bcx.ccx();
1936 let t_in = expr_ty(bcx, expr);
1937 let t_out = node_id_type(bcx, id);
1938 let k_in = cast_type_kind(bcx.tcx(), t_in);
1939 let k_out = cast_type_kind(bcx.tcx(), t_out);
1940 let s_in = k_in == cast_integral && ty::type_is_signed(t_in);
1941 let ll_t_in = type_of::arg_type_of(ccx, t_in);
1942 let ll_t_out = type_of::arg_type_of(ccx, t_out);
1944 // Convert the value to be cast into a ValueRef, either by-ref or
1945 // by-value as appropriate given its type:
1946 let mut datum = unpack_datum!(bcx, trans(bcx, expr));
1948 if cast_is_noop(datum.ty, t_out) {
1950 return DatumBlock::new(bcx, datum);
1953 let newval = match (k_in, k_out) {
1954 (cast_integral, cast_integral) => {
1955 let llexpr = datum.to_llscalarish(bcx);
1956 int_cast(bcx, ll_t_out, ll_t_in, llexpr, s_in)
1958 (cast_float, cast_float) => {
1959 let llexpr = datum.to_llscalarish(bcx);
1960 float_cast(bcx, ll_t_out, ll_t_in, llexpr)
1962 (cast_integral, cast_float) => {
1963 let llexpr = datum.to_llscalarish(bcx);
1965 SIToFP(bcx, llexpr, ll_t_out)
1966 } else { UIToFP(bcx, llexpr, ll_t_out) }
1968 (cast_float, cast_integral) => {
1969 let llexpr = datum.to_llscalarish(bcx);
1970 if ty::type_is_signed(t_out) {
1971 FPToSI(bcx, llexpr, ll_t_out)
1972 } else { FPToUI(bcx, llexpr, ll_t_out) }
1974 (cast_integral, cast_pointer) => {
1975 let llexpr = datum.to_llscalarish(bcx);
1976 IntToPtr(bcx, llexpr, ll_t_out)
1978 (cast_pointer, cast_integral) => {
1979 let llexpr = datum.to_llscalarish(bcx);
1980 PtrToInt(bcx, llexpr, ll_t_out)
1982 (cast_pointer, cast_pointer) => {
1983 let llexpr = datum.to_llscalarish(bcx);
1984 PointerCast(bcx, llexpr, ll_t_out)
1986 (cast_enum, cast_integral) |
1987 (cast_enum, cast_float) => {
1989 let repr = adt::represent_type(ccx, t_in);
1990 let datum = unpack_datum!(
1991 bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
1992 let llexpr_ptr = datum.to_llref();
1994 adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
1996 cast_integral => int_cast(bcx, ll_t_out,
1997 val_ty(lldiscrim_a),
1999 cast_float => SIToFP(bcx, lldiscrim_a, ll_t_out),
2001 ccx.sess().bug(format!("translating unsupported cast: \
2002 {} ({}) -> {} ({})",
2003 t_in.repr(bcx.tcx()),
2005 t_out.repr(bcx.tcx()),
2010 _ => ccx.sess().bug(format!("translating unsupported cast: \
2011 {} ({}) -> {} ({})",
2012 t_in.repr(bcx.tcx()),
2014 t_out.repr(bcx.tcx()),
2017 return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
2020 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2025 -> Block<'blk, 'tcx> {
2026 let _icx = push_ctxt("trans_assign_op");
2029 debug!("trans_assign_op(expr={})", bcx.expr_to_string(expr));
2031 // User-defined operator methods cannot be used with `+=` etc right now
2032 assert!(!bcx.tcx().method_map.borrow().contains_key(&MethodCall::expr(expr.id)));
2034 // Evaluate LHS (destination), which should be an lvalue
2035 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2036 assert!(!ty::type_needs_drop(bcx.tcx(), dst_datum.ty));
2037 let dst_ty = dst_datum.ty;
2038 let dst = load_ty(bcx, dst_datum.val, dst_datum.ty);
2041 let rhs_datum = unpack_datum!(bcx, trans(bcx, &*src));
2042 let rhs_ty = rhs_datum.ty;
2043 let rhs = rhs_datum.to_llscalarish(bcx);
2045 // Perform computation and store the result
2046 let result_datum = unpack_datum!(
2047 bcx, trans_eager_binop(bcx, expr, dst_datum.ty, op,
2048 dst_ty, dst, rhs_ty, rhs));
2049 return result_datum.store_to(bcx, dst_datum.val);
2052 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2053 datum: Datum<'tcx, Expr>,
2055 -> DatumBlock<'blk, 'tcx, Expr> {
2058 // Ensure cleanup of `datum` if not already scheduled and obtain
2059 // a "by ref" pointer.
2060 let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2062 // Compute final type. Note that we are loose with the region and
2063 // mutability, since those things don't matter in trans.
2064 let referent_ty = lv_datum.ty;
2065 let ptr_ty = ty::mk_imm_rptr(bcx.tcx(), ty::ReStatic, referent_ty);
2068 let llref = lv_datum.to_llref();
2070 // Construct the resulting datum, using what was the "by ref"
2071 // ValueRef of type `referent_ty` to be the "by value" ValueRef
2072 // of type `&referent_ty`.
2073 DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(ByValue))))
2076 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2078 datum: Datum<'tcx, Expr>,
2080 -> DatumBlock<'blk, 'tcx, Expr> {
2082 let mut datum = datum;
2083 for i in range(0, times) {
2084 let method_call = MethodCall::autoderef(expr.id, i);
2085 datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2087 DatumBlock { bcx: bcx, datum: datum }
2090 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2092 datum: Datum<'tcx, Expr>,
2093 method_call: MethodCall)
2094 -> DatumBlock<'blk, 'tcx, Expr> {
2095 let ccx = bcx.ccx();
2097 debug!("deref_once(expr={}, datum={}, method_call={})",
2098 expr.repr(bcx.tcx()),
2099 datum.to_string(ccx),
2104 // Check for overloaded deref.
2105 let method_ty = ccx.tcx().method_map.borrow()
2106 .get(&method_call).map(|method| method.ty);
2107 let datum = match method_ty {
2108 Some(method_ty) => {
2109 // Overloaded. Evaluate `trans_overloaded_op`, which will
2110 // invoke the user's deref() method, which basically
2111 // converts from the `Smaht<T>` pointer that we have into
2112 // a `&T` pointer. We can then proceed down the normal
2113 // path (below) to dereference that `&T`.
2114 let datum = match method_call.adjustment {
2115 // Always perform an AutoPtr when applying an overloaded auto-deref
2116 ty::AutoDeref(_) => unpack_datum!(bcx, auto_ref(bcx, datum, expr)),
2120 let ref_ty = ty::ty_fn_ret(monomorphize_type(bcx, method_ty)).unwrap();
2121 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2123 unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2124 datum, Vec::new(), Some(SaveIn(scratch.val)),
2126 scratch.to_expr_datum()
2129 // Not overloaded. We already have a pointer we know how to deref.
2134 let r = match datum.ty.sty {
2135 ty::ty_uniq(content_ty) => {
2136 if ty::type_is_sized(bcx.tcx(), content_ty) {
2137 deref_owned_pointer(bcx, expr, datum, content_ty)
2139 // A fat pointer and an opened DST value have the same
2140 // representation just different types. Since there is no
2141 // temporary for `*e` here (because it is unsized), we cannot
2142 // emulate the sized object code path for running drop glue and
2143 // free. Instead, we schedule cleanup for `e`, turning it into
2145 let datum = unpack_datum!(
2146 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2148 let datum = Datum::new(datum.val, ty::mk_open(bcx.tcx(), content_ty), LvalueExpr);
2149 DatumBlock::new(bcx, datum)
2153 ty::ty_ptr(ty::mt { ty: content_ty, .. }) |
2154 ty::ty_rptr(_, ty::mt { ty: content_ty, .. }) => {
2155 if ty::type_is_sized(bcx.tcx(), content_ty) {
2156 let ptr = datum.to_llscalarish(bcx);
2158 // Always generate an lvalue datum, even if datum.mode is
2159 // an rvalue. This is because datum.mode is only an
2160 // rvalue for non-owning pointers like &T or *T, in which
2161 // case cleanup *is* scheduled elsewhere, by the true
2162 // owner (or, in the case of *T, by the user).
2163 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr))
2165 // A fat pointer and an opened DST value have the same representation
2166 // just different types.
2167 DatumBlock::new(bcx, Datum::new(datum.val,
2168 ty::mk_open(bcx.tcx(), content_ty),
2174 bcx.tcx().sess.span_bug(
2176 format!("deref invoked on expr of illegal type {}",
2177 datum.ty.repr(bcx.tcx())).as_slice());
2181 debug!("deref_once(expr={}, method_call={}, result={})",
2182 expr.id, method_call, r.datum.to_string(ccx));
2186 /// We microoptimize derefs of owned pointers a bit here. Basically, the idea is to make the
2187 /// deref of an rvalue result in an rvalue. This helps to avoid intermediate stack slots in the
2188 /// resulting LLVM. The idea here is that, if the `Box<T>` pointer is an rvalue, then we can
2189 /// schedule a *shallow* free of the `Box<T>` pointer, and then return a ByRef rvalue into the
2190 /// pointer. Because the free is shallow, it is legit to return an rvalue, because we know that
2191 /// the contents are not yet scheduled to be freed. The language rules ensure that the contents
2192 /// will be used (or moved) before the free occurs.
2193 fn deref_owned_pointer<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2195 datum: Datum<'tcx, Expr>,
2196 content_ty: Ty<'tcx>)
2197 -> DatumBlock<'blk, 'tcx, Expr> {
2199 RvalueExpr(Rvalue { mode: ByRef }) => {
2200 let scope = cleanup::temporary_scope(bcx.tcx(), expr.id);
2201 let ptr = Load(bcx, datum.val);
2202 if !type_is_zero_size(bcx.ccx(), content_ty) {
2203 bcx.fcx.schedule_free_value(scope, ptr, cleanup::HeapExchange, content_ty);
2206 RvalueExpr(Rvalue { mode: ByValue }) => {
2207 let scope = cleanup::temporary_scope(bcx.tcx(), expr.id);
2208 if !type_is_zero_size(bcx.ccx(), content_ty) {
2209 bcx.fcx.schedule_free_value(scope, datum.val, cleanup::HeapExchange,
2216 // If we had an rvalue in, we produce an rvalue out.
2217 let (llptr, kind) = match datum.kind {
2219 (Load(bcx, datum.val), LvalueExpr)
2221 RvalueExpr(Rvalue { mode: ByRef }) => {
2222 (Load(bcx, datum.val), RvalueExpr(Rvalue::new(ByRef)))
2224 RvalueExpr(Rvalue { mode: ByValue }) => {
2225 (datum.val, RvalueExpr(Rvalue::new(ByRef)))
2229 let datum = Datum { ty: content_ty, val: llptr, kind: kind };
2230 DatumBlock { bcx: bcx, datum: datum }