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