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