]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/expr.rs
rollup merge of #21014: steveklabnik/gh20876
[rust.git] / src / librustc_trans / trans / expr.rs
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.
4 //
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.
10
11 //! # Translation of Expressions
12 //!
13 //! Public entry points:
14 //!
15 //! - `trans_into(bcx, expr, dest) -> bcx`: evaluates an expression,
16 //!   storing the result into `dest`. This is the preferred form, if you
17 //!   can manage it.
18 //!
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
22 //!   structural type.
23 //!
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.
27 //!
28 //! - `trans_local_var -> Datum`: looks up a local variable or upvar.
29 //!
30 //! See doc.rs for more comments.
31
32 #![allow(non_camel_case_types)]
33
34 pub use self::cast_kind::*;
35 pub use self::Dest::*;
36 use self::lazy_binop_ty::*;
37
38 use back::abi;
39 use llvm::{self, ValueRef};
40 use middle::def;
41 use middle::mem_categorization::Typer;
42 use middle::subst::{self, Substs};
43 use trans::{_match, adt, asm, base, callee, closure, consts, controlflow};
44 use trans::base::*;
45 use trans::build::*;
46 use trans::cleanup::{self, CleanupMethods};
47 use trans::common::*;
48 use trans::datum::*;
49 use trans::debuginfo;
50 use trans::glue;
51 use trans::machine;
52 use trans::meth;
53 use trans::monomorphize;
54 use trans::inline;
55 use trans::tvec;
56 use trans::type_of;
57 use middle::ty::{struct_fields, tup_fields};
58 use middle::ty::{AdjustDerefRef, AdjustReifyFnPointer, AutoUnsafe};
59 use middle::ty::{AutoPtr};
60 use middle::ty::{self, Ty};
61 use middle::ty::MethodCall;
62 use util::common::indenter;
63 use util::ppaux::Repr;
64 use trans::machine::{llsize_of, llsize_of_alloc};
65 use trans::type_::Type;
66
67 use syntax::{ast, ast_util, codemap};
68 use syntax::print::pprust::{expr_to_string};
69 use syntax::ptr::P;
70 use syntax::parse::token;
71 use std::rc::Rc;
72 use std::iter::repeat;
73
74 // Destinations
75
76 // These are passed around by the code generating functions to track the
77 // destination of a computation's value.
78
79 #[derive(Copy, PartialEq)]
80 pub enum Dest {
81     SaveIn(ValueRef),
82     Ignore,
83 }
84
85 impl Dest {
86     pub fn to_string(&self, ccx: &CrateContext) -> String {
87         match *self {
88             SaveIn(v) => format!("SaveIn({})", ccx.tn().val_to_string(v)),
89             Ignore => "Ignore".to_string()
90         }
91     }
92 }
93
94 /// This function is equivalent to `trans(bcx, expr).store_to_dest(dest)` but it may generate
95 /// better optimized LLVM code.
96 pub fn trans_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
97                               expr: &ast::Expr,
98                               dest: Dest)
99                               -> Block<'blk, 'tcx> {
100     let mut bcx = bcx;
101
102     if bcx.tcx().adjustments.borrow().contains_key(&expr.id) {
103         // use trans, which may be less efficient but
104         // which will perform the adjustments:
105         let datum = unpack_datum!(bcx, trans(bcx, expr));
106         return datum.store_to_dest(bcx, dest, expr.id)
107     }
108
109     debug!("trans_into() expr={}", expr.repr(bcx.tcx()));
110
111     let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
112                                                                           expr.id,
113                                                                           expr.span,
114                                                                           false);
115     bcx.fcx.push_ast_cleanup_scope(cleanup_debug_loc);
116
117     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
118     let kind = ty::expr_kind(bcx.tcx(), expr);
119     bcx = match kind {
120         ty::LvalueExpr | ty::RvalueDatumExpr => {
121             trans_unadjusted(bcx, expr).store_to_dest(dest, expr.id)
122         }
123         ty::RvalueDpsExpr => {
124             trans_rvalue_dps_unadjusted(bcx, expr, dest)
125         }
126         ty::RvalueStmtExpr => {
127             trans_rvalue_stmt_unadjusted(bcx, expr)
128         }
129     };
130
131     bcx.fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id)
132 }
133
134 /// Translates an expression, returning a datum (and new block) encapsulating the result. When
135 /// possible, it is preferred to use `trans_into`, as that may avoid creating a temporary on the
136 /// stack.
137 pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
138                          expr: &ast::Expr)
139                          -> DatumBlock<'blk, 'tcx, Expr> {
140     debug!("trans(expr={})", bcx.expr_to_string(expr));
141
142     let mut bcx = bcx;
143     let fcx = bcx.fcx;
144
145     let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
146                                                                           expr.id,
147                                                                           expr.span,
148                                                                           false);
149     fcx.push_ast_cleanup_scope(cleanup_debug_loc);
150     let datum = unpack_datum!(bcx, trans_unadjusted(bcx, expr));
151     let datum = unpack_datum!(bcx, apply_adjustments(bcx, expr, datum));
152     bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id);
153     return DatumBlock::new(bcx, datum);
154 }
155
156 pub fn get_len(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
157     GEPi(bcx, fat_ptr, &[0u, abi::FAT_PTR_EXTRA])
158 }
159
160 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
161     GEPi(bcx, fat_ptr, &[0u, abi::FAT_PTR_ADDR])
162 }
163
164 /// Helper for trans that apply adjustments from `expr` to `datum`, which should be the unadjusted
165 /// translation of `expr`.
166 fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
167                                  expr: &ast::Expr,
168                                  datum: Datum<'tcx, Expr>)
169                                  -> DatumBlock<'blk, 'tcx, Expr> {
170     let mut bcx = bcx;
171     let mut datum = datum;
172     let adjustment = match bcx.tcx().adjustments.borrow().get(&expr.id).cloned() {
173         None => {
174             return DatumBlock::new(bcx, datum);
175         }
176         Some(adj) => { adj }
177     };
178     debug!("unadjusted datum for expr {}: {}, adjustment={}",
179            expr.repr(bcx.tcx()),
180            datum.to_string(bcx.ccx()),
181            adjustment.repr(bcx.tcx()));
182     match adjustment {
183         AdjustReifyFnPointer(_def_id) => {
184             // FIXME(#19925) once fn item types are
185             // zero-sized, we'll need to do something here
186         }
187         AdjustDerefRef(ref adj) => {
188             let (autoderefs, use_autoref) = match adj.autoref {
189                 // Extracting a value from a box counts as a deref, but if we are
190                 // just converting Box<[T, ..n]> to Box<[T]> we aren't really doing
191                 // a deref (and wouldn't if we could treat Box like a normal struct).
192                 Some(ty::AutoUnsizeUniq(..)) => (adj.autoderefs - 1, true),
193                 // We are a bit paranoid about adjustments and thus might have a re-
194                 // borrow here which merely derefs and then refs again (it might have
195                 // a different region or mutability, but we don't care here. It might
196                 // also be just in case we need to unsize. But if there are no nested
197                 // adjustments then it should be a no-op).
198                 Some(ty::AutoPtr(_, _, None)) if adj.autoderefs == 1 => {
199                     match datum.ty.sty {
200                         // Don't skip a conversion from Box<T> to &T, etc.
201                         ty::ty_rptr(..) => {
202                             let method_call = MethodCall::autoderef(expr.id, adj.autoderefs-1);
203                             let method = bcx.tcx().method_map.borrow().get(&method_call).is_some();
204                             if method {
205                                 // Don't skip an overloaded deref.
206                                 (adj.autoderefs, true)
207                             } else {
208                                 (adj.autoderefs - 1, false)
209                             }
210                         }
211                         _ => (adj.autoderefs, true),
212                     }
213                 }
214                 _ => (adj.autoderefs, true)
215             };
216
217             if autoderefs > 0 {
218                 // Schedule cleanup.
219                 let lval = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "auto_deref", expr.id));
220                 datum = unpack_datum!(
221                     bcx, deref_multiple(bcx, expr, lval.to_expr_datum(), autoderefs));
222             }
223
224             // (You might think there is a more elegant way to do this than a
225             // use_autoref bool, but then you remember that the borrow checker exists).
226             if let (true, &Some(ref a)) = (use_autoref, &adj.autoref) {
227                 datum = unpack_datum!(bcx, apply_autoref(a,
228                                                          bcx,
229                                                          expr,
230                                                          datum));
231             }
232         }
233     }
234     debug!("after adjustments, datum={}", datum.to_string(bcx.ccx()));
235     return DatumBlock::new(bcx, datum);
236
237     fn apply_autoref<'blk, 'tcx>(autoref: &ty::AutoRef<'tcx>,
238                                  bcx: Block<'blk, 'tcx>,
239                                  expr: &ast::Expr,
240                                  datum: Datum<'tcx, Expr>)
241                                  -> DatumBlock<'blk, 'tcx, Expr> {
242         let mut bcx = bcx;
243         let mut datum = datum;
244
245         let datum = match autoref {
246             &AutoPtr(_, _, ref a) | &AutoUnsafe(_, ref a) => {
247                 debug!("  AutoPtr");
248                 match a {
249                     &Some(box ref a) => {
250                         datum = unpack_datum!(bcx, apply_autoref(a, bcx, expr, datum));
251                     }
252                     &None => {}
253                 }
254                 unpack_datum!(bcx, ref_ptr(bcx, expr, datum))
255             }
256             &ty::AutoUnsize(ref k) => {
257                 debug!("  AutoUnsize");
258                 unpack_datum!(bcx, unsize_expr(bcx, expr, datum, k))
259             }
260
261             &ty::AutoUnsizeUniq(ty::UnsizeLength(len)) => {
262                 debug!("  AutoUnsizeUniq(UnsizeLength)");
263                 unpack_datum!(bcx, unsize_unique_vec(bcx, expr, datum, len))
264             }
265             &ty::AutoUnsizeUniq(ref k) => {
266                 debug!("  AutoUnsizeUniq");
267                 unpack_datum!(bcx, unsize_unique_expr(bcx, expr, datum, k))
268             }
269         };
270
271         DatumBlock::new(bcx, datum)
272     }
273
274     fn ref_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
275                            expr: &ast::Expr,
276                            datum: Datum<'tcx, Expr>)
277                            -> DatumBlock<'blk, 'tcx, Expr> {
278         debug!("ref_ptr(expr={}, datum={})",
279                expr.repr(bcx.tcx()),
280                datum.to_string(bcx.ccx()));
281
282         if !type_is_sized(bcx.tcx(), datum.ty) {
283             debug!("Taking address of unsized type {}",
284                    bcx.ty_to_string(datum.ty));
285             ref_fat_ptr(bcx, expr, datum)
286         } else {
287             debug!("Taking address of sized type {}",
288                    bcx.ty_to_string(datum.ty));
289             auto_ref(bcx, datum, expr)
290         }
291     }
292
293     // Retrieve the information we are losing (making dynamic) in an unsizing
294     // adjustment.
295     // When making a dtor, we need to do different things depending on the
296     // ownership of the object.. mk_ty is a function for turning `unadjusted_ty`
297     // into a type to be destructed. If we want to end up with a Box pointer,
298     // then mk_ty should make a Box pointer (T -> Box<T>), if we want a
299     // borrowed reference then it should be T -> &T.
300     fn unsized_info<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
301                                    kind: &ty::UnsizeKind<'tcx>,
302                                    id: ast::NodeId,
303                                    unadjusted_ty: Ty<'tcx>,
304                                    mk_ty: F) -> ValueRef where
305         F: FnOnce(Ty<'tcx>) -> Ty<'tcx>,
306     {
307         // FIXME(#19596) workaround: `|t| t` causes monomorphization recursion
308         fn identity<T>(t: T) -> T { t }
309
310         debug!("unsized_info(kind={:?}, id={}, unadjusted_ty={})",
311                kind, id, unadjusted_ty.repr(bcx.tcx()));
312         match kind {
313             &ty::UnsizeLength(len) => C_uint(bcx.ccx(), len),
314             &ty::UnsizeStruct(box ref k, tp_index) => match unadjusted_ty.sty {
315                 ty::ty_struct(_, ref substs) => {
316                     let ty_substs = substs.types.get_slice(subst::TypeSpace);
317                     // The dtor for a field treats it like a value, so mk_ty
318                     // should just be the identity function.
319                     unsized_info(bcx, k, id, ty_substs[tp_index], identity)
320                 }
321                 _ => bcx.sess().bug(&format!("UnsizeStruct with bad sty: {}",
322                                           bcx.ty_to_string(unadjusted_ty))[])
323             },
324             &ty::UnsizeVtable(ty::TyTrait { ref principal, .. }, _) => {
325                 // Note that we preserve binding levels here:
326                 let substs = principal.0.substs.with_self_ty(unadjusted_ty).erase_regions();
327                 let substs = bcx.tcx().mk_substs(substs);
328                 let trait_ref =
329                     ty::Binder(Rc::new(ty::TraitRef { def_id: principal.def_id(),
330                                                       substs: substs }));
331                 let trait_ref = bcx.monomorphize(&trait_ref);
332                 let box_ty = mk_ty(unadjusted_ty);
333                 PointerCast(bcx,
334                             meth::get_vtable(bcx, box_ty, trait_ref),
335                             Type::vtable_ptr(bcx.ccx()))
336             }
337         }
338     }
339
340     fn unsize_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
341                                expr: &ast::Expr,
342                                datum: Datum<'tcx, Expr>,
343                                k: &ty::UnsizeKind<'tcx>)
344                                -> DatumBlock<'blk, 'tcx, Expr> {
345         let tcx = bcx.tcx();
346         let datum_ty = datum.ty;
347         let unsized_ty = ty::unsize_ty(tcx, datum_ty, k, expr.span);
348         debug!("unsized_ty={}", unsized_ty.repr(bcx.tcx()));
349         let dest_ty = ty::mk_open(tcx, unsized_ty);
350         debug!("dest_ty={}", unsized_ty.repr(bcx.tcx()));
351         // Closures for extracting and manipulating the data and payload parts of
352         // the fat pointer.
353         let info = |: bcx, _val| unsized_info(bcx,
354                                               k,
355                                               expr.id,
356                                               datum_ty,
357                                               |t| ty::mk_rptr(tcx,
358                                                               tcx.mk_region(ty::ReStatic),
359                                                               ty::mt{
360                                                                   ty: t,
361                                                                   mutbl: ast::MutImmutable
362                                                               }));
363         match *k {
364             ty::UnsizeStruct(..) =>
365                 into_fat_ptr(bcx, expr, datum, dest_ty, |bcx, val| {
366                     PointerCast(bcx, val, type_of::type_of(bcx.ccx(), unsized_ty).ptr_to())
367                 }, info),
368             ty::UnsizeLength(..) =>
369                 into_fat_ptr(bcx, expr, datum, dest_ty, |bcx, val| {
370                     GEPi(bcx, val, &[0u, 0u])
371                 }, info),
372             ty::UnsizeVtable(..) =>
373                 into_fat_ptr(bcx, expr, datum, dest_ty, |_bcx, val| {
374                     PointerCast(bcx, val, Type::i8p(bcx.ccx()))
375                 }, info),
376         }
377     }
378
379     fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
380                                expr: &ast::Expr,
381                                datum: Datum<'tcx, Expr>)
382                                -> DatumBlock<'blk, 'tcx, Expr> {
383         let tcx = bcx.tcx();
384         let dest_ty = ty::close_type(tcx, datum.ty);
385         let base = |: bcx, val| Load(bcx, get_dataptr(bcx, val));
386         let len = |: bcx, val| Load(bcx, get_len(bcx, val));
387         into_fat_ptr(bcx, expr, datum, dest_ty, base, len)
388     }
389
390     fn into_fat_ptr<'blk, 'tcx, F, G>(bcx: Block<'blk, 'tcx>,
391                                       expr: &ast::Expr,
392                                       datum: Datum<'tcx, Expr>,
393                                       dest_ty: Ty<'tcx>,
394                                       base: F,
395                                       info: G)
396                                       -> DatumBlock<'blk, 'tcx, Expr> where
397         F: FnOnce(Block<'blk, 'tcx>, ValueRef) -> ValueRef,
398         G: FnOnce(Block<'blk, 'tcx>, ValueRef) -> ValueRef,
399     {
400         let mut bcx = bcx;
401
402         // Arrange cleanup
403         let lval = unpack_datum!(bcx,
404                                  datum.to_lvalue_datum(bcx, "into_fat_ptr", expr.id));
405         let base = base(bcx, lval.val);
406         let info = info(bcx, lval.val);
407
408         let scratch = rvalue_scratch_datum(bcx, dest_ty, "__fat_ptr");
409         Store(bcx, base, get_dataptr(bcx, scratch.val));
410         Store(bcx, info, get_len(bcx, scratch.val));
411
412         DatumBlock::new(bcx, scratch.to_expr_datum())
413     }
414
415     fn unsize_unique_vec<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
416                                      expr: &ast::Expr,
417                                      datum: Datum<'tcx, Expr>,
418                                      len: uint)
419                                      -> DatumBlock<'blk, 'tcx, Expr> {
420         let mut bcx = bcx;
421         let tcx = bcx.tcx();
422
423         let datum_ty = datum.ty;
424         // Arrange cleanup
425         let lval = unpack_datum!(bcx,
426                                  datum.to_lvalue_datum(bcx, "unsize_unique_vec", expr.id));
427
428         let ll_len = C_uint(bcx.ccx(), len);
429         let unit_ty = ty::sequence_element_type(tcx, ty::type_content(datum_ty));
430         let vec_ty = ty::mk_uniq(tcx, ty::mk_vec(tcx, unit_ty, None));
431         let scratch = rvalue_scratch_datum(bcx, vec_ty, "__unsize_unique");
432
433         let base = get_dataptr(bcx, scratch.val);
434         let base = PointerCast(bcx,
435                                base,
436                                type_of::type_of(bcx.ccx(), datum_ty).ptr_to());
437         bcx = lval.store_to(bcx, base);
438
439         Store(bcx, ll_len, get_len(bcx, scratch.val));
440         DatumBlock::new(bcx, scratch.to_expr_datum())
441     }
442
443     fn unsize_unique_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
444                                       expr: &ast::Expr,
445                                       datum: Datum<'tcx, Expr>,
446                                       k: &ty::UnsizeKind<'tcx>)
447                                       -> DatumBlock<'blk, 'tcx, Expr> {
448         let mut bcx = bcx;
449         let tcx = bcx.tcx();
450
451         let datum_ty = datum.ty;
452         let unboxed_ty = match datum_ty.sty {
453             ty::ty_uniq(t) => t,
454             _ => bcx.sess().bug(&format!("Expected ty_uniq, found {}",
455                                         bcx.ty_to_string(datum_ty))[])
456         };
457         let result_ty = ty::mk_uniq(tcx, ty::unsize_ty(tcx, unboxed_ty, k, expr.span));
458
459         let lval = unpack_datum!(bcx,
460                                  datum.to_lvalue_datum(bcx, "unsize_unique_expr", expr.id));
461
462         let scratch = rvalue_scratch_datum(bcx, result_ty, "__uniq_fat_ptr");
463         let llbox_ty = type_of::type_of(bcx.ccx(), datum_ty);
464         let base = PointerCast(bcx, get_dataptr(bcx, scratch.val), llbox_ty.ptr_to());
465         bcx = lval.store_to(bcx, base);
466
467         let info = unsized_info(bcx, k, expr.id, unboxed_ty, |t| ty::mk_uniq(tcx, t));
468         Store(bcx, info, get_len(bcx, scratch.val));
469
470         let scratch = unpack_datum!(bcx,
471                                     scratch.to_expr_datum().to_lvalue_datum(bcx,
472                                                                             "fresh_uniq_fat_ptr",
473                                                                             expr.id));
474
475         DatumBlock::new(bcx, scratch.to_expr_datum())
476     }
477 }
478
479 /// Translates an expression in "lvalue" mode -- meaning that it returns a reference to the memory
480 /// that the expr represents.
481 ///
482 /// If this expression is an rvalue, this implies introducing a temporary.  In other words,
483 /// something like `x().f` is translated into roughly the equivalent of
484 ///
485 ///   { tmp = x(); tmp.f }
486 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
487                                    expr: &ast::Expr,
488                                    name: &str)
489                                    -> DatumBlock<'blk, 'tcx, Lvalue> {
490     let mut bcx = bcx;
491     let datum = unpack_datum!(bcx, trans(bcx, expr));
492     return datum.to_lvalue_datum(bcx, name, expr.id);
493 }
494
495 /// A version of `trans` that ignores adjustments. You almost certainly do not want to call this
496 /// directly.
497 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
498                                 expr: &ast::Expr)
499                                 -> DatumBlock<'blk, 'tcx, Expr> {
500     let mut bcx = bcx;
501
502     debug!("trans_unadjusted(expr={})", bcx.expr_to_string(expr));
503     let _indenter = indenter();
504
505     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
506
507     return match ty::expr_kind(bcx.tcx(), expr) {
508         ty::LvalueExpr | ty::RvalueDatumExpr => {
509             let datum = unpack_datum!(bcx, {
510                 trans_datum_unadjusted(bcx, expr)
511             });
512
513             DatumBlock {bcx: bcx, datum: datum}
514         }
515
516         ty::RvalueStmtExpr => {
517             bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
518             nil(bcx, expr_ty(bcx, expr))
519         }
520
521         ty::RvalueDpsExpr => {
522             let ty = expr_ty(bcx, expr);
523             if type_is_zero_size(bcx.ccx(), ty) {
524                 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
525                 nil(bcx, ty)
526             } else {
527                 let scratch = rvalue_scratch_datum(bcx, ty, "");
528                 bcx = trans_rvalue_dps_unadjusted(
529                     bcx, expr, SaveIn(scratch.val));
530
531                 // Note: this is not obviously a good idea.  It causes
532                 // immediate values to be loaded immediately after a
533                 // return from a call or other similar expression,
534                 // which in turn leads to alloca's having shorter
535                 // lifetimes and hence larger stack frames.  However,
536                 // in turn it can lead to more register pressure.
537                 // Still, in practice it seems to increase
538                 // performance, since we have fewer problems with
539                 // morestack churn.
540                 let scratch = unpack_datum!(
541                     bcx, scratch.to_appropriate_datum(bcx));
542
543                 DatumBlock::new(bcx, scratch.to_expr_datum())
544             }
545         }
546     };
547
548     fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: Ty<'tcx>)
549                        -> DatumBlock<'blk, 'tcx, Expr> {
550         let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
551         let datum = immediate_rvalue(llval, ty);
552         DatumBlock::new(bcx, datum.to_expr_datum())
553     }
554 }
555
556 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
557                                       expr: &ast::Expr)
558                                       -> DatumBlock<'blk, 'tcx, Expr> {
559     let mut bcx = bcx;
560     let fcx = bcx.fcx;
561     let _icx = push_ctxt("trans_datum_unadjusted");
562
563     match expr.node {
564         ast::ExprParen(ref e) => {
565             trans(bcx, &**e)
566         }
567         ast::ExprPath(_) | ast::ExprQPath(_) => {
568             trans_def(bcx, expr, bcx.def(expr.id))
569         }
570         ast::ExprField(ref base, ident) => {
571             trans_rec_field(bcx, &**base, ident.node)
572         }
573         ast::ExprTupField(ref base, idx) => {
574             trans_rec_tup_field(bcx, &**base, idx.node)
575         }
576         ast::ExprIndex(ref base, ref idx) => {
577             trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id))
578         }
579         ast::ExprBox(_, ref contents) => {
580             // Special case for `Box<T>`
581             let box_ty = expr_ty(bcx, expr);
582             let contents_ty = expr_ty(bcx, &**contents);
583             match box_ty.sty {
584                 ty::ty_uniq(..) => {
585                     trans_uniq_expr(bcx, box_ty, &**contents, contents_ty)
586                 }
587                 _ => bcx.sess().span_bug(expr.span,
588                                          "expected unique box")
589             }
590
591         }
592         ast::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, &**lit),
593         ast::ExprBinary(op, ref lhs, ref rhs) => {
594             trans_binary(bcx, expr, op, &**lhs, &**rhs)
595         }
596         ast::ExprUnary(op, ref x) => {
597             trans_unary(bcx, expr, op, &**x)
598         }
599         ast::ExprAddrOf(_, ref x) => {
600             match x.node {
601                 ast::ExprRepeat(..) | ast::ExprVec(..) => {
602                     // Special case for slices.
603                     let cleanup_debug_loc =
604                         debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
605                                                                       x.id,
606                                                                       x.span,
607                                                                       false);
608                     fcx.push_ast_cleanup_scope(cleanup_debug_loc);
609                     let datum = unpack_datum!(
610                         bcx, tvec::trans_slice_vec(bcx, expr, &**x));
611                     bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
612                     DatumBlock::new(bcx, datum)
613                 }
614                 _ => {
615                     trans_addr_of(bcx, expr, &**x)
616                 }
617             }
618         }
619         ast::ExprCast(ref val, _) => {
620             // Datum output mode means this is a scalar cast:
621             trans_imm_cast(bcx, &**val, expr.id)
622         }
623         _ => {
624             bcx.tcx().sess.span_bug(
625                 expr.span,
626                 &format!("trans_rvalue_datum_unadjusted reached \
627                          fall-through case: {:?}",
628                         expr.node)[]);
629         }
630     }
631 }
632
633 fn trans_field<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
634                               base: &ast::Expr,
635                               get_idx: F)
636                               -> DatumBlock<'blk, 'tcx, Expr> where
637     F: FnOnce(&'blk ty::ctxt<'tcx>, &[ty::field<'tcx>]) -> uint,
638 {
639     let mut bcx = bcx;
640     let _icx = push_ctxt("trans_rec_field");
641
642     let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
643     let bare_ty = ty::unopen_type(base_datum.ty);
644     let repr = adt::represent_type(bcx.ccx(), bare_ty);
645     with_field_tys(bcx.tcx(), bare_ty, None, move |discr, field_tys| {
646         let ix = get_idx(bcx.tcx(), field_tys);
647         let d = base_datum.get_element(
648             bcx,
649             field_tys[ix].mt.ty,
650             |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, ix));
651
652         if type_is_sized(bcx.tcx(), d.ty) {
653             DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
654         } else {
655             let scratch = rvalue_scratch_datum(bcx, ty::mk_open(bcx.tcx(), d.ty), "");
656             Store(bcx, d.val, get_dataptr(bcx, scratch.val));
657             let info = Load(bcx, get_len(bcx, base_datum.val));
658             Store(bcx, info, get_len(bcx, scratch.val));
659
660             DatumBlock::new(bcx, scratch.to_expr_datum())
661
662         }
663     })
664
665 }
666
667 /// Translates `base.field`.
668 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
669                                base: &ast::Expr,
670                                field: ast::Ident)
671                                -> DatumBlock<'blk, 'tcx, Expr> {
672     trans_field(bcx, base, |tcx, field_tys| ty::field_idx_strict(tcx, field.name, field_tys))
673 }
674
675 /// Translates `base.<idx>`.
676 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
677                                    base: &ast::Expr,
678                                    idx: uint)
679                                    -> DatumBlock<'blk, 'tcx, Expr> {
680     trans_field(bcx, base, |_, _| idx)
681 }
682
683 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
684                            index_expr: &ast::Expr,
685                            base: &ast::Expr,
686                            idx: &ast::Expr,
687                            method_call: MethodCall)
688                            -> DatumBlock<'blk, 'tcx, Expr> {
689     //! Translates `base[idx]`.
690
691     let _icx = push_ctxt("trans_index");
692     let ccx = bcx.ccx();
693     let mut bcx = bcx;
694
695     // Check for overloaded index.
696     let method_ty = ccx.tcx()
697                        .method_map
698                        .borrow()
699                        .get(&method_call)
700                        .map(|method| method.ty);
701     let elt_datum = match method_ty {
702         Some(method_ty) => {
703             let method_ty = monomorphize_type(bcx, method_ty);
704
705             let base_datum = unpack_datum!(bcx, trans(bcx, base));
706
707             // Translate index expression.
708             let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
709
710             let ref_ty = // invoked methods have LB regions instantiated:
711                 ty::assert_no_late_bound_regions(
712                     bcx.tcx(), &ty::ty_fn_ret(method_ty)).unwrap();
713             let elt_ty = match ty::deref(ref_ty, true) {
714                 None => {
715                     bcx.tcx().sess.span_bug(index_expr.span,
716                                             "index method didn't return a \
717                                              dereferenceable type?!")
718                 }
719                 Some(elt_tm) => elt_tm.ty,
720             };
721
722             // Overloaded. Evaluate `trans_overloaded_op`, which will
723             // invoke the user's index() method, which basically yields
724             // a `&T` pointer.  We can then proceed down the normal
725             // path (below) to dereference that `&T`.
726             let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_index_elt");
727             unpack_result!(bcx,
728                            trans_overloaded_op(bcx,
729                                                index_expr,
730                                                method_call,
731                                                base_datum,
732                                                vec![(ix_datum, idx.id)],
733                                                Some(SaveIn(scratch.val)),
734                                                true));
735             let datum = scratch.to_expr_datum();
736             if type_is_sized(bcx.tcx(), elt_ty) {
737                 Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr)
738             } else {
739                 Datum::new(datum.val, ty::mk_open(bcx.tcx(), elt_ty), LvalueExpr)
740             }
741         }
742         None => {
743             let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
744                                                                 base,
745                                                                 "index"));
746
747             // Translate index expression and cast to a suitable LLVM integer.
748             // Rust is less strict than LLVM in this regard.
749             let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
750             let ix_val = ix_datum.to_llscalarish(bcx);
751             let ix_size = machine::llbitsize_of_real(bcx.ccx(),
752                                                      val_ty(ix_val));
753             let int_size = machine::llbitsize_of_real(bcx.ccx(),
754                                                       ccx.int_type());
755             let ix_val = {
756                 if ix_size < int_size {
757                     if ty::type_is_signed(expr_ty(bcx, idx)) {
758                         SExt(bcx, ix_val, ccx.int_type())
759                     } else { ZExt(bcx, ix_val, ccx.int_type()) }
760                 } else if ix_size > int_size {
761                     Trunc(bcx, ix_val, ccx.int_type())
762                 } else {
763                     ix_val
764                 }
765             };
766
767             let vt =
768                 tvec::vec_types(bcx,
769                                 ty::sequence_element_type(bcx.tcx(),
770                                                           base_datum.ty));
771             base::maybe_name_value(bcx.ccx(), vt.llunit_size, "unit_sz");
772
773             let (base, len) = base_datum.get_vec_base_and_len(bcx);
774
775             debug!("trans_index: base {}", bcx.val_to_string(base));
776             debug!("trans_index: len {}", bcx.val_to_string(len));
777
778             let bounds_check = ICmp(bcx, llvm::IntUGE, ix_val, len);
779             let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
780             let expected = Call(bcx,
781                                 expect,
782                                 &[bounds_check, C_bool(ccx, false)],
783                                 None);
784             bcx = with_cond(bcx, expected, |bcx| {
785                 controlflow::trans_fail_bounds_check(bcx,
786                                                      index_expr.span,
787                                                      ix_val,
788                                                      len)
789             });
790             let elt = InBoundsGEP(bcx, base, &[ix_val]);
791             let elt = PointerCast(bcx, elt, vt.llunit_ty.ptr_to());
792             Datum::new(elt, vt.unit_ty, LvalueExpr)
793         }
794     };
795
796     DatumBlock::new(bcx, elt_datum)
797 }
798
799 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
800                          ref_expr: &ast::Expr,
801                          def: def::Def)
802                          -> DatumBlock<'blk, 'tcx, Expr> {
803     //! Translates a reference to a path.
804
805     let _icx = push_ctxt("trans_def_lvalue");
806     match def {
807         def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) |
808         def::DefStruct(_) | def::DefVariant(..) => {
809             let datum = trans_def_fn_unadjusted(bcx.ccx(), ref_expr, def,
810                                                 bcx.fcx.param_substs);
811             DatumBlock::new(bcx, datum.to_expr_datum())
812         }
813         def::DefStatic(did, _) => {
814             // There are two things that may happen here:
815             //  1) If the static item is defined in this crate, it will be
816             //     translated using `get_item_val`, and we return a pointer to
817             //     the result.
818             //  2) If the static item is defined in another crate then we add
819             //     (or reuse) a declaration of an external global, and return a
820             //     pointer to that.
821             let const_ty = expr_ty(bcx, ref_expr);
822
823             fn get_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, did: ast::DefId,
824                                    const_ty: Ty<'tcx>) -> ValueRef {
825                 // For external constants, we don't inline.
826                 if did.krate == ast::LOCAL_CRATE {
827                     // Case 1.
828
829                     // The LLVM global has the type of its initializer,
830                     // which may not be equal to the enum's type for
831                     // non-C-like enums.
832                     let val = base::get_item_val(bcx.ccx(), did.node);
833                     let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to();
834                     PointerCast(bcx, val, pty)
835                 } else {
836                     // Case 2.
837                     base::get_extern_const(bcx.ccx(), did, const_ty)
838                 }
839             }
840             let val = get_val(bcx, did, const_ty);
841             DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr))
842         }
843         def::DefConst(did) => {
844             // First, inline any external constants into the local crate so we
845             // can be sure to get the LLVM value corresponding to it.
846             let did = inline::maybe_instantiate_inline(bcx.ccx(), did);
847             if did.krate != ast::LOCAL_CRATE {
848                 bcx.tcx().sess.span_bug(ref_expr.span,
849                                         "cross crate constant could not \
850                                          be inlined");
851             }
852             let val = base::get_item_val(bcx.ccx(), did.node);
853
854             // Next, we need to crate a ByRef rvalue datum to return. We can't
855             // use the normal .to_ref_datum() function because the type of
856             // `val` is not actually the same as `const_ty`.
857             //
858             // To get around this, we make a custom alloca slot with the
859             // appropriate type (const_ty), and then we cast it to a pointer of
860             // typeof(val), store the value, and then hand this slot over to
861             // the datum infrastructure.
862             let const_ty = expr_ty(bcx, ref_expr);
863             let llty = type_of::type_of(bcx.ccx(), const_ty);
864             let slot = alloca(bcx, llty, "const");
865             let pty = Type::from_ref(unsafe { llvm::LLVMTypeOf(val) }).ptr_to();
866             Store(bcx, val, PointerCast(bcx, slot, pty));
867
868             let datum = Datum::new(slot, const_ty, Rvalue::new(ByRef));
869             DatumBlock::new(bcx, datum.to_expr_datum())
870         }
871         _ => {
872             DatumBlock::new(bcx, trans_local_var(bcx, def).to_expr_datum())
873         }
874     }
875 }
876
877 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
878                                             expr: &ast::Expr)
879                                             -> Block<'blk, 'tcx> {
880     let mut bcx = bcx;
881     let _icx = push_ctxt("trans_rvalue_stmt");
882
883     if bcx.unreachable.get() {
884         return bcx;
885     }
886
887     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
888
889     match expr.node {
890         ast::ExprParen(ref e) => {
891             trans_into(bcx, &**e, Ignore)
892         }
893         ast::ExprBreak(label_opt) => {
894             controlflow::trans_break(bcx, expr.id, label_opt)
895         }
896         ast::ExprAgain(label_opt) => {
897             controlflow::trans_cont(bcx, expr.id, label_opt)
898         }
899         ast::ExprRet(ref ex) => {
900             // Check to see if the return expression itself is reachable.
901             // This can occur when the inner expression contains a return
902             let reachable = if let Some(ref cfg) = bcx.fcx.cfg {
903                 cfg.node_is_reachable(expr.id)
904             } else {
905                 true
906             };
907
908             if reachable {
909                 controlflow::trans_ret(bcx, ex.as_ref().map(|e| &**e))
910             } else {
911                 // If it's not reachable, just translate the inner expression
912                 // directly. This avoids having to manage a return slot when
913                 // it won't actually be used anyway.
914                 if let &Some(ref x) = ex {
915                     bcx = trans_into(bcx, &**x, Ignore);
916                 }
917                 // Mark the end of the block as unreachable. Once we get to
918                 // a return expression, there's no more we should be doing
919                 // after this.
920                 Unreachable(bcx);
921                 bcx
922             }
923         }
924         ast::ExprWhile(ref cond, ref body, _) => {
925             controlflow::trans_while(bcx, expr.id, &**cond, &**body)
926         }
927         ast::ExprForLoop(ref pat, ref head, ref body, _) => {
928             controlflow::trans_for(bcx,
929                                    expr_info(expr),
930                                    &**pat,
931                                    &**head,
932                                    &**body)
933         }
934         ast::ExprLoop(ref body, _) => {
935             controlflow::trans_loop(bcx, expr.id, &**body)
936         }
937         ast::ExprAssign(ref dst, ref src) => {
938             let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
939             let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
940
941             if type_needs_drop(bcx.tcx(), dst_datum.ty) {
942                 // If there are destructors involved, make sure we
943                 // are copying from an rvalue, since that cannot possible
944                 // alias an lvalue. We are concerned about code like:
945                 //
946                 //   a = a
947                 //
948                 // but also
949                 //
950                 //   a = a.b
951                 //
952                 // where e.g. a : Option<Foo> and a.b :
953                 // Option<Foo>. In that case, freeing `a` before the
954                 // assignment may also free `a.b`!
955                 //
956                 // We could avoid this intermediary with some analysis
957                 // to determine whether `dst` may possibly own `src`.
958                 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
959                 let src_datum = unpack_datum!(
960                     bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
961                 bcx = glue::drop_ty(bcx,
962                                     dst_datum.val,
963                                     dst_datum.ty,
964                                     Some(NodeInfo { id: expr.id, span: expr.span }));
965                 src_datum.store_to(bcx, dst_datum.val)
966             } else {
967                 src_datum.store_to(bcx, dst_datum.val)
968             }
969         }
970         ast::ExprAssignOp(op, ref dst, ref src) => {
971             trans_assign_op(bcx, expr, op, &**dst, &**src)
972         }
973         ast::ExprInlineAsm(ref a) => {
974             asm::trans_inline_asm(bcx, a)
975         }
976         _ => {
977             bcx.tcx().sess.span_bug(
978                 expr.span,
979                 &format!("trans_rvalue_stmt_unadjusted reached \
980                          fall-through case: {:?}",
981                         expr.node)[]);
982         }
983     }
984 }
985
986 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
987                                            expr: &ast::Expr,
988                                            dest: Dest)
989                                            -> Block<'blk, 'tcx> {
990     let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
991     let mut bcx = bcx;
992     let tcx = bcx.tcx();
993
994     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
995
996     match expr.node {
997         ast::ExprParen(ref e) => {
998             trans_into(bcx, &**e, dest)
999         }
1000         ast::ExprPath(_) | ast::ExprQPath(_) => {
1001             trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
1002         }
1003         ast::ExprIf(ref cond, ref thn, ref els) => {
1004             controlflow::trans_if(bcx, expr.id, &**cond, &**thn, els.as_ref().map(|e| &**e), dest)
1005         }
1006         ast::ExprMatch(ref discr, ref arms, _) => {
1007             _match::trans_match(bcx, expr, &**discr, &arms[], dest)
1008         }
1009         ast::ExprBlock(ref blk) => {
1010             controlflow::trans_block(bcx, &**blk, dest)
1011         }
1012         ast::ExprStruct(_, ref fields, ref base) => {
1013             trans_struct(bcx,
1014                          &fields[],
1015                          base.as_ref().map(|e| &**e),
1016                          expr.span,
1017                          expr.id,
1018                          node_id_type(bcx, expr.id),
1019                          dest)
1020         }
1021         ast::ExprRange(ref start, ref end) => {
1022             // FIXME it is just not right that we are synthesising ast nodes in
1023             // trans. Shudder.
1024             fn make_field(field_name: &str, expr: P<ast::Expr>) -> ast::Field {
1025                 ast::Field {
1026                     ident: codemap::dummy_spanned(token::str_to_ident(field_name)),
1027                     expr: expr,
1028                     span: codemap::DUMMY_SP,
1029                 }
1030             }
1031
1032             // A range just desugars into a struct.
1033             // Note that the type of the start and end may not be the same, but
1034             // they should only differ in their lifetime, which should not matter
1035             // in trans.
1036             let (did, fields, ty_params) = match (start, end) {
1037                 (&Some(ref start), &Some(ref end)) => {
1038                     // Desugar to Range
1039                     let fields = vec![make_field("start", start.clone()),
1040                                       make_field("end", end.clone())];
1041                     (tcx.lang_items.range_struct(), fields, vec![node_id_type(bcx, start.id)])
1042                 }
1043                 (&Some(ref start), &None) => {
1044                     // Desugar to RangeFrom
1045                     let fields = vec![make_field("start", start.clone())];
1046                     (tcx.lang_items.range_from_struct(), fields, vec![node_id_type(bcx, start.id)])
1047                 }
1048                 (&None, &Some(ref end)) => {
1049                     // Desugar to RangeTo
1050                     let fields = vec![make_field("end", end.clone())];
1051                     (tcx.lang_items.range_to_struct(), fields, vec![node_id_type(bcx, end.id)])
1052                 }
1053                 _ => {
1054                     // Desugar to FullRange
1055                     (tcx.lang_items.full_range_struct(), vec![], vec![])
1056                 }
1057             };
1058
1059             if let Some(did) = did {
1060                 let substs = Substs::new_type(ty_params, vec![]);
1061                 trans_struct(bcx,
1062                              fields.as_slice(),
1063                              None,
1064                              expr.span,
1065                              expr.id,
1066                              ty::mk_struct(tcx, did, tcx.mk_substs(substs)),
1067                              dest)
1068             } else {
1069                 tcx.sess.span_bug(expr.span,
1070                                   "No lang item for ranges (how did we get this far?)")
1071             }
1072         }
1073         ast::ExprTup(ref args) => {
1074             let numbered_fields: Vec<(uint, &ast::Expr)> =
1075                 args.iter().enumerate().map(|(i, arg)| (i, &**arg)).collect();
1076             trans_adt(bcx,
1077                       expr_ty(bcx, expr),
1078                       0,
1079                       &numbered_fields[],
1080                       None,
1081                       dest,
1082                       Some(NodeInfo { id: expr.id, span: expr.span }))
1083         }
1084         ast::ExprLit(ref lit) => {
1085             match lit.node {
1086                 ast::LitStr(ref s, _) => {
1087                     tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1088                 }
1089                 _ => {
1090                     bcx.tcx()
1091                        .sess
1092                        .span_bug(expr.span,
1093                                  "trans_rvalue_dps_unadjusted shouldn't be \
1094                                   translating this type of literal")
1095                 }
1096             }
1097         }
1098         ast::ExprVec(..) | ast::ExprRepeat(..) => {
1099             tvec::trans_fixed_vstore(bcx, expr, dest)
1100         }
1101         ast::ExprClosure(_, _, ref decl, ref body) => {
1102             // Check the side-table to see whether this is an unboxed
1103             // closure or an older, legacy style closure. Store this
1104             // into a variable to ensure the the RefCell-lock is
1105             // released before we recurse.
1106             let is_unboxed_closure =
1107                 bcx.tcx().unboxed_closures.borrow().contains_key(&ast_util::local_def(expr.id));
1108             if is_unboxed_closure {
1109                 closure::trans_unboxed_closure(bcx, &**decl, &**body, expr.id, dest)
1110             } else {
1111                 let expr_ty = expr_ty(bcx, expr);
1112                 let store = ty::ty_closure_store(expr_ty);
1113                 debug!("translating block function {} with type {}",
1114                        expr_to_string(expr), expr_ty.repr(tcx));
1115                 closure::trans_expr_fn(bcx, store, &**decl, &**body, expr.id, dest)
1116             }
1117         }
1118         ast::ExprCall(ref f, ref args) => {
1119             if bcx.tcx().is_method_call(expr.id) {
1120                 trans_overloaded_call(bcx,
1121                                       expr,
1122                                       &**f,
1123                                       &args[],
1124                                       Some(dest))
1125             } else {
1126                 callee::trans_call(bcx,
1127                                    expr,
1128                                    &**f,
1129                                    callee::ArgExprs(&args[]),
1130                                    dest)
1131             }
1132         }
1133         ast::ExprMethodCall(_, _, ref args) => {
1134             callee::trans_method_call(bcx,
1135                                       expr,
1136                                       &*args[0],
1137                                       callee::ArgExprs(&args[]),
1138                                       dest)
1139         }
1140         ast::ExprBinary(op, ref lhs, ref rhs) => {
1141             // if not overloaded, would be RvalueDatumExpr
1142             let lhs = unpack_datum!(bcx, trans(bcx, &**lhs));
1143             let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs));
1144             trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs,
1145                                 vec![(rhs_datum, rhs.id)], Some(dest),
1146                                 !ast_util::is_by_value_binop(op)).bcx
1147         }
1148         ast::ExprUnary(op, ref subexpr) => {
1149             // if not overloaded, would be RvalueDatumExpr
1150             let arg = unpack_datum!(bcx, trans(bcx, &**subexpr));
1151             trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id),
1152                                 arg, Vec::new(), Some(dest), !ast_util::is_by_value_unop(op)).bcx
1153         }
1154         ast::ExprIndex(ref base, ref idx) => {
1155             // if not overloaded, would be RvalueDatumExpr
1156             let base = unpack_datum!(bcx, trans(bcx, &**base));
1157             let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx));
1158             trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
1159                                 vec![(idx_datum, idx.id)], Some(dest), true).bcx
1160         }
1161         ast::ExprCast(ref val, _) => {
1162             // DPS output mode means this is a trait cast:
1163             if ty::type_is_trait(node_id_type(bcx, expr.id)) {
1164                 let trait_ref =
1165                     bcx.tcx().object_cast_map.borrow()
1166                                              .get(&expr.id)
1167                                              .map(|t| (*t).clone())
1168                                              .unwrap();
1169                 let trait_ref = bcx.monomorphize(&trait_ref);
1170                 let datum = unpack_datum!(bcx, trans(bcx, &**val));
1171                 meth::trans_trait_cast(bcx, datum, expr.id,
1172                                        trait_ref, dest)
1173             } else {
1174                 bcx.tcx().sess.span_bug(expr.span,
1175                                         "expr_cast of non-trait");
1176             }
1177         }
1178         ast::ExprAssignOp(op, ref dst, ref src) => {
1179             trans_assign_op(bcx, expr, op, &**dst, &**src)
1180         }
1181         _ => {
1182             bcx.tcx().sess.span_bug(
1183                 expr.span,
1184                 &format!("trans_rvalue_dps_unadjusted reached fall-through \
1185                          case: {:?}",
1186                         expr.node)[]);
1187         }
1188     }
1189 }
1190
1191 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1192                                         ref_expr: &ast::Expr,
1193                                         def: def::Def,
1194                                         dest: Dest)
1195                                         -> Block<'blk, 'tcx> {
1196     let _icx = push_ctxt("trans_def_dps_unadjusted");
1197
1198     let lldest = match dest {
1199         SaveIn(lldest) => lldest,
1200         Ignore => { return bcx; }
1201     };
1202
1203     match def {
1204         def::DefVariant(tid, vid, _) => {
1205             let variant_info = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
1206             if variant_info.args.len() > 0u {
1207                 // N-ary variant.
1208                 let llfn = callee::trans_fn_ref(bcx.ccx(), vid,
1209                                                 ExprId(ref_expr.id),
1210                                                 bcx.fcx.param_substs).val;
1211                 Store(bcx, llfn, lldest);
1212                 return bcx;
1213             } else {
1214                 // Nullary variant.
1215                 let ty = expr_ty(bcx, ref_expr);
1216                 let repr = adt::represent_type(bcx.ccx(), ty);
1217                 adt::trans_set_discr(bcx, &*repr, lldest,
1218                                      variant_info.disr_val);
1219                 return bcx;
1220             }
1221         }
1222         def::DefStruct(_) => {
1223             let ty = expr_ty(bcx, ref_expr);
1224             match ty.sty {
1225                 ty::ty_struct(did, _) if ty::has_dtor(bcx.tcx(), did) => {
1226                     let repr = adt::represent_type(bcx.ccx(), ty);
1227                     adt::trans_set_discr(bcx, &*repr, lldest, 0);
1228                 }
1229                 _ => {}
1230             }
1231             bcx
1232         }
1233         _ => {
1234             bcx.tcx().sess.span_bug(ref_expr.span, &format!(
1235                 "Non-DPS def {:?} referened by {}",
1236                 def, bcx.node_id_to_string(ref_expr.id))[]);
1237         }
1238     }
1239 }
1240
1241 pub fn trans_def_fn_unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1242                                          ref_expr: &ast::Expr,
1243                                          def: def::Def,
1244                                          param_substs: &subst::Substs<'tcx>)
1245                                          -> Datum<'tcx, Rvalue> {
1246     let _icx = push_ctxt("trans_def_datum_unadjusted");
1247
1248     match def {
1249         def::DefFn(did, _) |
1250         def::DefStruct(did) | def::DefVariant(_, did, _) |
1251         def::DefStaticMethod(did, def::FromImpl(_)) |
1252         def::DefMethod(did, _, def::FromImpl(_)) => {
1253             callee::trans_fn_ref(ccx, did, ExprId(ref_expr.id), param_substs)
1254         }
1255         def::DefStaticMethod(impl_did, def::FromTrait(trait_did)) |
1256         def::DefMethod(impl_did, _, def::FromTrait(trait_did)) => {
1257             meth::trans_static_method_callee(ccx, impl_did,
1258                                              trait_did, ref_expr.id,
1259                                              param_substs)
1260         }
1261         _ => {
1262             ccx.tcx().sess.span_bug(ref_expr.span, &format!(
1263                     "trans_def_fn_unadjusted invoked on: {:?} for {}",
1264                     def,
1265                     ref_expr.repr(ccx.tcx()))[]);
1266         }
1267     }
1268 }
1269
1270 /// Translates a reference to a local variable or argument. This always results in an lvalue datum.
1271 pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1272                                    def: def::Def)
1273                                    -> Datum<'tcx, Lvalue> {
1274     let _icx = push_ctxt("trans_local_var");
1275
1276     match def {
1277         def::DefUpvar(nid, _, _) => {
1278             // Can't move upvars, so this is never a ZeroMemLastUse.
1279             let local_ty = node_id_type(bcx, nid);
1280             match bcx.fcx.llupvars.borrow().get(&nid) {
1281                 Some(&val) => Datum::new(val, local_ty, Lvalue),
1282                 None => {
1283                     bcx.sess().bug(&format!(
1284                         "trans_local_var: no llval for upvar {} found",
1285                         nid)[]);
1286                 }
1287             }
1288         }
1289         def::DefLocal(nid) => {
1290             let datum = match bcx.fcx.lllocals.borrow().get(&nid) {
1291                 Some(&v) => v,
1292                 None => {
1293                     bcx.sess().bug(&format!(
1294                         "trans_local_var: no datum for local/arg {} found",
1295                         nid)[]);
1296                 }
1297             };
1298             debug!("take_local(nid={}, v={}, ty={})",
1299                    nid, bcx.val_to_string(datum.val), bcx.ty_to_string(datum.ty));
1300             datum
1301         }
1302         _ => {
1303             bcx.sess().unimpl(&format!(
1304                 "unsupported def type in trans_local_var: {:?}",
1305                 def)[]);
1306         }
1307     }
1308 }
1309
1310 /// Helper for enumerating the field types of structs, enums, or records. The optional node ID here
1311 /// is the node ID of the path identifying the enum variant in use. If none, this cannot possibly
1312 /// an enum variant (so, if it is and `node_id_opt` is none, this function panics).
1313 pub fn with_field_tys<'tcx, R, F>(tcx: &ty::ctxt<'tcx>,
1314                                   ty: Ty<'tcx>,
1315                                   node_id_opt: Option<ast::NodeId>,
1316                                   op: F)
1317                                   -> R where
1318     F: FnOnce(ty::Disr, &[ty::field<'tcx>]) -> R,
1319 {
1320     match ty.sty {
1321         ty::ty_struct(did, substs) => {
1322             let fields = struct_fields(tcx, did, substs);
1323             let fields = monomorphize::normalize_associated_type(tcx, &fields);
1324             op(0, &fields[])
1325         }
1326
1327         ty::ty_tup(ref v) => {
1328             op(0, &tup_fields(&v[])[])
1329         }
1330
1331         ty::ty_enum(_, substs) => {
1332             // We want the *variant* ID here, not the enum ID.
1333             match node_id_opt {
1334                 None => {
1335                     tcx.sess.bug(&format!(
1336                         "cannot get field types from the enum type {} \
1337                          without a node ID",
1338                         ty.repr(tcx))[]);
1339                 }
1340                 Some(node_id) => {
1341                     let def = tcx.def_map.borrow()[node_id].clone();
1342                     match def {
1343                         def::DefVariant(enum_id, variant_id, _) => {
1344                             let variant_info = ty::enum_variant_with_id(
1345                                 tcx, enum_id, variant_id);
1346                             let fields = struct_fields(tcx, variant_id, substs);
1347                             let fields = monomorphize::normalize_associated_type(tcx, &fields);
1348                             op(variant_info.disr_val, &fields[])
1349                         }
1350                         _ => {
1351                             tcx.sess.bug("resolve didn't map this expr to a \
1352                                           variant ID")
1353                         }
1354                     }
1355                 }
1356             }
1357         }
1358
1359         _ => {
1360             tcx.sess.bug(&format!(
1361                 "cannot get field types from the type {}",
1362                 ty.repr(tcx))[]);
1363         }
1364     }
1365 }
1366
1367 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1368                             fields: &[ast::Field],
1369                             base: Option<&ast::Expr>,
1370                             expr_span: codemap::Span,
1371                             expr_id: ast::NodeId,
1372                             ty: Ty<'tcx>,
1373                             dest: Dest) -> Block<'blk, 'tcx> {
1374     let _icx = push_ctxt("trans_rec");
1375
1376     let tcx = bcx.tcx();
1377     with_field_tys(tcx, ty, Some(expr_id), |discr, field_tys| {
1378         let mut need_base: Vec<bool> = repeat(true).take(field_tys.len()).collect();
1379
1380         let numbered_fields = fields.iter().map(|field| {
1381             let opt_pos =
1382                 field_tys.iter().position(|field_ty|
1383                                           field_ty.name == field.ident.node.name);
1384             let result = match opt_pos {
1385                 Some(i) => {
1386                     need_base[i] = false;
1387                     (i, &*field.expr)
1388                 }
1389                 None => {
1390                     tcx.sess.span_bug(field.span,
1391                                       "Couldn't find field in struct type")
1392                 }
1393             };
1394             result
1395         }).collect::<Vec<_>>();
1396         let optbase = match base {
1397             Some(base_expr) => {
1398                 let mut leftovers = Vec::new();
1399                 for (i, b) in need_base.iter().enumerate() {
1400                     if *b {
1401                         leftovers.push((i, field_tys[i].mt.ty));
1402                     }
1403                 }
1404                 Some(StructBaseInfo {expr: base_expr,
1405                                      fields: leftovers })
1406             }
1407             None => {
1408                 if need_base.iter().any(|b| *b) {
1409                     tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1410                 }
1411                 None
1412             }
1413         };
1414
1415         trans_adt(bcx,
1416                   ty,
1417                   discr,
1418                   numbered_fields.as_slice(),
1419                   optbase,
1420                   dest,
1421                   Some(NodeInfo { id: expr_id, span: expr_span }))
1422     })
1423 }
1424
1425 /// Information that `trans_adt` needs in order to fill in the fields
1426 /// of a struct copied from a base struct (e.g., from an expression
1427 /// like `Foo { a: b, ..base }`.
1428 ///
1429 /// Note that `fields` may be empty; the base expression must always be
1430 /// evaluated for side-effects.
1431 pub struct StructBaseInfo<'a, 'tcx> {
1432     /// The base expression; will be evaluated after all explicit fields.
1433     expr: &'a ast::Expr,
1434     /// The indices of fields to copy paired with their types.
1435     fields: Vec<(uint, Ty<'tcx>)>
1436 }
1437
1438 /// Constructs an ADT instance:
1439 ///
1440 /// - `fields` should be a list of field indices paired with the
1441 /// expression to store into that field.  The initializers will be
1442 /// evaluated in the order specified by `fields`.
1443 ///
1444 /// - `optbase` contains information on the base struct (if any) from
1445 /// which remaining fields are copied; see comments on `StructBaseInfo`.
1446 pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1447                                  ty: Ty<'tcx>,
1448                                  discr: ty::Disr,
1449                                  fields: &[(uint, &ast::Expr)],
1450                                  optbase: Option<StructBaseInfo<'a, 'tcx>>,
1451                                  dest: Dest,
1452                                  source_location: Option<NodeInfo>)
1453                                  -> Block<'blk, 'tcx> {
1454     let _icx = push_ctxt("trans_adt");
1455     let fcx = bcx.fcx;
1456     let repr = adt::represent_type(bcx.ccx(), ty);
1457
1458     match source_location {
1459         Some(src_loc) => debuginfo::set_source_location(bcx.fcx,
1460                                                         src_loc.id,
1461                                                         src_loc.span),
1462         None => {}
1463     };
1464
1465     // If we don't care about the result, just make a
1466     // temporary stack slot
1467     let addr = match dest {
1468         SaveIn(pos) => pos,
1469         Ignore => alloc_ty(bcx, ty, "temp"),
1470     };
1471
1472     // This scope holds intermediates that must be cleaned should
1473     // panic occur before the ADT as a whole is ready.
1474     let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1475
1476     // First we trans the base, if we have one, to the dest
1477     for base in optbase.iter() {
1478         assert_eq!(discr, 0);
1479
1480         match ty::expr_kind(bcx.tcx(), &*base.expr) {
1481             ty::RvalueDpsExpr | ty::RvalueDatumExpr if !type_needs_drop(bcx.tcx(), ty) => {
1482                 bcx = trans_into(bcx, &*base.expr, SaveIn(addr));
1483             },
1484             ty::RvalueStmtExpr => bcx.tcx().sess.bug("unexpected expr kind for struct base expr"),
1485             _ => {
1486                 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base"));
1487                 for &(i, t) in base.fields.iter() {
1488                     let datum = base_datum.get_element(
1489                             bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i));
1490                     assert!(type_is_sized(bcx.tcx(), datum.ty));
1491                     let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1492                     bcx = datum.store_to(bcx, dest);
1493                 }
1494             }
1495         }
1496     }
1497
1498     match source_location {
1499         Some(src_loc) => debuginfo::set_source_location(bcx.fcx,
1500                                                         src_loc.id,
1501                                                         src_loc.span),
1502         None => {}
1503     };
1504
1505     if ty::type_is_simd(bcx.tcx(), ty) {
1506         // This is the constructor of a SIMD type, such types are
1507         // always primitive machine types and so do not have a
1508         // destructor or require any clean-up.
1509         let llty = type_of::type_of(bcx.ccx(), ty);
1510
1511         // keep a vector as a register, and running through the field
1512         // `insertelement`ing them directly into that register
1513         // (i.e. avoid GEPi and `store`s to an alloca) .
1514         let mut vec_val = C_undef(llty);
1515
1516         for &(i, ref e) in fields.iter() {
1517             let block_datum = trans(bcx, &**e);
1518             bcx = block_datum.bcx;
1519             let position = C_uint(bcx.ccx(), i);
1520             let value = block_datum.datum.to_llscalarish(bcx);
1521             vec_val = InsertElement(bcx, vec_val, value, position);
1522         }
1523         Store(bcx, vec_val, addr);
1524     } else {
1525         // Now, we just overwrite the fields we've explicitly specified
1526         for &(i, ref e) in fields.iter() {
1527             let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1528             let e_ty = expr_ty_adjusted(bcx, &**e);
1529             bcx = trans_into(bcx, &**e, SaveIn(dest));
1530             let scope = cleanup::CustomScope(custom_cleanup_scope);
1531             fcx.schedule_lifetime_end(scope, dest);
1532             fcx.schedule_drop_mem(scope, dest, e_ty);
1533         }
1534     }
1535
1536     adt::trans_set_discr(bcx, &*repr, addr, discr);
1537
1538     fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1539
1540     // If we don't care about the result drop the temporary we made
1541     match dest {
1542         SaveIn(_) => bcx,
1543         Ignore => {
1544             bcx = glue::drop_ty(bcx, addr, ty, source_location);
1545             base::call_lifetime_end(bcx, addr);
1546             bcx
1547         }
1548     }
1549 }
1550
1551
1552 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1553                                    expr: &ast::Expr,
1554                                    lit: &ast::Lit)
1555                                    -> DatumBlock<'blk, 'tcx, Expr> {
1556     // must not be a string constant, that is a RvalueDpsExpr
1557     let _icx = push_ctxt("trans_immediate_lit");
1558     let ty = expr_ty(bcx, expr);
1559     let v = consts::const_lit(bcx.ccx(), expr, lit);
1560     immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1561 }
1562
1563 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1564                            expr: &ast::Expr,
1565                            op: ast::UnOp,
1566                            sub_expr: &ast::Expr)
1567                            -> DatumBlock<'blk, 'tcx, Expr> {
1568     let ccx = bcx.ccx();
1569     let mut bcx = bcx;
1570     let _icx = push_ctxt("trans_unary_datum");
1571
1572     let method_call = MethodCall::expr(expr.id);
1573
1574     // The only overloaded operator that is translated to a datum
1575     // is an overloaded deref, since it is always yields a `&T`.
1576     // Otherwise, we should be in the RvalueDpsExpr path.
1577     assert!(
1578         op == ast::UnDeref ||
1579         !ccx.tcx().method_map.borrow().contains_key(&method_call));
1580
1581     let un_ty = expr_ty(bcx, expr);
1582
1583     match op {
1584         ast::UnNot => {
1585             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1586             let llresult = Not(bcx, datum.to_llscalarish(bcx));
1587             immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1588         }
1589         ast::UnNeg => {
1590             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1591             let val = datum.to_llscalarish(bcx);
1592             let llneg = {
1593                 if ty::type_is_fp(un_ty) {
1594                     FNeg(bcx, val)
1595                 } else {
1596                     Neg(bcx, val)
1597                 }
1598             };
1599             immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1600         }
1601         ast::UnUniq => {
1602             trans_uniq_expr(bcx, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1603         }
1604         ast::UnDeref => {
1605             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1606             deref_once(bcx, expr, datum, method_call)
1607         }
1608     }
1609 }
1610
1611 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1612                                box_ty: Ty<'tcx>,
1613                                contents: &ast::Expr,
1614                                contents_ty: Ty<'tcx>)
1615                                -> DatumBlock<'blk, 'tcx, Expr> {
1616     let _icx = push_ctxt("trans_uniq_expr");
1617     let fcx = bcx.fcx;
1618     assert!(type_is_sized(bcx.tcx(), contents_ty));
1619     let llty = type_of::type_of(bcx.ccx(), contents_ty);
1620     let size = llsize_of(bcx.ccx(), llty);
1621     let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty));
1622     let llty_ptr = llty.ptr_to();
1623     let Result { bcx, val } = malloc_raw_dyn(bcx, llty_ptr, box_ty, size, align);
1624     // Unique boxes do not allocate for zero-size types. The standard library
1625     // may assume that `free` is never called on the pointer returned for
1626     // `Box<ZeroSizeType>`.
1627     let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1628         trans_into(bcx, contents, SaveIn(val))
1629     } else {
1630         let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1631         fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1632                                 val, cleanup::HeapExchange, contents_ty);
1633         let bcx = trans_into(bcx, contents, SaveIn(val));
1634         fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1635         bcx
1636     };
1637     immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1638 }
1639
1640 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1641                              expr: &ast::Expr,
1642                              subexpr: &ast::Expr)
1643                              -> DatumBlock<'blk, 'tcx, Expr> {
1644     let _icx = push_ctxt("trans_addr_of");
1645     let mut bcx = bcx;
1646     let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1647     match sub_datum.ty.sty {
1648         ty::ty_open(_) => {
1649             // Opened DST value, close to a fat pointer
1650             debug!("Closing fat pointer {}", bcx.ty_to_string(sub_datum.ty));
1651
1652             let scratch = rvalue_scratch_datum(bcx,
1653                                                ty::close_type(bcx.tcx(), sub_datum.ty),
1654                                                "fat_addr_of");
1655             let base = Load(bcx, get_dataptr(bcx, sub_datum.val));
1656             Store(bcx, base, get_dataptr(bcx, scratch.val));
1657
1658             let len = Load(bcx, get_len(bcx, sub_datum.val));
1659             Store(bcx, len, get_len(bcx, scratch.val));
1660
1661             DatumBlock::new(bcx, scratch.to_expr_datum())
1662         }
1663         _ => {
1664             // Sized value, ref to a thin pointer
1665             let ty = expr_ty(bcx, expr);
1666             immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1667         }
1668     }
1669 }
1670
1671 // Important to get types for both lhs and rhs, because one might be _|_
1672 // and the other not.
1673 fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1674                                  binop_expr: &ast::Expr,
1675                                  binop_ty: Ty<'tcx>,
1676                                  op: ast::BinOp,
1677                                  lhs_t: Ty<'tcx>,
1678                                  lhs: ValueRef,
1679                                  rhs_t: Ty<'tcx>,
1680                                  rhs: ValueRef)
1681                                  -> DatumBlock<'blk, 'tcx, Expr> {
1682     let _icx = push_ctxt("trans_eager_binop");
1683
1684     let tcx = bcx.tcx();
1685     let is_simd = ty::type_is_simd(tcx, lhs_t);
1686     let intype = {
1687         if is_simd { ty::simd_type(tcx, lhs_t) }
1688         else { lhs_t }
1689     };
1690     let is_float = ty::type_is_fp(intype);
1691     let is_signed = ty::type_is_signed(intype);
1692
1693     let rhs = base::cast_shift_expr_rhs(bcx, op, lhs, rhs);
1694
1695     let mut bcx = bcx;
1696     let val = match op {
1697       ast::BiAdd => {
1698         if is_float { FAdd(bcx, lhs, rhs) }
1699         else { Add(bcx, lhs, rhs) }
1700       }
1701       ast::BiSub => {
1702         if is_float { FSub(bcx, lhs, rhs) }
1703         else { Sub(bcx, lhs, rhs) }
1704       }
1705       ast::BiMul => {
1706         if is_float { FMul(bcx, lhs, rhs) }
1707         else { Mul(bcx, lhs, rhs) }
1708       }
1709       ast::BiDiv => {
1710         if is_float {
1711             FDiv(bcx, lhs, rhs)
1712         } else {
1713             // Only zero-check integers; fp /0 is NaN
1714             bcx = base::fail_if_zero_or_overflows(bcx, binop_expr.span,
1715                                                   op, lhs, rhs, rhs_t);
1716             if is_signed {
1717                 SDiv(bcx, lhs, rhs)
1718             } else {
1719                 UDiv(bcx, lhs, rhs)
1720             }
1721         }
1722       }
1723       ast::BiRem => {
1724         if is_float {
1725             FRem(bcx, lhs, rhs)
1726         } else {
1727             // Only zero-check integers; fp %0 is NaN
1728             bcx = base::fail_if_zero_or_overflows(bcx, binop_expr.span,
1729                                                   op, lhs, rhs, rhs_t);
1730             if is_signed {
1731                 SRem(bcx, lhs, rhs)
1732             } else {
1733                 URem(bcx, lhs, rhs)
1734             }
1735         }
1736       }
1737       ast::BiBitOr => Or(bcx, lhs, rhs),
1738       ast::BiBitAnd => And(bcx, lhs, rhs),
1739       ast::BiBitXor => Xor(bcx, lhs, rhs),
1740       ast::BiShl => Shl(bcx, lhs, rhs),
1741       ast::BiShr => {
1742         if is_signed {
1743             AShr(bcx, lhs, rhs)
1744         } else { LShr(bcx, lhs, rhs) }
1745       }
1746       ast::BiEq | ast::BiNe | ast::BiLt | ast::BiGe | ast::BiLe | ast::BiGt => {
1747         if ty::type_is_scalar(rhs_t) {
1748             unpack_result!(bcx, base::compare_scalar_types(bcx, lhs, rhs, rhs_t, op))
1749         } else if is_simd {
1750             base::compare_simd_types(bcx, lhs, rhs, intype, ty::simd_size(tcx, lhs_t), op)
1751         } else {
1752             bcx.tcx().sess.span_bug(binop_expr.span, "comparison operator unsupported for type")
1753         }
1754       }
1755       _ => {
1756         bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1757       }
1758     };
1759
1760     immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1761 }
1762
1763 // refinement types would obviate the need for this
1764 enum lazy_binop_ty {
1765     lazy_and,
1766     lazy_or,
1767 }
1768
1769 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1770                                 binop_expr: &ast::Expr,
1771                                 op: lazy_binop_ty,
1772                                 a: &ast::Expr,
1773                                 b: &ast::Expr)
1774                                 -> DatumBlock<'blk, 'tcx, Expr> {
1775     let _icx = push_ctxt("trans_lazy_binop");
1776     let binop_ty = expr_ty(bcx, binop_expr);
1777     let fcx = bcx.fcx;
1778
1779     let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1780     let lhs = lhs.to_llscalarish(past_lhs);
1781
1782     if past_lhs.unreachable.get() {
1783         return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1784     }
1785
1786     let join = fcx.new_id_block("join", binop_expr.id);
1787     let before_rhs = fcx.new_id_block("before_rhs", b.id);
1788
1789     match op {
1790       lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb),
1791       lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb)
1792     }
1793
1794     let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1795     let rhs = rhs.to_llscalarish(past_rhs);
1796
1797     if past_rhs.unreachable.get() {
1798         return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1799     }
1800
1801     Br(past_rhs, join.llbb);
1802     let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1803                   &[past_lhs.llbb, past_rhs.llbb]);
1804
1805     return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1806 }
1807
1808 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1809                             expr: &ast::Expr,
1810                             op: ast::BinOp,
1811                             lhs: &ast::Expr,
1812                             rhs: &ast::Expr)
1813                             -> DatumBlock<'blk, 'tcx, Expr> {
1814     let _icx = push_ctxt("trans_binary");
1815     let ccx = bcx.ccx();
1816
1817     // if overloaded, would be RvalueDpsExpr
1818     assert!(!ccx.tcx().method_map.borrow().contains_key(&MethodCall::expr(expr.id)));
1819
1820     match op {
1821         ast::BiAnd => {
1822             trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1823         }
1824         ast::BiOr => {
1825             trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1826         }
1827         _ => {
1828             let mut bcx = bcx;
1829             let lhs_datum = unpack_datum!(bcx, trans(bcx, lhs));
1830             let rhs_datum = unpack_datum!(bcx, trans(bcx, rhs));
1831             let binop_ty = expr_ty(bcx, expr);
1832
1833             debug!("trans_binary (expr {}): lhs_datum={}",
1834                    expr.id,
1835                    lhs_datum.to_string(ccx));
1836             let lhs_ty = lhs_datum.ty;
1837             let lhs = lhs_datum.to_llscalarish(bcx);
1838
1839             debug!("trans_binary (expr {}): rhs_datum={}",
1840                    expr.id,
1841                    rhs_datum.to_string(ccx));
1842             let rhs_ty = rhs_datum.ty;
1843             let rhs = rhs_datum.to_llscalarish(bcx);
1844             trans_eager_binop(bcx, expr, binop_ty, op,
1845                               lhs_ty, lhs, rhs_ty, rhs)
1846         }
1847     }
1848 }
1849
1850 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1851                                    expr: &ast::Expr,
1852                                    method_call: MethodCall,
1853                                    lhs: Datum<'tcx, Expr>,
1854                                    rhs: Vec<(Datum<'tcx, Expr>, ast::NodeId)>,
1855                                    dest: Option<Dest>,
1856                                    autoref: bool)
1857                                    -> Result<'blk, 'tcx> {
1858     let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
1859     callee::trans_call_inner(bcx,
1860                              Some(expr_info(expr)),
1861                              monomorphize_type(bcx, method_ty),
1862                              |bcx, arg_cleanup_scope| {
1863                                 meth::trans_method_callee(bcx,
1864                                                           method_call,
1865                                                           None,
1866                                                           arg_cleanup_scope)
1867                              },
1868                              callee::ArgOverloadedOp(lhs, rhs, autoref),
1869                              dest)
1870 }
1871
1872 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1873                                          expr: &ast::Expr,
1874                                          callee: &'a ast::Expr,
1875                                          args: &'a [P<ast::Expr>],
1876                                          dest: Option<Dest>)
1877                                          -> Block<'blk, 'tcx> {
1878     let method_call = MethodCall::expr(expr.id);
1879     let method_type = (*bcx.tcx()
1880                            .method_map
1881                            .borrow())[method_call]
1882                            .ty;
1883     let mut all_args = vec!(callee);
1884     all_args.extend(args.iter().map(|e| &**e));
1885     unpack_result!(bcx,
1886                    callee::trans_call_inner(bcx,
1887                                             Some(expr_info(expr)),
1888                                             monomorphize_type(bcx,
1889                                                               method_type),
1890                                             |bcx, arg_cleanup_scope| {
1891                                                 meth::trans_method_callee(
1892                                                     bcx,
1893                                                     method_call,
1894                                                     None,
1895                                                     arg_cleanup_scope)
1896                                             },
1897                                             callee::ArgOverloadedCall(all_args),
1898                                             dest));
1899     bcx
1900 }
1901
1902 fn int_cast(bcx: Block,
1903             lldsttype: Type,
1904             llsrctype: Type,
1905             llsrc: ValueRef,
1906             signed: bool)
1907             -> ValueRef {
1908     let _icx = push_ctxt("int_cast");
1909     unsafe {
1910         let srcsz = llvm::LLVMGetIntTypeWidth(llsrctype.to_ref());
1911         let dstsz = llvm::LLVMGetIntTypeWidth(lldsttype.to_ref());
1912         return if dstsz == srcsz {
1913             BitCast(bcx, llsrc, lldsttype)
1914         } else if srcsz > dstsz {
1915             TruncOrBitCast(bcx, llsrc, lldsttype)
1916         } else if signed {
1917             SExtOrBitCast(bcx, llsrc, lldsttype)
1918         } else {
1919             ZExtOrBitCast(bcx, llsrc, lldsttype)
1920         };
1921     }
1922 }
1923
1924 fn float_cast(bcx: Block,
1925               lldsttype: Type,
1926               llsrctype: Type,
1927               llsrc: ValueRef)
1928               -> ValueRef {
1929     let _icx = push_ctxt("float_cast");
1930     let srcsz = llsrctype.float_width();
1931     let dstsz = lldsttype.float_width();
1932     return if dstsz > srcsz {
1933         FPExt(bcx, llsrc, lldsttype)
1934     } else if srcsz > dstsz {
1935         FPTrunc(bcx, llsrc, lldsttype)
1936     } else { llsrc };
1937 }
1938
1939 #[derive(Copy, PartialEq, Show)]
1940 pub enum cast_kind {
1941     cast_pointer,
1942     cast_integral,
1943     cast_float,
1944     cast_enum,
1945     cast_other,
1946 }
1947
1948 pub fn cast_type_kind<'tcx>(tcx: &ty::ctxt<'tcx>, t: Ty<'tcx>) -> cast_kind {
1949     match t.sty {
1950         ty::ty_char        => cast_integral,
1951         ty::ty_float(..)   => cast_float,
1952         ty::ty_rptr(_, mt) | ty::ty_ptr(mt) => {
1953             if type_is_sized(tcx, mt.ty) {
1954                 cast_pointer
1955             } else {
1956                 cast_other
1957             }
1958         }
1959         ty::ty_bare_fn(..) => cast_pointer,
1960         ty::ty_int(..)     => cast_integral,
1961         ty::ty_uint(..)    => cast_integral,
1962         ty::ty_bool        => cast_integral,
1963         ty::ty_enum(..)    => cast_enum,
1964         _                  => cast_other
1965     }
1966 }
1967
1968 fn cast_is_noop<'tcx>(t_in: Ty<'tcx>, t_out: Ty<'tcx>) -> bool {
1969     match (ty::deref(t_in, true), ty::deref(t_out, true)) {
1970         (Some(ty::mt{ ty: t_in, .. }), Some(ty::mt{ ty: t_out, .. })) => {
1971             t_in == t_out
1972         }
1973         _ => false
1974     }
1975 }
1976
1977 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1978                               expr: &ast::Expr,
1979                               id: ast::NodeId)
1980                               -> DatumBlock<'blk, 'tcx, Expr> {
1981     let _icx = push_ctxt("trans_cast");
1982     let mut bcx = bcx;
1983     let ccx = bcx.ccx();
1984
1985     let t_in = expr_ty(bcx, expr);
1986     let t_out = node_id_type(bcx, id);
1987     let k_in = cast_type_kind(bcx.tcx(), t_in);
1988     let k_out = cast_type_kind(bcx.tcx(), t_out);
1989     let s_in = k_in == cast_integral && ty::type_is_signed(t_in);
1990     let ll_t_in = type_of::arg_type_of(ccx, t_in);
1991     let ll_t_out = type_of::arg_type_of(ccx, t_out);
1992
1993     // Convert the value to be cast into a ValueRef, either by-ref or
1994     // by-value as appropriate given its type:
1995     let mut datum = unpack_datum!(bcx, trans(bcx, expr));
1996
1997     if cast_is_noop(datum.ty, t_out) {
1998         datum.ty = t_out;
1999         return DatumBlock::new(bcx, datum);
2000     }
2001
2002     let newval = match (k_in, k_out) {
2003         (cast_integral, cast_integral) => {
2004             let llexpr = datum.to_llscalarish(bcx);
2005             int_cast(bcx, ll_t_out, ll_t_in, llexpr, s_in)
2006         }
2007         (cast_float, cast_float) => {
2008             let llexpr = datum.to_llscalarish(bcx);
2009             float_cast(bcx, ll_t_out, ll_t_in, llexpr)
2010         }
2011         (cast_integral, cast_float) => {
2012             let llexpr = datum.to_llscalarish(bcx);
2013             if s_in {
2014                 SIToFP(bcx, llexpr, ll_t_out)
2015             } else { UIToFP(bcx, llexpr, ll_t_out) }
2016         }
2017         (cast_float, cast_integral) => {
2018             let llexpr = datum.to_llscalarish(bcx);
2019             if ty::type_is_signed(t_out) {
2020                 FPToSI(bcx, llexpr, ll_t_out)
2021             } else { FPToUI(bcx, llexpr, ll_t_out) }
2022         }
2023         (cast_integral, cast_pointer) => {
2024             let llexpr = datum.to_llscalarish(bcx);
2025             IntToPtr(bcx, llexpr, ll_t_out)
2026         }
2027         (cast_pointer, cast_integral) => {
2028             let llexpr = datum.to_llscalarish(bcx);
2029             PtrToInt(bcx, llexpr, ll_t_out)
2030         }
2031         (cast_pointer, cast_pointer) => {
2032             let llexpr = datum.to_llscalarish(bcx);
2033             PointerCast(bcx, llexpr, ll_t_out)
2034         }
2035         (cast_enum, cast_integral) |
2036         (cast_enum, cast_float) => {
2037             let mut bcx = bcx;
2038             let repr = adt::represent_type(ccx, t_in);
2039             let datum = unpack_datum!(
2040                 bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
2041             let llexpr_ptr = datum.to_llref();
2042             let lldiscrim_a =
2043                 adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
2044             match k_out {
2045                 cast_integral => int_cast(bcx, ll_t_out,
2046                                           val_ty(lldiscrim_a),
2047                                           lldiscrim_a, true),
2048                 cast_float => SIToFP(bcx, lldiscrim_a, ll_t_out),
2049                 _ => {
2050                     ccx.sess().bug(&format!("translating unsupported cast: \
2051                                             {} ({:?}) -> {} ({:?})",
2052                                             t_in.repr(bcx.tcx()),
2053                                             k_in,
2054                                             t_out.repr(bcx.tcx()),
2055                                             k_out)[])
2056                 }
2057             }
2058         }
2059         _ => ccx.sess().bug(&format!("translating unsupported cast: \
2060                                     {} ({:?}) -> {} ({:?})",
2061                                     t_in.repr(bcx.tcx()),
2062                                     k_in,
2063                                     t_out.repr(bcx.tcx()),
2064                                     k_out)[])
2065     };
2066     return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
2067 }
2068
2069 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2070                                expr: &ast::Expr,
2071                                op: ast::BinOp,
2072                                dst: &ast::Expr,
2073                                src: &ast::Expr)
2074                                -> Block<'blk, 'tcx> {
2075     let _icx = push_ctxt("trans_assign_op");
2076     let mut bcx = bcx;
2077
2078     debug!("trans_assign_op(expr={})", bcx.expr_to_string(expr));
2079
2080     // User-defined operator methods cannot be used with `+=` etc right now
2081     assert!(!bcx.tcx().method_map.borrow().contains_key(&MethodCall::expr(expr.id)));
2082
2083     // Evaluate LHS (destination), which should be an lvalue
2084     let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2085     assert!(!type_needs_drop(bcx.tcx(), dst_datum.ty));
2086     let dst_ty = dst_datum.ty;
2087     let dst = load_ty(bcx, dst_datum.val, dst_datum.ty);
2088
2089     // Evaluate RHS
2090     let rhs_datum = unpack_datum!(bcx, trans(bcx, &*src));
2091     let rhs_ty = rhs_datum.ty;
2092     let rhs = rhs_datum.to_llscalarish(bcx);
2093
2094     // Perform computation and store the result
2095     let result_datum = unpack_datum!(
2096         bcx, trans_eager_binop(bcx, expr, dst_datum.ty, op,
2097                                dst_ty, dst, rhs_ty, rhs));
2098     return result_datum.store_to(bcx, dst_datum.val);
2099 }
2100
2101 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2102                         datum: Datum<'tcx, Expr>,
2103                         expr: &ast::Expr)
2104                         -> DatumBlock<'blk, 'tcx, Expr> {
2105     let mut bcx = bcx;
2106
2107     // Ensure cleanup of `datum` if not already scheduled and obtain
2108     // a "by ref" pointer.
2109     let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2110
2111     // Compute final type. Note that we are loose with the region and
2112     // mutability, since those things don't matter in trans.
2113     let referent_ty = lv_datum.ty;
2114     let ptr_ty = ty::mk_imm_rptr(bcx.tcx(), bcx.tcx().mk_region(ty::ReStatic), referent_ty);
2115
2116     // Get the pointer.
2117     let llref = lv_datum.to_llref();
2118
2119     // Construct the resulting datum, using what was the "by ref"
2120     // ValueRef of type `referent_ty` to be the "by value" ValueRef
2121     // of type `&referent_ty`.
2122     DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(ByValue))))
2123 }
2124
2125 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2126                               expr: &ast::Expr,
2127                               datum: Datum<'tcx, Expr>,
2128                               times: uint)
2129                               -> DatumBlock<'blk, 'tcx, Expr> {
2130     let mut bcx = bcx;
2131     let mut datum = datum;
2132     for i in range(0, times) {
2133         let method_call = MethodCall::autoderef(expr.id, i);
2134         datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2135     }
2136     DatumBlock { bcx: bcx, datum: datum }
2137 }
2138
2139 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2140                           expr: &ast::Expr,
2141                           datum: Datum<'tcx, Expr>,
2142                           method_call: MethodCall)
2143                           -> DatumBlock<'blk, 'tcx, Expr> {
2144     let ccx = bcx.ccx();
2145
2146     debug!("deref_once(expr={}, datum={}, method_call={:?})",
2147            expr.repr(bcx.tcx()),
2148            datum.to_string(ccx),
2149            method_call);
2150
2151     let mut bcx = bcx;
2152
2153     // Check for overloaded deref.
2154     let method_ty = ccx.tcx().method_map.borrow()
2155                        .get(&method_call).map(|method| method.ty);
2156     let datum = match method_ty {
2157         Some(method_ty) => {
2158             let method_ty = monomorphize_type(bcx, method_ty);
2159
2160             // Overloaded. Evaluate `trans_overloaded_op`, which will
2161             // invoke the user's deref() method, which basically
2162             // converts from the `Smaht<T>` pointer that we have into
2163             // a `&T` pointer.  We can then proceed down the normal
2164             // path (below) to dereference that `&T`.
2165             let datum = match method_call.adjustment {
2166                 // Always perform an AutoPtr when applying an overloaded auto-deref
2167                 ty::AutoDeref(_) => unpack_datum!(bcx, auto_ref(bcx, datum, expr)),
2168                 _ => datum
2169             };
2170
2171             let ref_ty = // invoked methods have their LB regions instantiated
2172                 ty::assert_no_late_bound_regions(
2173                     ccx.tcx(), &ty::ty_fn_ret(method_ty)).unwrap();
2174             let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2175
2176             unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2177                                                     datum, Vec::new(), Some(SaveIn(scratch.val)),
2178                                                     false));
2179             scratch.to_expr_datum()
2180         }
2181         None => {
2182             // Not overloaded. We already have a pointer we know how to deref.
2183             datum
2184         }
2185     };
2186
2187     let r = match datum.ty.sty {
2188         ty::ty_uniq(content_ty) => {
2189             if type_is_sized(bcx.tcx(), content_ty) {
2190                 deref_owned_pointer(bcx, expr, datum, content_ty)
2191             } else {
2192                 // A fat pointer and an opened DST value have the same
2193                 // representation just different types. Since there is no
2194                 // temporary for `*e` here (because it is unsized), we cannot
2195                 // emulate the sized object code path for running drop glue and
2196                 // free. Instead, we schedule cleanup for `e`, turning it into
2197                 // an lvalue.
2198                 let datum = unpack_datum!(
2199                     bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2200
2201                 let datum = Datum::new(datum.val, ty::mk_open(bcx.tcx(), content_ty), LvalueExpr);
2202                 DatumBlock::new(bcx, datum)
2203             }
2204         }
2205
2206         ty::ty_ptr(ty::mt { ty: content_ty, .. }) |
2207         ty::ty_rptr(_, ty::mt { ty: content_ty, .. }) => {
2208             if type_is_sized(bcx.tcx(), content_ty) {
2209                 let ptr = datum.to_llscalarish(bcx);
2210
2211                 // Always generate an lvalue datum, even if datum.mode is
2212                 // an rvalue.  This is because datum.mode is only an
2213                 // rvalue for non-owning pointers like &T or *T, in which
2214                 // case cleanup *is* scheduled elsewhere, by the true
2215                 // owner (or, in the case of *T, by the user).
2216                 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr))
2217             } else {
2218                 // A fat pointer and an opened DST value have the same representation
2219                 // just different types.
2220                 DatumBlock::new(bcx, Datum::new(datum.val,
2221                                                 ty::mk_open(bcx.tcx(), content_ty),
2222                                                 LvalueExpr))
2223             }
2224         }
2225
2226         _ => {
2227             bcx.tcx().sess.span_bug(
2228                 expr.span,
2229                 &format!("deref invoked on expr of illegal type {}",
2230                         datum.ty.repr(bcx.tcx()))[]);
2231         }
2232     };
2233
2234     debug!("deref_once(expr={}, method_call={:?}, result={})",
2235            expr.id, method_call, r.datum.to_string(ccx));
2236
2237     return r;
2238
2239     /// We microoptimize derefs of owned pointers a bit here. Basically, the idea is to make the
2240     /// deref of an rvalue result in an rvalue. This helps to avoid intermediate stack slots in the
2241     /// resulting LLVM. The idea here is that, if the `Box<T>` pointer is an rvalue, then we can
2242     /// schedule a *shallow* free of the `Box<T>` pointer, and then return a ByRef rvalue into the
2243     /// pointer. Because the free is shallow, it is legit to return an rvalue, because we know that
2244     /// the contents are not yet scheduled to be freed. The language rules ensure that the contents
2245     /// will be used (or moved) before the free occurs.
2246     fn deref_owned_pointer<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2247                                        expr: &ast::Expr,
2248                                        datum: Datum<'tcx, Expr>,
2249                                        content_ty: Ty<'tcx>)
2250                                        -> DatumBlock<'blk, 'tcx, Expr> {
2251         match datum.kind {
2252             RvalueExpr(Rvalue { mode: ByRef }) => {
2253                 let scope = cleanup::temporary_scope(bcx.tcx(), expr.id);
2254                 let ptr = Load(bcx, datum.val);
2255                 if !type_is_zero_size(bcx.ccx(), content_ty) {
2256                     bcx.fcx.schedule_free_value(scope, ptr, cleanup::HeapExchange, content_ty);
2257                 }
2258             }
2259             RvalueExpr(Rvalue { mode: ByValue }) => {
2260                 let scope = cleanup::temporary_scope(bcx.tcx(), expr.id);
2261                 if !type_is_zero_size(bcx.ccx(), content_ty) {
2262                     bcx.fcx.schedule_free_value(scope, datum.val, cleanup::HeapExchange,
2263                                                 content_ty);
2264                 }
2265             }
2266             LvalueExpr => { }
2267         }
2268
2269         // If we had an rvalue in, we produce an rvalue out.
2270         let (llptr, kind) = match datum.kind {
2271             LvalueExpr => {
2272                 (Load(bcx, datum.val), LvalueExpr)
2273             }
2274             RvalueExpr(Rvalue { mode: ByRef }) => {
2275                 (Load(bcx, datum.val), RvalueExpr(Rvalue::new(ByRef)))
2276             }
2277             RvalueExpr(Rvalue { mode: ByValue }) => {
2278                 (datum.val, RvalueExpr(Rvalue::new(ByRef)))
2279             }
2280         };
2281
2282         let datum = Datum { ty: content_ty, val: llptr, kind: kind };
2283         DatumBlock { bcx: bcx, datum: datum }
2284     }
2285 }