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