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