]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/expr.rs
Auto merge of #28197 - petrochenkov:borrow, r=alexcrichton
[rust.git] / src / librustc_trans / trans / expr.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! # Translation of Expressions
12 //!
13 //! The expr module handles translation of expressions. The most general
14 //! translation routine is `trans()`, which will translate an expression
15 //! into a datum. `trans_into()` is also available, which will translate
16 //! an expression and write the result directly into memory, sometimes
17 //! avoiding the need for a temporary stack slot. Finally,
18 //! `trans_to_lvalue()` is available if you'd like to ensure that the
19 //! result has cleanup scheduled.
20 //!
21 //! Internally, each of these functions dispatches to various other
22 //! expression functions depending on the kind of expression. We divide
23 //! up expressions into:
24 //!
25 //! - **Datum expressions:** Those that most naturally yield values.
26 //!   Examples would be `22`, `box x`, or `a + b` (when not overloaded).
27 //! - **DPS expressions:** Those that most naturally write into a location
28 //!   in memory. Examples would be `foo()` or `Point { x: 3, y: 4 }`.
29 //! - **Statement expressions:** That that do not generate a meaningful
30 //!   result. Examples would be `while { ... }` or `return 44`.
31 //!
32 //! Public entry points:
33 //!
34 //! - `trans_into(bcx, expr, dest) -> bcx`: evaluates an expression,
35 //!   storing the result into `dest`. This is the preferred form, if you
36 //!   can manage it.
37 //!
38 //! - `trans(bcx, expr) -> DatumBlock`: evaluates an expression, yielding
39 //!   `Datum` with the result. You can then store the datum, inspect
40 //!   the value, etc. This may introduce temporaries if the datum is a
41 //!   structural type.
42 //!
43 //! - `trans_to_lvalue(bcx, expr, "...") -> DatumBlock`: evaluates an
44 //!   expression and ensures that the result has a cleanup associated with it,
45 //!   creating a temporary stack slot if necessary.
46 //!
47 //! - `trans_local_var -> Datum`: looks up a local variable or upvar.
48
49 #![allow(non_camel_case_types)]
50
51 pub use self::Dest::*;
52 use self::lazy_binop_ty::*;
53
54 use back::abi;
55 use llvm::{self, ValueRef, TypeKind};
56 use middle::check_const;
57 use middle::def;
58 use middle::lang_items::CoerceUnsizedTraitLangItem;
59 use middle::subst::{Substs, VecPerParamSpace};
60 use middle::traits;
61 use trans::{_match, adt, asm, base, callee, closure, consts, controlflow};
62 use trans::base::*;
63 use trans::build::*;
64 use trans::cleanup::{self, CleanupMethods, DropHintMethods};
65 use trans::common::*;
66 use trans::datum::*;
67 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
68 use trans::declare;
69 use trans::glue;
70 use trans::machine;
71 use trans::meth;
72 use trans::tvec;
73 use trans::type_of;
74 use middle::cast::{CastKind, CastTy};
75 use middle::ty::{AdjustDerefRef, AdjustReifyFnPointer, AdjustUnsafeFnPointer};
76 use middle::ty::{self, Ty};
77 use middle::ty::MethodCall;
78 use util::common::indenter;
79 use trans::machine::{llsize_of, llsize_of_alloc};
80 use trans::type_::Type;
81
82 use rustc_front;
83 use rustc_front::hir;
84
85 use syntax::{ast, codemap};
86 use syntax::parse::token::InternedString;
87 use syntax::ptr::P;
88 use syntax::parse::token;
89 use std::mem;
90
91 // Destinations
92
93 // These are passed around by the code generating functions to track the
94 // destination of a computation's value.
95
96 #[derive(Copy, Clone, PartialEq)]
97 pub enum Dest {
98     SaveIn(ValueRef),
99     Ignore,
100 }
101
102 impl Dest {
103     pub fn to_string(&self, ccx: &CrateContext) -> String {
104         match *self {
105             SaveIn(v) => format!("SaveIn({})", ccx.tn().val_to_string(v)),
106             Ignore => "Ignore".to_string()
107         }
108     }
109 }
110
111 /// This function is equivalent to `trans(bcx, expr).store_to_dest(dest)` but it may generate
112 /// better optimized LLVM code.
113 pub fn trans_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
114                               expr: &hir::Expr,
115                               dest: Dest)
116                               -> Block<'blk, 'tcx> {
117     let mut bcx = bcx;
118
119     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
120
121     if bcx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
122         // use trans, which may be less efficient but
123         // which will perform the adjustments:
124         let datum = unpack_datum!(bcx, trans(bcx, expr));
125         return datum.store_to_dest(bcx, dest, expr.id);
126     }
127
128     let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
129     if !qualif.intersects(
130         check_const::ConstQualif::NOT_CONST |
131         check_const::ConstQualif::NEEDS_DROP
132     ) {
133         if !qualif.intersects(check_const::ConstQualif::PREFER_IN_PLACE) {
134             if let SaveIn(lldest) = dest {
135                 let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
136                                                             bcx.fcx.param_substs);
137                 // Cast pointer to destination, because constants
138                 // have different types.
139                 let lldest = PointerCast(bcx, lldest, val_ty(global));
140                 memcpy_ty(bcx, lldest, global, expr_ty_adjusted(bcx, expr));
141                 return bcx;
142             }
143             // Even if we don't have a value to emit, and the expression
144             // doesn't have any side-effects, we still have to translate the
145             // body of any closures.
146             // FIXME: Find a better way of handling this case.
147         } else {
148             // The only way we're going to see a `const` at this point is if
149             // it prefers in-place instantiation, likely because it contains
150             // `[x; N]` somewhere within.
151             match expr.node {
152                 hir::ExprPath(..) => {
153                     match bcx.def(expr.id) {
154                         def::DefConst(did) => {
155                             let const_expr = consts::get_const_expr(bcx.ccx(), did, expr);
156                             // Temporarily get cleanup scopes out of the way,
157                             // as they require sub-expressions to be contained
158                             // inside the current AST scope.
159                             // These should record no cleanups anyways, `const`
160                             // can't have destructors.
161                             let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
162                                                       vec![]);
163                             // Lock emitted debug locations to the location of
164                             // the constant reference expression.
165                             debuginfo::with_source_location_override(bcx.fcx,
166                                                                      expr.debug_loc(),
167                                                                      || {
168                                 bcx = trans_into(bcx, const_expr, dest)
169                             });
170                             let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
171                                                       scopes);
172                             assert!(scopes.is_empty());
173                             return bcx;
174                         }
175                         _ => {}
176                     }
177                 }
178                 _ => {}
179             }
180         }
181     }
182
183     debug!("trans_into() expr={:?}", expr);
184
185     let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
186                                                                           expr.id,
187                                                                           expr.span,
188                                                                           false);
189     bcx.fcx.push_ast_cleanup_scope(cleanup_debug_loc);
190
191     let kind = expr_kind(bcx.tcx(), expr);
192     bcx = match kind {
193         ExprKind::Lvalue | ExprKind::RvalueDatum => {
194             trans_unadjusted(bcx, expr).store_to_dest(dest, expr.id)
195         }
196         ExprKind::RvalueDps => {
197             trans_rvalue_dps_unadjusted(bcx, expr, dest)
198         }
199         ExprKind::RvalueStmt => {
200             trans_rvalue_stmt_unadjusted(bcx, expr)
201         }
202     };
203
204     bcx.fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id)
205 }
206
207 /// Translates an expression, returning a datum (and new block) encapsulating the result. When
208 /// possible, it is preferred to use `trans_into`, as that may avoid creating a temporary on the
209 /// stack.
210 pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
211                          expr: &hir::Expr)
212                          -> DatumBlock<'blk, 'tcx, Expr> {
213     debug!("trans(expr={:?})", expr);
214
215     let mut bcx = bcx;
216     let fcx = bcx.fcx;
217     let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
218     let adjusted_global = !qualif.intersects(check_const::ConstQualif::NON_STATIC_BORROWS);
219     let global = if !qualif.intersects(
220         check_const::ConstQualif::NOT_CONST |
221         check_const::ConstQualif::NEEDS_DROP
222     ) {
223         let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
224                                                       bcx.fcx.param_substs);
225
226         if qualif.intersects(check_const::ConstQualif::HAS_STATIC_BORROWS) {
227             // Is borrowed as 'static, must return lvalue.
228
229             // Cast pointer to global, because constants have different types.
230             let const_ty = expr_ty_adjusted(bcx, expr);
231             let llty = type_of::type_of(bcx.ccx(), const_ty);
232             let global = PointerCast(bcx, global, llty.ptr_to());
233             let datum = Datum::new(global, const_ty, Lvalue::new("expr::trans"));
234             return DatumBlock::new(bcx, datum.to_expr_datum());
235         }
236
237         // Otherwise, keep around and perform adjustments, if needed.
238         let const_ty = if adjusted_global {
239             expr_ty_adjusted(bcx, expr)
240         } else {
241             expr_ty(bcx, expr)
242         };
243
244         // This could use a better heuristic.
245         Some(if type_is_immediate(bcx.ccx(), const_ty) {
246             // Cast pointer to global, because constants have different types.
247             let llty = type_of::type_of(bcx.ccx(), const_ty);
248             let global = PointerCast(bcx, global, llty.ptr_to());
249             // Maybe just get the value directly, instead of loading it?
250             immediate_rvalue(load_ty(bcx, global, const_ty), const_ty)
251         } else {
252             let scratch = alloc_ty(bcx, const_ty, "const");
253             call_lifetime_start(bcx, scratch);
254             let lldest = if !const_ty.is_structural() {
255                 // Cast pointer to slot, because constants have different types.
256                 PointerCast(bcx, scratch, val_ty(global))
257             } else {
258                 // In this case, memcpy_ty calls llvm.memcpy after casting both
259                 // source and destination to i8*, so we don't need any casts.
260                 scratch
261             };
262             memcpy_ty(bcx, lldest, global, const_ty);
263             Datum::new(scratch, const_ty, Rvalue::new(ByRef))
264         })
265     } else {
266         None
267     };
268
269     let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
270                                                                           expr.id,
271                                                                           expr.span,
272                                                                           false);
273     fcx.push_ast_cleanup_scope(cleanup_debug_loc);
274     let datum = match global {
275         Some(rvalue) => rvalue.to_expr_datum(),
276         None => unpack_datum!(bcx, trans_unadjusted(bcx, expr))
277     };
278     let datum = if adjusted_global {
279         datum // trans::consts already performed adjustments.
280     } else {
281         unpack_datum!(bcx, apply_adjustments(bcx, expr, datum))
282     };
283     bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id);
284     return DatumBlock::new(bcx, datum);
285 }
286
287 pub fn get_meta(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
288     StructGEP(bcx, fat_ptr, abi::FAT_PTR_EXTRA)
289 }
290
291 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
292     StructGEP(bcx, fat_ptr, abi::FAT_PTR_ADDR)
293 }
294
295 pub fn copy_fat_ptr(bcx: Block, src_ptr: ValueRef, dst_ptr: ValueRef) {
296     Store(bcx, Load(bcx, get_dataptr(bcx, src_ptr)), get_dataptr(bcx, dst_ptr));
297     Store(bcx, Load(bcx, get_meta(bcx, src_ptr)), get_meta(bcx, dst_ptr));
298 }
299
300 /// Retrieve the information we are losing (making dynamic) in an unsizing
301 /// adjustment.
302 ///
303 /// The `old_info` argument is a bit funny. It is intended for use
304 /// in an upcast, where the new vtable for an object will be drived
305 /// from the old one.
306 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
307                                 source: Ty<'tcx>,
308                                 target: Ty<'tcx>,
309                                 old_info: Option<ValueRef>,
310                                 param_substs: &'tcx Substs<'tcx>)
311                                 -> ValueRef {
312     let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
313     match (&source.sty, &target.sty) {
314         (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
315         (&ty::TyTrait(_), &ty::TyTrait(_)) => {
316             // For now, upcasts are limited to changes in marker
317             // traits, and hence never actually require an actual
318             // change to the vtable.
319             old_info.expect("unsized_info: missing old info for trait upcast")
320         }
321         (_, &ty::TyTrait(box ty::TraitTy { ref principal, .. })) => {
322             // Note that we preserve binding levels here:
323             let substs = principal.0.substs.with_self_ty(source).erase_regions();
324             let substs = ccx.tcx().mk_substs(substs);
325             let trait_ref = ty::Binder(ty::TraitRef { def_id: principal.def_id(),
326                                                       substs: substs });
327             consts::ptrcast(meth::get_vtable(ccx, trait_ref, param_substs),
328                             Type::vtable_ptr(ccx))
329         }
330         _ => ccx.sess().bug(&format!("unsized_info: invalid unsizing {:?} -> {:?}",
331                                      source,
332                                      target))
333     }
334 }
335
336 /// Helper for trans that apply adjustments from `expr` to `datum`, which should be the unadjusted
337 /// translation of `expr`.
338 fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
339                                  expr: &hir::Expr,
340                                  datum: Datum<'tcx, Expr>)
341                                  -> DatumBlock<'blk, 'tcx, Expr>
342 {
343     let mut bcx = bcx;
344     let mut datum = datum;
345     let adjustment = match bcx.tcx().tables.borrow().adjustments.get(&expr.id).cloned() {
346         None => {
347             return DatumBlock::new(bcx, datum);
348         }
349         Some(adj) => { adj }
350     };
351     debug!("unadjusted datum for expr {:?}: {} adjustment={:?}",
352            expr,
353            datum.to_string(bcx.ccx()),
354            adjustment);
355     match adjustment {
356         AdjustReifyFnPointer => {
357             // FIXME(#19925) once fn item types are
358             // zero-sized, we'll need to do something here
359         }
360         AdjustUnsafeFnPointer => {
361             // purely a type-level thing
362         }
363         AdjustDerefRef(ref adj) => {
364             let skip_reborrows = if adj.autoderefs == 1 && adj.autoref.is_some() {
365                 // We are a bit paranoid about adjustments and thus might have a re-
366                 // borrow here which merely derefs and then refs again (it might have
367                 // a different region or mutability, but we don't care here).
368                 match datum.ty.sty {
369                     // Don't skip a conversion from Box<T> to &T, etc.
370                     ty::TyRef(..) => {
371                         if bcx.tcx().is_overloaded_autoderef(expr.id, 0) {
372                             // Don't skip an overloaded deref.
373                             0
374                         } else {
375                             1
376                         }
377                     }
378                     _ => 0
379                 }
380             } else {
381                 0
382             };
383
384             if adj.autoderefs > skip_reborrows {
385                 // Schedule cleanup.
386                 let lval = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "auto_deref", expr.id));
387                 datum = unpack_datum!(bcx, deref_multiple(bcx, expr,
388                                                           lval.to_expr_datum(),
389                                                           adj.autoderefs - skip_reborrows));
390             }
391
392             // (You might think there is a more elegant way to do this than a
393             // skip_reborrows bool, but then you remember that the borrow checker exists).
394             if skip_reborrows == 0 && adj.autoref.is_some() {
395                 datum = unpack_datum!(bcx, auto_ref(bcx, datum, expr));
396             }
397
398             if let Some(target) = adj.unsize {
399                 // We do not arrange cleanup ourselves; if we already are an
400                 // L-value, then cleanup will have already been scheduled (and
401                 // the `datum.to_rvalue_datum` call below will emit code to zero
402                 // the drop flag when moving out of the L-value). If we are an
403                 // R-value, then we do not need to schedule cleanup.
404                 let source_datum = unpack_datum!(bcx,
405                     datum.to_rvalue_datum(bcx, "__coerce_source"));
406
407                 let target = bcx.monomorphize(&target);
408
409                 let scratch = alloc_ty(bcx, target, "__coerce_target");
410                 call_lifetime_start(bcx, scratch);
411                 let target_datum = Datum::new(scratch, target,
412                                               Rvalue::new(ByRef));
413                 bcx = coerce_unsized(bcx, expr.span, source_datum, target_datum);
414                 datum = Datum::new(scratch, target,
415                                    RvalueExpr(Rvalue::new(ByRef)));
416             }
417         }
418     }
419     debug!("after adjustments, datum={}", datum.to_string(bcx.ccx()));
420     DatumBlock::new(bcx, datum)
421 }
422
423 fn coerce_unsized<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
424                               span: codemap::Span,
425                               source: Datum<'tcx, Rvalue>,
426                               target: Datum<'tcx, Rvalue>)
427                               -> Block<'blk, 'tcx> {
428     let mut bcx = bcx;
429     debug!("coerce_unsized({} -> {})",
430            source.to_string(bcx.ccx()),
431            target.to_string(bcx.ccx()));
432
433     match (&source.ty.sty, &target.ty.sty) {
434         (&ty::TyBox(a), &ty::TyBox(b)) |
435         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
436          &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
437         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
438          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
439         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
440          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
441             let (inner_source, inner_target) = (a, b);
442
443             let (base, old_info) = if !type_is_sized(bcx.tcx(), inner_source) {
444                 // Normally, the source is a thin pointer and we are
445                 // adding extra info to make a fat pointer. The exception
446                 // is when we are upcasting an existing object fat pointer
447                 // to use a different vtable. In that case, we want to
448                 // load out the original data pointer so we can repackage
449                 // it.
450                 (Load(bcx, get_dataptr(bcx, source.val)),
451                 Some(Load(bcx, get_meta(bcx, source.val))))
452             } else {
453                 let val = if source.kind.is_by_ref() {
454                     load_ty(bcx, source.val, source.ty)
455                 } else {
456                     source.val
457                 };
458                 (val, None)
459             };
460
461             let info = unsized_info(bcx.ccx(), inner_source, inner_target,
462                                     old_info, bcx.fcx.param_substs);
463
464             // Compute the base pointer. This doesn't change the pointer value,
465             // but merely its type.
466             let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), inner_target).ptr_to();
467             let base = PointerCast(bcx, base, ptr_ty);
468
469             Store(bcx, base, get_dataptr(bcx, target.val));
470             Store(bcx, info, get_meta(bcx, target.val));
471         }
472
473         // This can be extended to enums and tuples in the future.
474         // (&ty::TyEnum(def_id_a, _), &ty::TyEnum(def_id_b, _)) |
475         (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
476             assert_eq!(def_id_a, def_id_b);
477
478             // The target is already by-ref because it's to be written to.
479             let source = unpack_datum!(bcx, source.to_ref_datum(bcx));
480             assert!(target.kind.is_by_ref());
481
482             let trait_substs = Substs::erased(VecPerParamSpace::new(vec![target.ty],
483                                                                     vec![source.ty],
484                                                                     Vec::new()));
485             let trait_ref = ty::Binder(ty::TraitRef {
486                 def_id: langcall(bcx, Some(span), "coercion",
487                                  CoerceUnsizedTraitLangItem),
488                 substs: bcx.tcx().mk_substs(trait_substs)
489             });
490
491             let kind = match fulfill_obligation(bcx.ccx(), span, trait_ref) {
492                 traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
493                     bcx.tcx().custom_coerce_unsized_kind(impl_def_id)
494                 }
495                 vtable => {
496                     bcx.sess().span_bug(span, &format!("invalid CoerceUnsized vtable: {:?}",
497                                                        vtable));
498                 }
499             };
500
501             let repr_source = adt::represent_type(bcx.ccx(), source.ty);
502             let src_fields = match &*repr_source {
503                 &adt::Repr::Univariant(ref s, _) => &s.fields,
504                 _ => bcx.sess().span_bug(span,
505                                          &format!("Non univariant struct? (repr_source: {:?})",
506                                                   repr_source)),
507             };
508             let repr_target = adt::represent_type(bcx.ccx(), target.ty);
509             let target_fields = match &*repr_target {
510                 &adt::Repr::Univariant(ref s, _) => &s.fields,
511                 _ => bcx.sess().span_bug(span,
512                                          &format!("Non univariant struct? (repr_target: {:?})",
513                                                   repr_target)),
514             };
515
516             let coerce_index = match kind {
517                 ty::CustomCoerceUnsized::Struct(i) => i
518             };
519             assert!(coerce_index < src_fields.len() && src_fields.len() == target_fields.len());
520
521             let iter = src_fields.iter().zip(target_fields).enumerate();
522             for (i, (src_ty, target_ty)) in iter {
523                 let ll_source = adt::trans_field_ptr(bcx, &repr_source, source.val, 0, i);
524                 let ll_target = adt::trans_field_ptr(bcx, &repr_target, target.val, 0, i);
525
526                 // If this is the field we need to coerce, recurse on it.
527                 if i == coerce_index {
528                     coerce_unsized(bcx, span,
529                                    Datum::new(ll_source, src_ty,
530                                               Rvalue::new(ByRef)),
531                                    Datum::new(ll_target, target_ty,
532                                               Rvalue::new(ByRef)));
533                 } else {
534                     // Otherwise, simply copy the data from the source.
535                     assert_eq!(src_ty, target_ty);
536                     memcpy_ty(bcx, ll_target, ll_source, src_ty);
537                 }
538             }
539         }
540         _ => bcx.sess().bug(&format!("coerce_unsized: invalid coercion {:?} -> {:?}",
541                                      source.ty,
542                                      target.ty))
543     }
544     bcx
545 }
546
547 /// Translates an expression in "lvalue" mode -- meaning that it returns a reference to the memory
548 /// that the expr represents.
549 ///
550 /// If this expression is an rvalue, this implies introducing a temporary.  In other words,
551 /// something like `x().f` is translated into roughly the equivalent of
552 ///
553 ///   { tmp = x(); tmp.f }
554 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
555                                    expr: &hir::Expr,
556                                    name: &str)
557                                    -> DatumBlock<'blk, 'tcx, Lvalue> {
558     let mut bcx = bcx;
559     let datum = unpack_datum!(bcx, trans(bcx, expr));
560     return datum.to_lvalue_datum(bcx, name, expr.id);
561 }
562
563 /// A version of `trans` that ignores adjustments. You almost certainly do not want to call this
564 /// directly.
565 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
566                                 expr: &hir::Expr)
567                                 -> DatumBlock<'blk, 'tcx, Expr> {
568     let mut bcx = bcx;
569
570     debug!("trans_unadjusted(expr={:?})", expr);
571     let _indenter = indenter();
572
573     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
574
575     return match expr_kind(bcx.tcx(), expr) {
576         ExprKind::Lvalue | ExprKind::RvalueDatum => {
577             let datum = unpack_datum!(bcx, {
578                 trans_datum_unadjusted(bcx, expr)
579             });
580
581             DatumBlock {bcx: bcx, datum: datum}
582         }
583
584         ExprKind::RvalueStmt => {
585             bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
586             nil(bcx, expr_ty(bcx, expr))
587         }
588
589         ExprKind::RvalueDps => {
590             let ty = expr_ty(bcx, expr);
591             if type_is_zero_size(bcx.ccx(), ty) {
592                 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
593                 nil(bcx, ty)
594             } else {
595                 let scratch = rvalue_scratch_datum(bcx, ty, "");
596                 bcx = trans_rvalue_dps_unadjusted(
597                     bcx, expr, SaveIn(scratch.val));
598
599                 // Note: this is not obviously a good idea.  It causes
600                 // immediate values to be loaded immediately after a
601                 // return from a call or other similar expression,
602                 // which in turn leads to alloca's having shorter
603                 // lifetimes and hence larger stack frames.  However,
604                 // in turn it can lead to more register pressure.
605                 // Still, in practice it seems to increase
606                 // performance, since we have fewer problems with
607                 // morestack churn.
608                 let scratch = unpack_datum!(
609                     bcx, scratch.to_appropriate_datum(bcx));
610
611                 DatumBlock::new(bcx, scratch.to_expr_datum())
612             }
613         }
614     };
615
616     fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: Ty<'tcx>)
617                        -> DatumBlock<'blk, 'tcx, Expr> {
618         let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
619         let datum = immediate_rvalue(llval, ty);
620         DatumBlock::new(bcx, datum.to_expr_datum())
621     }
622 }
623
624 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
625                                       expr: &hir::Expr)
626                                       -> DatumBlock<'blk, 'tcx, Expr> {
627     let mut bcx = bcx;
628     let fcx = bcx.fcx;
629     let _icx = push_ctxt("trans_datum_unadjusted");
630
631     match expr.node {
632         hir::ExprParen(ref e) => {
633             trans(bcx, &**e)
634         }
635         hir::ExprPath(..) => {
636             trans_def(bcx, expr, bcx.def(expr.id))
637         }
638         hir::ExprField(ref base, ident) => {
639             trans_rec_field(bcx, &**base, ident.node.name)
640         }
641         hir::ExprTupField(ref base, idx) => {
642             trans_rec_tup_field(bcx, &**base, idx.node)
643         }
644         hir::ExprIndex(ref base, ref idx) => {
645             trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id))
646         }
647         hir::ExprBox(_, ref contents) => {
648             // Special case for `Box<T>`
649             let box_ty = expr_ty(bcx, expr);
650             let contents_ty = expr_ty(bcx, &**contents);
651             match box_ty.sty {
652                 ty::TyBox(..) => {
653                     trans_uniq_expr(bcx, expr, box_ty, &**contents, contents_ty)
654                 }
655                 _ => bcx.sess().span_bug(expr.span,
656                                          "expected unique box")
657             }
658
659         }
660         hir::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, &**lit),
661         hir::ExprBinary(op, ref lhs, ref rhs) => {
662             trans_binary(bcx, expr, op, &**lhs, &**rhs)
663         }
664         hir::ExprUnary(op, ref x) => {
665             trans_unary(bcx, expr, op, &**x)
666         }
667         hir::ExprAddrOf(_, ref x) => {
668             match x.node {
669                 hir::ExprRepeat(..) | hir::ExprVec(..) => {
670                     // Special case for slices.
671                     let cleanup_debug_loc =
672                         debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
673                                                                       x.id,
674                                                                       x.span,
675                                                                       false);
676                     fcx.push_ast_cleanup_scope(cleanup_debug_loc);
677                     let datum = unpack_datum!(
678                         bcx, tvec::trans_slice_vec(bcx, expr, &**x));
679                     bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
680                     DatumBlock::new(bcx, datum)
681                 }
682                 _ => {
683                     trans_addr_of(bcx, expr, &**x)
684                 }
685             }
686         }
687         hir::ExprCast(ref val, _) => {
688             // Datum output mode means this is a scalar cast:
689             trans_imm_cast(bcx, &**val, expr.id)
690         }
691         _ => {
692             bcx.tcx().sess.span_bug(
693                 expr.span,
694                 &format!("trans_rvalue_datum_unadjusted reached \
695                          fall-through case: {:?}",
696                         expr.node));
697         }
698     }
699 }
700
701 fn trans_field<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
702                               base: &hir::Expr,
703                               get_idx: F)
704                               -> DatumBlock<'blk, 'tcx, Expr> where
705     F: FnOnce(&'blk ty::ctxt<'tcx>, &VariantInfo<'tcx>) -> usize,
706 {
707     let mut bcx = bcx;
708     let _icx = push_ctxt("trans_rec_field");
709
710     let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
711     let bare_ty = base_datum.ty;
712     let repr = adt::represent_type(bcx.ccx(), bare_ty);
713     let vinfo = VariantInfo::from_ty(bcx.tcx(), bare_ty, None);
714
715     let ix = get_idx(bcx.tcx(), &vinfo);
716     let d = base_datum.get_element(
717         bcx,
718         vinfo.fields[ix].1,
719         |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, vinfo.discr, ix));
720
721     if type_is_sized(bcx.tcx(), d.ty) {
722         DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
723     } else {
724         let scratch = rvalue_scratch_datum(bcx, d.ty, "");
725         Store(bcx, d.val, get_dataptr(bcx, scratch.val));
726         let info = Load(bcx, get_meta(bcx, base_datum.val));
727         Store(bcx, info, get_meta(bcx, scratch.val));
728
729         // Always generate an lvalue datum, because this pointer doesn't own
730         // the data and cleanup is scheduled elsewhere.
731         DatumBlock::new(bcx, Datum::new(scratch.val, scratch.ty, LvalueExpr(d.kind)))
732     }
733 }
734
735 /// Translates `base.field`.
736 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
737                                base: &hir::Expr,
738                                field: ast::Name)
739                                -> DatumBlock<'blk, 'tcx, Expr> {
740     trans_field(bcx, base, |_, vinfo| vinfo.field_index(field))
741 }
742
743 /// Translates `base.<idx>`.
744 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
745                                    base: &hir::Expr,
746                                    idx: usize)
747                                    -> DatumBlock<'blk, 'tcx, Expr> {
748     trans_field(bcx, base, |_, _| idx)
749 }
750
751 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
752                            index_expr: &hir::Expr,
753                            base: &hir::Expr,
754                            idx: &hir::Expr,
755                            method_call: MethodCall)
756                            -> DatumBlock<'blk, 'tcx, Expr> {
757     //! Translates `base[idx]`.
758
759     let _icx = push_ctxt("trans_index");
760     let ccx = bcx.ccx();
761     let mut bcx = bcx;
762
763     let index_expr_debug_loc = index_expr.debug_loc();
764
765     // Check for overloaded index.
766     let method_ty = ccx.tcx()
767                        .tables
768                        .borrow()
769                        .method_map
770                        .get(&method_call)
771                        .map(|method| method.ty);
772     let elt_datum = match method_ty {
773         Some(method_ty) => {
774             let method_ty = monomorphize_type(bcx, method_ty);
775
776             let base_datum = unpack_datum!(bcx, trans(bcx, base));
777
778             // Translate index expression.
779             let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
780
781             let ref_ty = // invoked methods have LB regions instantiated:
782                 bcx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
783             let elt_ty = match ref_ty.builtin_deref(true, ty::NoPreference) {
784                 None => {
785                     bcx.tcx().sess.span_bug(index_expr.span,
786                                             "index method didn't return a \
787                                              dereferenceable type?!")
788                 }
789                 Some(elt_tm) => elt_tm.ty,
790             };
791
792             // Overloaded. Evaluate `trans_overloaded_op`, which will
793             // invoke the user's index() method, which basically yields
794             // a `&T` pointer.  We can then proceed down the normal
795             // path (below) to dereference that `&T`.
796             let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_index_elt");
797             unpack_result!(bcx,
798                            trans_overloaded_op(bcx,
799                                                index_expr,
800                                                method_call,
801                                                base_datum,
802                                                Some((ix_datum, idx.id)),
803                                                Some(SaveIn(scratch.val)),
804                                                false));
805             let datum = scratch.to_expr_datum();
806             let lval = Lvalue::new("expr::trans_index overload");
807             if type_is_sized(bcx.tcx(), elt_ty) {
808                 Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr(lval))
809             } else {
810                 Datum::new(datum.val, elt_ty, LvalueExpr(lval))
811             }
812         }
813         None => {
814             let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
815                                                                 base,
816                                                                 "index"));
817
818             // Translate index expression and cast to a suitable LLVM integer.
819             // Rust is less strict than LLVM in this regard.
820             let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
821             let ix_val = ix_datum.to_llscalarish(bcx);
822             let ix_size = machine::llbitsize_of_real(bcx.ccx(),
823                                                      val_ty(ix_val));
824             let int_size = machine::llbitsize_of_real(bcx.ccx(),
825                                                       ccx.int_type());
826             let ix_val = {
827                 if ix_size < int_size {
828                     if expr_ty(bcx, idx).is_signed() {
829                         SExt(bcx, ix_val, ccx.int_type())
830                     } else { ZExt(bcx, ix_val, ccx.int_type()) }
831                 } else if ix_size > int_size {
832                     Trunc(bcx, ix_val, ccx.int_type())
833                 } else {
834                     ix_val
835                 }
836             };
837
838             let unit_ty = base_datum.ty.sequence_element_type(bcx.tcx());
839
840             let (base, len) = base_datum.get_vec_base_and_len(bcx);
841
842             debug!("trans_index: base {}", bcx.val_to_string(base));
843             debug!("trans_index: len {}", bcx.val_to_string(len));
844
845             let bounds_check = ICmp(bcx,
846                                     llvm::IntUGE,
847                                     ix_val,
848                                     len,
849                                     index_expr_debug_loc);
850             let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
851             let expected = Call(bcx,
852                                 expect,
853                                 &[bounds_check, C_bool(ccx, false)],
854                                 None,
855                                 index_expr_debug_loc);
856             bcx = with_cond(bcx, expected, |bcx| {
857                 controlflow::trans_fail_bounds_check(bcx,
858                                                      expr_info(index_expr),
859                                                      ix_val,
860                                                      len)
861             });
862             let elt = InBoundsGEP(bcx, base, &[ix_val]);
863             let elt = PointerCast(bcx, elt, type_of::type_of(ccx, unit_ty).ptr_to());
864             let lval = Lvalue::new("expr::trans_index fallback");
865             Datum::new(elt, unit_ty, LvalueExpr(lval))
866         }
867     };
868
869     DatumBlock::new(bcx, elt_datum)
870 }
871
872 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
873                          ref_expr: &hir::Expr,
874                          def: def::Def)
875                          -> DatumBlock<'blk, 'tcx, Expr> {
876     //! Translates a reference to a path.
877
878     let _icx = push_ctxt("trans_def_lvalue");
879     match def {
880         def::DefFn(..) | def::DefMethod(..) |
881         def::DefStruct(_) | def::DefVariant(..) => {
882             let datum = trans_def_fn_unadjusted(bcx.ccx(), ref_expr, def,
883                                                 bcx.fcx.param_substs);
884             DatumBlock::new(bcx, datum.to_expr_datum())
885         }
886         def::DefStatic(did, _) => {
887             // There are two things that may happen here:
888             //  1) If the static item is defined in this crate, it will be
889             //     translated using `get_item_val`, and we return a pointer to
890             //     the result.
891             //  2) If the static item is defined in another crate then we add
892             //     (or reuse) a declaration of an external global, and return a
893             //     pointer to that.
894             let const_ty = expr_ty(bcx, ref_expr);
895
896             // For external constants, we don't inline.
897             let val = if did.is_local() {
898                 // Case 1.
899
900                 // The LLVM global has the type of its initializer,
901                 // which may not be equal to the enum's type for
902                 // non-C-like enums.
903                 let val = base::get_item_val(bcx.ccx(), did.node);
904                 let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to();
905                 PointerCast(bcx, val, pty)
906             } else {
907                 // Case 2.
908                 base::get_extern_const(bcx.ccx(), did, const_ty)
909             };
910             let lval = Lvalue::new("expr::trans_def");
911             DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr(lval)))
912         }
913         def::DefConst(_) => {
914             bcx.sess().span_bug(ref_expr.span,
915                 "constant expression should not reach expr::trans_def")
916         }
917         _ => {
918             DatumBlock::new(bcx, trans_local_var(bcx, def).to_expr_datum())
919         }
920     }
921 }
922
923 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
924                                             expr: &hir::Expr)
925                                             -> Block<'blk, 'tcx> {
926     let mut bcx = bcx;
927     let _icx = push_ctxt("trans_rvalue_stmt");
928
929     if bcx.unreachable.get() {
930         return bcx;
931     }
932
933     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
934
935     match expr.node {
936         hir::ExprParen(ref e) => {
937             trans_into(bcx, &**e, Ignore)
938         }
939         hir::ExprBreak(label_opt) => {
940             controlflow::trans_break(bcx, expr, label_opt.map(|l| l.node))
941         }
942         hir::ExprAgain(label_opt) => {
943             controlflow::trans_cont(bcx, expr, label_opt.map(|l| l.node))
944         }
945         hir::ExprRet(ref ex) => {
946             // Check to see if the return expression itself is reachable.
947             // This can occur when the inner expression contains a return
948             let reachable = if let Some(ref cfg) = bcx.fcx.cfg {
949                 cfg.node_is_reachable(expr.id)
950             } else {
951                 true
952             };
953
954             if reachable {
955                 controlflow::trans_ret(bcx, expr, ex.as_ref().map(|e| &**e))
956             } else {
957                 // If it's not reachable, just translate the inner expression
958                 // directly. This avoids having to manage a return slot when
959                 // it won't actually be used anyway.
960                 if let &Some(ref x) = ex {
961                     bcx = trans_into(bcx, &**x, Ignore);
962                 }
963                 // Mark the end of the block as unreachable. Once we get to
964                 // a return expression, there's no more we should be doing
965                 // after this.
966                 Unreachable(bcx);
967                 bcx
968             }
969         }
970         hir::ExprWhile(ref cond, ref body, _) => {
971             controlflow::trans_while(bcx, expr, &**cond, &**body)
972         }
973         hir::ExprLoop(ref body, _) => {
974             controlflow::trans_loop(bcx, expr, &**body)
975         }
976         hir::ExprAssign(ref dst, ref src) => {
977             let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
978             let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
979
980             if bcx.fcx.type_needs_drop(dst_datum.ty) {
981                 // If there are destructors involved, make sure we
982                 // are copying from an rvalue, since that cannot possible
983                 // alias an lvalue. We are concerned about code like:
984                 //
985                 //   a = a
986                 //
987                 // but also
988                 //
989                 //   a = a.b
990                 //
991                 // where e.g. a : Option<Foo> and a.b :
992                 // Option<Foo>. In that case, freeing `a` before the
993                 // assignment may also free `a.b`!
994                 //
995                 // We could avoid this intermediary with some analysis
996                 // to determine whether `dst` may possibly own `src`.
997                 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
998                 let src_datum = unpack_datum!(
999                     bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
1000                 let opt_hint_datum = dst_datum.kind.drop_flag_info.hint_datum(bcx);
1001                 let opt_hint_val = opt_hint_datum.map(|d|d.to_value());
1002
1003                 // 1. Drop the data at the destination, passing the
1004                 //    drop-hint in case the lvalue has already been
1005                 //    dropped or moved.
1006                 bcx = glue::drop_ty_core(bcx,
1007                                          dst_datum.val,
1008                                          dst_datum.ty,
1009                                          expr.debug_loc(),
1010                                          false,
1011                                          opt_hint_val);
1012
1013                 // 2. We are overwriting the destination; ensure that
1014                 //    its drop-hint (if any) says "initialized."
1015                 if let Some(hint_val) = opt_hint_val {
1016                     let hint_llval = hint_val.value();
1017                     let drop_needed = C_u8(bcx.fcx.ccx, adt::DTOR_NEEDED_HINT);
1018                     Store(bcx, drop_needed, hint_llval);
1019                 }
1020                 src_datum.store_to(bcx, dst_datum.val)
1021             } else {
1022                 src_datum.store_to(bcx, dst_datum.val)
1023             }
1024         }
1025         hir::ExprAssignOp(op, ref dst, ref src) => {
1026             trans_assign_op(bcx, expr, op, &**dst, &**src)
1027         }
1028         hir::ExprInlineAsm(ref a) => {
1029             asm::trans_inline_asm(bcx, a)
1030         }
1031         _ => {
1032             bcx.tcx().sess.span_bug(
1033                 expr.span,
1034                 &format!("trans_rvalue_stmt_unadjusted reached \
1035                          fall-through case: {:?}",
1036                         expr.node));
1037         }
1038     }
1039 }
1040
1041 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1042                                            expr: &hir::Expr,
1043                                            dest: Dest)
1044                                            -> Block<'blk, 'tcx> {
1045     let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
1046     let mut bcx = bcx;
1047     let tcx = bcx.tcx();
1048
1049     debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
1050
1051     match expr.node {
1052         hir::ExprParen(ref e) => {
1053             trans_into(bcx, &**e, dest)
1054         }
1055         hir::ExprPath(..) => {
1056             trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
1057         }
1058         hir::ExprIf(ref cond, ref thn, ref els) => {
1059             controlflow::trans_if(bcx, expr.id, &**cond, &**thn, els.as_ref().map(|e| &**e), dest)
1060         }
1061         hir::ExprMatch(ref discr, ref arms, _) => {
1062             _match::trans_match(bcx, expr, &**discr, &arms[..], dest)
1063         }
1064         hir::ExprBlock(ref blk) => {
1065             controlflow::trans_block(bcx, &**blk, dest)
1066         }
1067         hir::ExprStruct(_, ref fields, ref base) => {
1068             trans_struct(bcx,
1069                          &fields[..],
1070                          base.as_ref().map(|e| &**e),
1071                          expr.span,
1072                          expr.id,
1073                          node_id_type(bcx, expr.id),
1074                          dest)
1075         }
1076         hir::ExprRange(ref start, ref end) => {
1077             // FIXME it is just not right that we are synthesising ast nodes in
1078             // trans. Shudder.
1079             fn make_field(field_name: &str, expr: P<hir::Expr>) -> hir::Field {
1080                 hir::Field {
1081                     ident: codemap::dummy_spanned(token::str_to_ident(field_name)),
1082                     expr: expr,
1083                     span: codemap::DUMMY_SP,
1084                 }
1085             }
1086
1087             // A range just desugars into a struct.
1088             // Note that the type of the start and end may not be the same, but
1089             // they should only differ in their lifetime, which should not matter
1090             // in trans.
1091             let (did, fields, ty_params) = match (start, end) {
1092                 (&Some(ref start), &Some(ref end)) => {
1093                     // Desugar to Range
1094                     let fields = vec![make_field("start", start.clone()),
1095                                       make_field("end", end.clone())];
1096                     (tcx.lang_items.range_struct(), fields, vec![node_id_type(bcx, start.id)])
1097                 }
1098                 (&Some(ref start), &None) => {
1099                     // Desugar to RangeFrom
1100                     let fields = vec![make_field("start", start.clone())];
1101                     (tcx.lang_items.range_from_struct(), fields, vec![node_id_type(bcx, start.id)])
1102                 }
1103                 (&None, &Some(ref end)) => {
1104                     // Desugar to RangeTo
1105                     let fields = vec![make_field("end", end.clone())];
1106                     (tcx.lang_items.range_to_struct(), fields, vec![node_id_type(bcx, end.id)])
1107                 }
1108                 _ => {
1109                     // Desugar to RangeFull
1110                     (tcx.lang_items.range_full_struct(), vec![], vec![])
1111                 }
1112             };
1113
1114             if let Some(did) = did {
1115                 let substs = Substs::new_type(ty_params, vec![]);
1116                 trans_struct(bcx,
1117                              &fields,
1118                              None,
1119                              expr.span,
1120                              expr.id,
1121                              tcx.mk_struct(tcx.lookup_adt_def(did),
1122                                            tcx.mk_substs(substs)),
1123                              dest)
1124             } else {
1125                 tcx.sess.span_bug(expr.span,
1126                                   "No lang item for ranges (how did we get this far?)")
1127             }
1128         }
1129         hir::ExprTup(ref args) => {
1130             let numbered_fields: Vec<(usize, &hir::Expr)> =
1131                 args.iter().enumerate().map(|(i, arg)| (i, &**arg)).collect();
1132             trans_adt(bcx,
1133                       expr_ty(bcx, expr),
1134                       0,
1135                       &numbered_fields[..],
1136                       None,
1137                       dest,
1138                       expr.debug_loc())
1139         }
1140         hir::ExprLit(ref lit) => {
1141             match lit.node {
1142                 hir::LitStr(ref s, _) => {
1143                     tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1144                 }
1145                 _ => {
1146                     bcx.tcx()
1147                        .sess
1148                        .span_bug(expr.span,
1149                                  "trans_rvalue_dps_unadjusted shouldn't be \
1150                                   translating this type of literal")
1151                 }
1152             }
1153         }
1154         hir::ExprVec(..) | hir::ExprRepeat(..) => {
1155             tvec::trans_fixed_vstore(bcx, expr, dest)
1156         }
1157         hir::ExprClosure(_, ref decl, ref body) => {
1158             let dest = match dest {
1159                 SaveIn(lldest) => closure::Dest::SaveIn(bcx, lldest),
1160                 Ignore => closure::Dest::Ignore(bcx.ccx())
1161             };
1162             let substs = match expr_ty(bcx, expr).sty {
1163                 ty::TyClosure(_, ref substs) => substs,
1164                 ref t =>
1165                     bcx.tcx().sess.span_bug(
1166                         expr.span,
1167                         &format!("closure expr without closure type: {:?}", t)),
1168             };
1169             closure::trans_closure_expr(dest, decl, body, expr.id, substs).unwrap_or(bcx)
1170         }
1171         hir::ExprCall(ref f, ref args) => {
1172             if bcx.tcx().is_method_call(expr.id) {
1173                 trans_overloaded_call(bcx,
1174                                       expr,
1175                                       &**f,
1176                                       &args[..],
1177                                       Some(dest))
1178             } else {
1179                 callee::trans_call(bcx,
1180                                    expr,
1181                                    &**f,
1182                                    callee::ArgExprs(&args[..]),
1183                                    dest)
1184             }
1185         }
1186         hir::ExprMethodCall(_, _, ref args) => {
1187             callee::trans_method_call(bcx,
1188                                       expr,
1189                                       &*args[0],
1190                                       callee::ArgExprs(&args[..]),
1191                                       dest)
1192         }
1193         hir::ExprBinary(op, ref lhs, ref rhs) => {
1194             // if not overloaded, would be RvalueDatumExpr
1195             let lhs = unpack_datum!(bcx, trans(bcx, &**lhs));
1196             let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs));
1197             trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs,
1198                                 Some((rhs_datum, rhs.id)), Some(dest),
1199                                 !rustc_front::util::is_by_value_binop(op.node)).bcx
1200         }
1201         hir::ExprUnary(op, ref subexpr) => {
1202             // if not overloaded, would be RvalueDatumExpr
1203             let arg = unpack_datum!(bcx, trans(bcx, &**subexpr));
1204             trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id),
1205                                 arg, None, Some(dest), !rustc_front::util::is_by_value_unop(op)).bcx
1206         }
1207         hir::ExprIndex(ref base, ref idx) => {
1208             // if not overloaded, would be RvalueDatumExpr
1209             let base = unpack_datum!(bcx, trans(bcx, &**base));
1210             let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx));
1211             trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
1212                                 Some((idx_datum, idx.id)), Some(dest), true).bcx
1213         }
1214         hir::ExprCast(..) => {
1215             // Trait casts used to come this way, now they should be coercions.
1216             bcx.tcx().sess.span_bug(expr.span, "DPS expr_cast (residual trait cast?)")
1217         }
1218         hir::ExprAssignOp(op, ref dst, ref src) => {
1219             trans_assign_op(bcx, expr, op, &**dst, &**src)
1220         }
1221         _ => {
1222             bcx.tcx().sess.span_bug(
1223                 expr.span,
1224                 &format!("trans_rvalue_dps_unadjusted reached fall-through \
1225                          case: {:?}",
1226                         expr.node));
1227         }
1228     }
1229 }
1230
1231 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1232                                         ref_expr: &hir::Expr,
1233                                         def: def::Def,
1234                                         dest: Dest)
1235                                         -> Block<'blk, 'tcx> {
1236     let _icx = push_ctxt("trans_def_dps_unadjusted");
1237
1238     let lldest = match dest {
1239         SaveIn(lldest) => lldest,
1240         Ignore => { return bcx; }
1241     };
1242
1243     match def {
1244         def::DefVariant(tid, vid, _) => {
1245             let variant = bcx.tcx().lookup_adt_def(tid).variant_with_id(vid);
1246             if let ty::VariantKind::Tuple = variant.kind() {
1247                 // N-ary variant.
1248                 let llfn = callee::trans_fn_ref(bcx.ccx(), vid,
1249                                                 ExprId(ref_expr.id),
1250                                                 bcx.fcx.param_substs).val;
1251                 Store(bcx, llfn, lldest);
1252                 return bcx;
1253             } else {
1254                 // Nullary variant.
1255                 let ty = expr_ty(bcx, ref_expr);
1256                 let repr = adt::represent_type(bcx.ccx(), ty);
1257                 adt::trans_set_discr(bcx, &*repr, lldest, variant.disr_val);
1258                 return bcx;
1259             }
1260         }
1261         def::DefStruct(_) => {
1262             let ty = expr_ty(bcx, ref_expr);
1263             match ty.sty {
1264                 ty::TyStruct(def, _) if def.has_dtor() => {
1265                     let repr = adt::represent_type(bcx.ccx(), ty);
1266                     adt::trans_set_discr(bcx, &*repr, lldest, 0);
1267                 }
1268                 _ => {}
1269             }
1270             bcx
1271         }
1272         _ => {
1273             bcx.tcx().sess.span_bug(ref_expr.span, &format!(
1274                 "Non-DPS def {:?} referened by {}",
1275                 def, bcx.node_id_to_string(ref_expr.id)));
1276         }
1277     }
1278 }
1279
1280 pub fn trans_def_fn_unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1281                                          ref_expr: &hir::Expr,
1282                                          def: def::Def,
1283                                          param_substs: &'tcx Substs<'tcx>)
1284                                          -> Datum<'tcx, Rvalue> {
1285     let _icx = push_ctxt("trans_def_datum_unadjusted");
1286
1287     match def {
1288         def::DefFn(did, _) |
1289         def::DefStruct(did) | def::DefVariant(_, did, _) => {
1290             callee::trans_fn_ref(ccx, did, ExprId(ref_expr.id), param_substs)
1291         }
1292         def::DefMethod(method_did) => {
1293             match ccx.tcx().impl_or_trait_item(method_did).container() {
1294                 ty::ImplContainer(_) => {
1295                     callee::trans_fn_ref(ccx, method_did,
1296                                          ExprId(ref_expr.id),
1297                                          param_substs)
1298                 }
1299                 ty::TraitContainer(trait_did) => {
1300                     meth::trans_static_method_callee(ccx, method_did,
1301                                                      trait_did, ref_expr.id,
1302                                                      param_substs)
1303                 }
1304             }
1305         }
1306         _ => {
1307             ccx.tcx().sess.span_bug(ref_expr.span, &format!(
1308                     "trans_def_fn_unadjusted invoked on: {:?} for {:?}",
1309                     def,
1310                     ref_expr));
1311         }
1312     }
1313 }
1314
1315 /// Translates a reference to a local variable or argument. This always results in an lvalue datum.
1316 pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1317                                    def: def::Def)
1318                                    -> Datum<'tcx, Lvalue> {
1319     let _icx = push_ctxt("trans_local_var");
1320
1321     match def {
1322         def::DefUpvar(nid, _) => {
1323             // Can't move upvars, so this is never a ZeroMemLastUse.
1324             let local_ty = node_id_type(bcx, nid);
1325             let lval = Lvalue::new_with_hint("expr::trans_local_var (upvar)",
1326                                              bcx, nid, HintKind::ZeroAndMaintain);
1327             match bcx.fcx.llupvars.borrow().get(&nid) {
1328                 Some(&val) => Datum::new(val, local_ty, lval),
1329                 None => {
1330                     bcx.sess().bug(&format!(
1331                         "trans_local_var: no llval for upvar {} found",
1332                         nid));
1333                 }
1334             }
1335         }
1336         def::DefLocal(nid) => {
1337             let datum = match bcx.fcx.lllocals.borrow().get(&nid) {
1338                 Some(&v) => v,
1339                 None => {
1340                     bcx.sess().bug(&format!(
1341                         "trans_local_var: no datum for local/arg {} found",
1342                         nid));
1343                 }
1344             };
1345             debug!("take_local(nid={}, v={}, ty={})",
1346                    nid, bcx.val_to_string(datum.val), datum.ty);
1347             datum
1348         }
1349         _ => {
1350             bcx.sess().unimpl(&format!(
1351                 "unsupported def type in trans_local_var: {:?}",
1352                 def));
1353         }
1354     }
1355 }
1356
1357 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1358                             fields: &[hir::Field],
1359                             base: Option<&hir::Expr>,
1360                             expr_span: codemap::Span,
1361                             expr_id: ast::NodeId,
1362                             ty: Ty<'tcx>,
1363                             dest: Dest) -> Block<'blk, 'tcx> {
1364     let _icx = push_ctxt("trans_rec");
1365
1366     let tcx = bcx.tcx();
1367     let vinfo = VariantInfo::of_node(tcx, ty, expr_id);
1368
1369     let mut need_base = vec![true; vinfo.fields.len()];
1370
1371     let numbered_fields = fields.iter().map(|field| {
1372         let pos = vinfo.field_index(field.ident.node.name);
1373         need_base[pos] = false;
1374         (pos, &*field.expr)
1375     }).collect::<Vec<_>>();
1376
1377     let optbase = match base {
1378         Some(base_expr) => {
1379             let mut leftovers = Vec::new();
1380             for (i, b) in need_base.iter().enumerate() {
1381                 if *b {
1382                     leftovers.push((i, vinfo.fields[i].1));
1383                 }
1384             }
1385             Some(StructBaseInfo {expr: base_expr,
1386                                  fields: leftovers })
1387         }
1388         None => {
1389             if need_base.iter().any(|b| *b) {
1390                 tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1391             }
1392             None
1393         }
1394     };
1395
1396     trans_adt(bcx,
1397               ty,
1398               vinfo.discr,
1399               &numbered_fields,
1400               optbase,
1401               dest,
1402               DebugLoc::At(expr_id, expr_span))
1403 }
1404
1405 /// Information that `trans_adt` needs in order to fill in the fields
1406 /// of a struct copied from a base struct (e.g., from an expression
1407 /// like `Foo { a: b, ..base }`.
1408 ///
1409 /// Note that `fields` may be empty; the base expression must always be
1410 /// evaluated for side-effects.
1411 pub struct StructBaseInfo<'a, 'tcx> {
1412     /// The base expression; will be evaluated after all explicit fields.
1413     expr: &'a hir::Expr,
1414     /// The indices of fields to copy paired with their types.
1415     fields: Vec<(usize, Ty<'tcx>)>
1416 }
1417
1418 /// Constructs an ADT instance:
1419 ///
1420 /// - `fields` should be a list of field indices paired with the
1421 /// expression to store into that field.  The initializers will be
1422 /// evaluated in the order specified by `fields`.
1423 ///
1424 /// - `optbase` contains information on the base struct (if any) from
1425 /// which remaining fields are copied; see comments on `StructBaseInfo`.
1426 pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1427                                  ty: Ty<'tcx>,
1428                                  discr: ty::Disr,
1429                                  fields: &[(usize, &hir::Expr)],
1430                                  optbase: Option<StructBaseInfo<'a, 'tcx>>,
1431                                  dest: Dest,
1432                                  debug_location: DebugLoc)
1433                                  -> Block<'blk, 'tcx> {
1434     let _icx = push_ctxt("trans_adt");
1435     let fcx = bcx.fcx;
1436     let repr = adt::represent_type(bcx.ccx(), ty);
1437
1438     debug_location.apply(bcx.fcx);
1439
1440     // If we don't care about the result, just make a
1441     // temporary stack slot
1442     let addr = match dest {
1443         SaveIn(pos) => pos,
1444         Ignore => {
1445             let llresult = alloc_ty(bcx, ty, "temp");
1446             call_lifetime_start(bcx, llresult);
1447             llresult
1448         }
1449     };
1450
1451     // This scope holds intermediates that must be cleaned should
1452     // panic occur before the ADT as a whole is ready.
1453     let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1454
1455     if ty.is_simd() {
1456         // Issue 23112: The original logic appeared vulnerable to same
1457         // order-of-eval bug. But, SIMD values are tuple-structs;
1458         // i.e. functional record update (FRU) syntax is unavailable.
1459         //
1460         // To be safe, double-check that we did not get here via FRU.
1461         assert!(optbase.is_none());
1462
1463         // This is the constructor of a SIMD type, such types are
1464         // always primitive machine types and so do not have a
1465         // destructor or require any clean-up.
1466         let llty = type_of::type_of(bcx.ccx(), ty);
1467
1468         // keep a vector as a register, and running through the field
1469         // `insertelement`ing them directly into that register
1470         // (i.e. avoid GEPi and `store`s to an alloca) .
1471         let mut vec_val = C_undef(llty);
1472
1473         for &(i, ref e) in fields {
1474             let block_datum = trans(bcx, &**e);
1475             bcx = block_datum.bcx;
1476             let position = C_uint(bcx.ccx(), i);
1477             let value = block_datum.datum.to_llscalarish(bcx);
1478             vec_val = InsertElement(bcx, vec_val, value, position);
1479         }
1480         Store(bcx, vec_val, addr);
1481     } else if let Some(base) = optbase {
1482         // Issue 23112: If there is a base, then order-of-eval
1483         // requires field expressions eval'ed before base expression.
1484
1485         // First, trans field expressions to temporary scratch values.
1486         let scratch_vals: Vec<_> = fields.iter().map(|&(i, ref e)| {
1487             let datum = unpack_datum!(bcx, trans(bcx, &**e));
1488             (i, datum)
1489         }).collect();
1490
1491         debug_location.apply(bcx.fcx);
1492
1493         // Second, trans the base to the dest.
1494         assert_eq!(discr, 0);
1495
1496         match expr_kind(bcx.tcx(), &*base.expr) {
1497             ExprKind::RvalueDps | ExprKind::RvalueDatum if !bcx.fcx.type_needs_drop(ty) => {
1498                 bcx = trans_into(bcx, &*base.expr, SaveIn(addr));
1499             },
1500             ExprKind::RvalueStmt => {
1501                 bcx.tcx().sess.bug("unexpected expr kind for struct base expr")
1502             }
1503             _ => {
1504                 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base"));
1505                 for &(i, t) in &base.fields {
1506                     let datum = base_datum.get_element(
1507                             bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i));
1508                     assert!(type_is_sized(bcx.tcx(), datum.ty));
1509                     let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1510                     bcx = datum.store_to(bcx, dest);
1511                 }
1512             }
1513         }
1514
1515         // Finally, move scratch field values into actual field locations
1516         for (i, datum) in scratch_vals {
1517             let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1518             bcx = datum.store_to(bcx, dest);
1519         }
1520     } else {
1521         // No base means we can write all fields directly in place.
1522         for &(i, ref e) in fields {
1523             let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1524             let e_ty = expr_ty_adjusted(bcx, &**e);
1525             bcx = trans_into(bcx, &**e, SaveIn(dest));
1526             let scope = cleanup::CustomScope(custom_cleanup_scope);
1527             fcx.schedule_lifetime_end(scope, dest);
1528             // FIXME: nonzeroing move should generalize to fields
1529             fcx.schedule_drop_mem(scope, dest, e_ty, None);
1530         }
1531     }
1532
1533     adt::trans_set_discr(bcx, &*repr, addr, discr);
1534
1535     fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1536
1537     // If we don't care about the result drop the temporary we made
1538     match dest {
1539         SaveIn(_) => bcx,
1540         Ignore => {
1541             bcx = glue::drop_ty(bcx, addr, ty, debug_location);
1542             base::call_lifetime_end(bcx, addr);
1543             bcx
1544         }
1545     }
1546 }
1547
1548
1549 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1550                                    expr: &hir::Expr,
1551                                    lit: &hir::Lit)
1552                                    -> DatumBlock<'blk, 'tcx, Expr> {
1553     // must not be a string constant, that is a RvalueDpsExpr
1554     let _icx = push_ctxt("trans_immediate_lit");
1555     let ty = expr_ty(bcx, expr);
1556     let v = consts::const_lit(bcx.ccx(), expr, lit);
1557     immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1558 }
1559
1560 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1561                            expr: &hir::Expr,
1562                            op: hir::UnOp,
1563                            sub_expr: &hir::Expr)
1564                            -> DatumBlock<'blk, 'tcx, Expr> {
1565     let ccx = bcx.ccx();
1566     let mut bcx = bcx;
1567     let _icx = push_ctxt("trans_unary_datum");
1568
1569     let method_call = MethodCall::expr(expr.id);
1570
1571     // The only overloaded operator that is translated to a datum
1572     // is an overloaded deref, since it is always yields a `&T`.
1573     // Otherwise, we should be in the RvalueDpsExpr path.
1574     assert!(op == hir::UnDeref || !ccx.tcx().is_method_call(expr.id));
1575
1576     let un_ty = expr_ty(bcx, expr);
1577
1578     let debug_loc = expr.debug_loc();
1579
1580     match op {
1581         hir::UnNot => {
1582             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1583             let llresult = Not(bcx, datum.to_llscalarish(bcx), debug_loc);
1584             immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1585         }
1586         hir::UnNeg => {
1587             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1588             let val = datum.to_llscalarish(bcx);
1589             let (bcx, llneg) = {
1590                 if un_ty.is_fp() {
1591                     let result = FNeg(bcx, val, debug_loc);
1592                     (bcx, result)
1593                 } else {
1594                     let is_signed = un_ty.is_signed();
1595                     let result = Neg(bcx, val, debug_loc);
1596                     let bcx = if bcx.ccx().check_overflow() && is_signed {
1597                         let (llty, min) = base::llty_and_min_for_signed_ty(bcx, un_ty);
1598                         let is_min = ICmp(bcx, llvm::IntEQ, val,
1599                                           C_integral(llty, min, true), debug_loc);
1600                         with_cond(bcx, is_min, |bcx| {
1601                             let msg = InternedString::new(
1602                                 "attempted to negate with overflow");
1603                             controlflow::trans_fail(bcx, expr_info(expr), msg)
1604                         })
1605                     } else {
1606                         bcx
1607                     };
1608                     (bcx, result)
1609                 }
1610             };
1611             immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1612         }
1613         hir::UnUniq => {
1614             trans_uniq_expr(bcx, expr, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1615         }
1616         hir::UnDeref => {
1617             let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1618             deref_once(bcx, expr, datum, method_call)
1619         }
1620     }
1621 }
1622
1623 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1624                                box_expr: &hir::Expr,
1625                                box_ty: Ty<'tcx>,
1626                                contents: &hir::Expr,
1627                                contents_ty: Ty<'tcx>)
1628                                -> DatumBlock<'blk, 'tcx, Expr> {
1629     let _icx = push_ctxt("trans_uniq_expr");
1630     let fcx = bcx.fcx;
1631     assert!(type_is_sized(bcx.tcx(), contents_ty));
1632     let llty = type_of::type_of(bcx.ccx(), contents_ty);
1633     let size = llsize_of(bcx.ccx(), llty);
1634     let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty));
1635     let llty_ptr = llty.ptr_to();
1636     let Result { bcx, val } = malloc_raw_dyn(bcx,
1637                                              llty_ptr,
1638                                              box_ty,
1639                                              size,
1640                                              align,
1641                                              box_expr.debug_loc());
1642     // Unique boxes do not allocate for zero-size types. The standard library
1643     // may assume that `free` is never called on the pointer returned for
1644     // `Box<ZeroSizeType>`.
1645     let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1646         trans_into(bcx, contents, SaveIn(val))
1647     } else {
1648         let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1649         fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1650                                 val, cleanup::HeapExchange, contents_ty);
1651         let bcx = trans_into(bcx, contents, SaveIn(val));
1652         fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1653         bcx
1654     };
1655     immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1656 }
1657
1658 fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1659                            lval: Datum<'tcx, Lvalue>)
1660                            -> DatumBlock<'blk, 'tcx, Expr> {
1661     let dest_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), lval.ty);
1662     let scratch = rvalue_scratch_datum(bcx, dest_ty, "__fat_ptr");
1663     memcpy_ty(bcx, scratch.val, lval.val, scratch.ty);
1664
1665     DatumBlock::new(bcx, scratch.to_expr_datum())
1666 }
1667
1668 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1669                              expr: &hir::Expr,
1670                              subexpr: &hir::Expr)
1671                              -> DatumBlock<'blk, 'tcx, Expr> {
1672     let _icx = push_ctxt("trans_addr_of");
1673     let mut bcx = bcx;
1674     let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1675     if !type_is_sized(bcx.tcx(), sub_datum.ty) {
1676         // DST lvalue, close to a fat pointer
1677         ref_fat_ptr(bcx, sub_datum)
1678     } else {
1679         // Sized value, ref to a thin pointer
1680         let ty = expr_ty(bcx, expr);
1681         immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1682     }
1683 }
1684
1685 // Important to get types for both lhs and rhs, because one might be _|_
1686 // and the other not.
1687 fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1688                                  binop_expr: &hir::Expr,
1689                                  binop_ty: Ty<'tcx>,
1690                                  op: hir::BinOp,
1691                                  lhs_t: Ty<'tcx>,
1692                                  lhs: ValueRef,
1693                                  rhs_t: Ty<'tcx>,
1694                                  rhs: ValueRef)
1695                                  -> DatumBlock<'blk, 'tcx, Expr> {
1696     let _icx = push_ctxt("trans_eager_binop");
1697
1698     let tcx = bcx.tcx();
1699     assert!(!lhs_t.is_simd());
1700     let is_float = lhs_t.is_fp();
1701     let is_signed = lhs_t.is_signed();
1702     let info = expr_info(binop_expr);
1703
1704     let binop_debug_loc = binop_expr.debug_loc();
1705
1706     let mut bcx = bcx;
1707     let val = match op.node {
1708       hir::BiAdd => {
1709         if is_float {
1710             FAdd(bcx, lhs, rhs, binop_debug_loc)
1711         } else {
1712             let (newbcx, res) = with_overflow_check(
1713                 bcx, OverflowOp::Add, info, lhs_t, lhs, rhs, binop_debug_loc);
1714             bcx = newbcx;
1715             res
1716         }
1717       }
1718       hir::BiSub => {
1719         if is_float {
1720             FSub(bcx, lhs, rhs, binop_debug_loc)
1721         } else {
1722             let (newbcx, res) = with_overflow_check(
1723                 bcx, OverflowOp::Sub, info, lhs_t, lhs, rhs, binop_debug_loc);
1724             bcx = newbcx;
1725             res
1726         }
1727       }
1728       hir::BiMul => {
1729         if is_float {
1730             FMul(bcx, lhs, rhs, binop_debug_loc)
1731         } else {
1732             let (newbcx, res) = with_overflow_check(
1733                 bcx, OverflowOp::Mul, info, lhs_t, lhs, rhs, binop_debug_loc);
1734             bcx = newbcx;
1735             res
1736         }
1737       }
1738       hir::BiDiv => {
1739         if is_float {
1740             FDiv(bcx, lhs, rhs, binop_debug_loc)
1741         } else {
1742             // Only zero-check integers; fp /0 is NaN
1743             bcx = base::fail_if_zero_or_overflows(bcx,
1744                                                   expr_info(binop_expr),
1745                                                   op,
1746                                                   lhs,
1747                                                   rhs,
1748                                                   rhs_t);
1749             if is_signed {
1750                 SDiv(bcx, lhs, rhs, binop_debug_loc)
1751             } else {
1752                 UDiv(bcx, lhs, rhs, binop_debug_loc)
1753             }
1754         }
1755       }
1756       hir::BiRem => {
1757         if is_float {
1758             // LLVM currently always lowers the `frem` instructions appropriate
1759             // library calls typically found in libm. Notably f64 gets wired up
1760             // to `fmod` and f32 gets wired up to `fmodf`. Inconveniently for
1761             // us, 32-bit MSVC does not actually have a `fmodf` symbol, it's
1762             // instead just an inline function in a header that goes up to a
1763             // f64, uses `fmod`, and then comes back down to a f32.
1764             //
1765             // Although LLVM knows that `fmodf` doesn't exist on MSVC, it will
1766             // still unconditionally lower frem instructions over 32-bit floats
1767             // to a call to `fmodf`. To work around this we special case MSVC
1768             // 32-bit float rem instructions and instead do the call out to
1769             // `fmod` ourselves.
1770             //
1771             // Note that this is currently duplicated with src/libcore/ops.rs
1772             // which does the same thing, and it would be nice to perhaps unify
1773             // these two implementations on day! Also note that we call `fmod`
1774             // for both 32 and 64-bit floats because if we emit any FRem
1775             // instruction at all then LLVM is capable of optimizing it into a
1776             // 32-bit FRem (which we're trying to avoid).
1777             let use_fmod = tcx.sess.target.target.options.is_like_msvc &&
1778                            tcx.sess.target.target.arch == "x86";
1779             if use_fmod {
1780                 let f64t = Type::f64(bcx.ccx());
1781                 let fty = Type::func(&[f64t, f64t], &f64t);
1782                 let llfn = declare::declare_cfn(bcx.ccx(), "fmod", fty,
1783                                                 tcx.types.f64);
1784                 if lhs_t == tcx.types.f32 {
1785                     let lhs = FPExt(bcx, lhs, f64t);
1786                     let rhs = FPExt(bcx, rhs, f64t);
1787                     let res = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
1788                     FPTrunc(bcx, res, Type::f32(bcx.ccx()))
1789                 } else {
1790                     Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc)
1791                 }
1792             } else {
1793                 FRem(bcx, lhs, rhs, binop_debug_loc)
1794             }
1795         } else {
1796             // Only zero-check integers; fp %0 is NaN
1797             bcx = base::fail_if_zero_or_overflows(bcx,
1798                                                   expr_info(binop_expr),
1799                                                   op, lhs, rhs, rhs_t);
1800             if is_signed {
1801                 SRem(bcx, lhs, rhs, binop_debug_loc)
1802             } else {
1803                 URem(bcx, lhs, rhs, binop_debug_loc)
1804             }
1805         }
1806       }
1807       hir::BiBitOr => Or(bcx, lhs, rhs, binop_debug_loc),
1808       hir::BiBitAnd => And(bcx, lhs, rhs, binop_debug_loc),
1809       hir::BiBitXor => Xor(bcx, lhs, rhs, binop_debug_loc),
1810       hir::BiShl => {
1811           let (newbcx, res) = with_overflow_check(
1812               bcx, OverflowOp::Shl, info, lhs_t, lhs, rhs, binop_debug_loc);
1813           bcx = newbcx;
1814           res
1815       }
1816       hir::BiShr => {
1817           let (newbcx, res) = with_overflow_check(
1818               bcx, OverflowOp::Shr, info, lhs_t, lhs, rhs, binop_debug_loc);
1819           bcx = newbcx;
1820           res
1821       }
1822       hir::BiEq | hir::BiNe | hir::BiLt | hir::BiGe | hir::BiLe | hir::BiGt => {
1823           base::compare_scalar_types(bcx, lhs, rhs, lhs_t, op.node, binop_debug_loc)
1824       }
1825       _ => {
1826         bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1827       }
1828     };
1829
1830     immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1831 }
1832
1833 // refinement types would obviate the need for this
1834 enum lazy_binop_ty {
1835     lazy_and,
1836     lazy_or,
1837 }
1838
1839 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1840                                 binop_expr: &hir::Expr,
1841                                 op: lazy_binop_ty,
1842                                 a: &hir::Expr,
1843                                 b: &hir::Expr)
1844                                 -> DatumBlock<'blk, 'tcx, Expr> {
1845     let _icx = push_ctxt("trans_lazy_binop");
1846     let binop_ty = expr_ty(bcx, binop_expr);
1847     let fcx = bcx.fcx;
1848
1849     let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1850     let lhs = lhs.to_llscalarish(past_lhs);
1851
1852     if past_lhs.unreachable.get() {
1853         return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1854     }
1855
1856     let join = fcx.new_id_block("join", binop_expr.id);
1857     let before_rhs = fcx.new_id_block("before_rhs", b.id);
1858
1859     match op {
1860       lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb, DebugLoc::None),
1861       lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb, DebugLoc::None)
1862     }
1863
1864     let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1865     let rhs = rhs.to_llscalarish(past_rhs);
1866
1867     if past_rhs.unreachable.get() {
1868         return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1869     }
1870
1871     Br(past_rhs, join.llbb, DebugLoc::None);
1872     let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1873                   &[past_lhs.llbb, past_rhs.llbb]);
1874
1875     return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1876 }
1877
1878 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1879                             expr: &hir::Expr,
1880                             op: hir::BinOp,
1881                             lhs: &hir::Expr,
1882                             rhs: &hir::Expr)
1883                             -> DatumBlock<'blk, 'tcx, Expr> {
1884     let _icx = push_ctxt("trans_binary");
1885     let ccx = bcx.ccx();
1886
1887     // if overloaded, would be RvalueDpsExpr
1888     assert!(!ccx.tcx().is_method_call(expr.id));
1889
1890     match op.node {
1891         hir::BiAnd => {
1892             trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1893         }
1894         hir::BiOr => {
1895             trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1896         }
1897         _ => {
1898             let mut bcx = bcx;
1899             let lhs_datum = unpack_datum!(bcx, trans(bcx, lhs));
1900             let rhs_datum = unpack_datum!(bcx, trans(bcx, rhs));
1901             let binop_ty = expr_ty(bcx, expr);
1902
1903             debug!("trans_binary (expr {}): lhs_datum={}",
1904                    expr.id,
1905                    lhs_datum.to_string(ccx));
1906             let lhs_ty = lhs_datum.ty;
1907             let lhs = lhs_datum.to_llscalarish(bcx);
1908
1909             debug!("trans_binary (expr {}): rhs_datum={}",
1910                    expr.id,
1911                    rhs_datum.to_string(ccx));
1912             let rhs_ty = rhs_datum.ty;
1913             let rhs = rhs_datum.to_llscalarish(bcx);
1914             trans_eager_binop(bcx, expr, binop_ty, op,
1915                               lhs_ty, lhs, rhs_ty, rhs)
1916         }
1917     }
1918 }
1919
1920 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1921                                    expr: &hir::Expr,
1922                                    method_call: MethodCall,
1923                                    lhs: Datum<'tcx, Expr>,
1924                                    rhs: Option<(Datum<'tcx, Expr>, ast::NodeId)>,
1925                                    dest: Option<Dest>,
1926                                    autoref: bool)
1927                                    -> Result<'blk, 'tcx> {
1928     callee::trans_call_inner(bcx,
1929                              expr.debug_loc(),
1930                              |bcx, arg_cleanup_scope| {
1931                                 meth::trans_method_callee(bcx,
1932                                                           method_call,
1933                                                           None,
1934                                                           arg_cleanup_scope)
1935                              },
1936                              callee::ArgOverloadedOp(lhs, rhs, autoref),
1937                              dest)
1938 }
1939
1940 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1941                                          expr: &hir::Expr,
1942                                          callee: &'a hir::Expr,
1943                                          args: &'a [P<hir::Expr>],
1944                                          dest: Option<Dest>)
1945                                          -> Block<'blk, 'tcx> {
1946     debug!("trans_overloaded_call {}", expr.id);
1947     let method_call = MethodCall::expr(expr.id);
1948     let mut all_args = vec!(callee);
1949     all_args.extend(args.iter().map(|e| &**e));
1950     unpack_result!(bcx,
1951                    callee::trans_call_inner(bcx,
1952                                             expr.debug_loc(),
1953                                             |bcx, arg_cleanup_scope| {
1954                                                 meth::trans_method_callee(
1955                                                     bcx,
1956                                                     method_call,
1957                                                     None,
1958                                                     arg_cleanup_scope)
1959                                             },
1960                                             callee::ArgOverloadedCall(all_args),
1961                                             dest));
1962     bcx
1963 }
1964
1965 pub fn cast_is_noop<'tcx>(tcx: &ty::ctxt<'tcx>,
1966                           expr: &hir::Expr,
1967                           t_in: Ty<'tcx>,
1968                           t_out: Ty<'tcx>)
1969                           -> bool {
1970     if let Some(&CastKind::CoercionCast) = tcx.cast_kinds.borrow().get(&expr.id) {
1971         return true;
1972     }
1973
1974     match (t_in.builtin_deref(true, ty::NoPreference),
1975            t_out.builtin_deref(true, ty::NoPreference)) {
1976         (Some(ty::TypeAndMut{ ty: t_in, .. }), Some(ty::TypeAndMut{ ty: t_out, .. })) => {
1977             t_in == t_out
1978         }
1979         _ => {
1980             // This condition isn't redundant with the check for CoercionCast:
1981             // different types can be substituted into the same type, and
1982             // == equality can be overconservative if there are regions.
1983             t_in == t_out
1984         }
1985     }
1986 }
1987
1988 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1989                               expr: &hir::Expr,
1990                               id: ast::NodeId)
1991                               -> DatumBlock<'blk, 'tcx, Expr>
1992 {
1993     use middle::cast::CastTy::*;
1994     use middle::cast::IntTy::*;
1995
1996     fn int_cast(bcx: Block,
1997                 lldsttype: Type,
1998                 llsrctype: Type,
1999                 llsrc: ValueRef,
2000                 signed: bool)
2001                 -> ValueRef
2002     {
2003         let _icx = push_ctxt("int_cast");
2004         let srcsz = llsrctype.int_width();
2005         let dstsz = lldsttype.int_width();
2006         return if dstsz == srcsz {
2007             BitCast(bcx, llsrc, lldsttype)
2008         } else if srcsz > dstsz {
2009             TruncOrBitCast(bcx, llsrc, lldsttype)
2010         } else if signed {
2011             SExtOrBitCast(bcx, llsrc, lldsttype)
2012         } else {
2013             ZExtOrBitCast(bcx, llsrc, lldsttype)
2014         }
2015     }
2016
2017     fn float_cast(bcx: Block,
2018                   lldsttype: Type,
2019                   llsrctype: Type,
2020                   llsrc: ValueRef)
2021                   -> ValueRef
2022     {
2023         let _icx = push_ctxt("float_cast");
2024         let srcsz = llsrctype.float_width();
2025         let dstsz = lldsttype.float_width();
2026         return if dstsz > srcsz {
2027             FPExt(bcx, llsrc, lldsttype)
2028         } else if srcsz > dstsz {
2029             FPTrunc(bcx, llsrc, lldsttype)
2030         } else { llsrc };
2031     }
2032
2033     let _icx = push_ctxt("trans_cast");
2034     let mut bcx = bcx;
2035     let ccx = bcx.ccx();
2036
2037     let t_in = expr_ty_adjusted(bcx, expr);
2038     let t_out = node_id_type(bcx, id);
2039
2040     debug!("trans_cast({:?} as {:?})", t_in, t_out);
2041     let mut ll_t_in = type_of::arg_type_of(ccx, t_in);
2042     let ll_t_out = type_of::arg_type_of(ccx, t_out);
2043     // Convert the value to be cast into a ValueRef, either by-ref or
2044     // by-value as appropriate given its type:
2045     let mut datum = unpack_datum!(bcx, trans(bcx, expr));
2046
2047     let datum_ty = monomorphize_type(bcx, datum.ty);
2048
2049     if cast_is_noop(bcx.tcx(), expr, datum_ty, t_out) {
2050         datum.ty = t_out;
2051         return DatumBlock::new(bcx, datum);
2052     }
2053
2054     if type_is_fat_ptr(bcx.tcx(), t_in) {
2055         assert!(datum.kind.is_by_ref());
2056         if type_is_fat_ptr(bcx.tcx(), t_out) {
2057             return DatumBlock::new(bcx, Datum::new(
2058                 PointerCast(bcx, datum.val, ll_t_out.ptr_to()),
2059                 t_out,
2060                 Rvalue::new(ByRef)
2061             )).to_expr_datumblock();
2062         } else {
2063             // Return the address
2064             return immediate_rvalue_bcx(bcx,
2065                                         PointerCast(bcx,
2066                                                     Load(bcx, get_dataptr(bcx, datum.val)),
2067                                                     ll_t_out),
2068                                         t_out).to_expr_datumblock();
2069         }
2070     }
2071
2072     let r_t_in = CastTy::from_ty(t_in).expect("bad input type for cast");
2073     let r_t_out = CastTy::from_ty(t_out).expect("bad output type for cast");
2074
2075     let (llexpr, signed) = if let Int(CEnum) = r_t_in {
2076         let repr = adt::represent_type(ccx, t_in);
2077         let datum = unpack_datum!(
2078             bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
2079         let llexpr_ptr = datum.to_llref();
2080         let discr = adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
2081         ll_t_in = val_ty(discr);
2082         (discr, adt::is_discr_signed(&*repr))
2083     } else {
2084         (datum.to_llscalarish(bcx), t_in.is_signed())
2085     };
2086
2087     let newval = match (r_t_in, r_t_out) {
2088         (Ptr(_), Ptr(_)) | (FnPtr, Ptr(_)) | (RPtr(_), Ptr(_)) => {
2089             PointerCast(bcx, llexpr, ll_t_out)
2090         }
2091         (Ptr(_), Int(_)) | (FnPtr, Int(_)) => PtrToInt(bcx, llexpr, ll_t_out),
2092         (Int(_), Ptr(_)) => IntToPtr(bcx, llexpr, ll_t_out),
2093
2094         (Int(_), Int(_)) => int_cast(bcx, ll_t_out, ll_t_in, llexpr, signed),
2095         (Float, Float) => float_cast(bcx, ll_t_out, ll_t_in, llexpr),
2096         (Int(_), Float) if signed => SIToFP(bcx, llexpr, ll_t_out),
2097         (Int(_), Float) => UIToFP(bcx, llexpr, ll_t_out),
2098         (Float, Int(I)) => FPToSI(bcx, llexpr, ll_t_out),
2099         (Float, Int(_)) => FPToUI(bcx, llexpr, ll_t_out),
2100
2101         _ => ccx.sess().span_bug(expr.span,
2102                                   &format!("translating unsupported cast: \
2103                                             {:?} -> {:?}",
2104                                            t_in,
2105                                            t_out)
2106                                  )
2107     };
2108     return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
2109 }
2110
2111 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2112                                expr: &hir::Expr,
2113                                op: hir::BinOp,
2114                                dst: &hir::Expr,
2115                                src: &hir::Expr)
2116                                -> Block<'blk, 'tcx> {
2117     let _icx = push_ctxt("trans_assign_op");
2118     let mut bcx = bcx;
2119
2120     debug!("trans_assign_op(expr={:?})", expr);
2121
2122     // User-defined operator methods cannot be used with `+=` etc right now
2123     assert!(!bcx.tcx().is_method_call(expr.id));
2124
2125     // Evaluate LHS (destination), which should be an lvalue
2126     let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2127     assert!(!bcx.fcx.type_needs_drop(dst_datum.ty));
2128     let dst_ty = dst_datum.ty;
2129     let dst = load_ty(bcx, dst_datum.val, dst_datum.ty);
2130
2131     // Evaluate RHS
2132     let rhs_datum = unpack_datum!(bcx, trans(bcx, &*src));
2133     let rhs_ty = rhs_datum.ty;
2134     let rhs = rhs_datum.to_llscalarish(bcx);
2135
2136     // Perform computation and store the result
2137     let result_datum = unpack_datum!(
2138         bcx, trans_eager_binop(bcx, expr, dst_datum.ty, op,
2139                                dst_ty, dst, rhs_ty, rhs));
2140     return result_datum.store_to(bcx, dst_datum.val);
2141 }
2142
2143 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2144                         datum: Datum<'tcx, Expr>,
2145                         expr: &hir::Expr)
2146                         -> DatumBlock<'blk, 'tcx, Expr> {
2147     let mut bcx = bcx;
2148
2149     // Ensure cleanup of `datum` if not already scheduled and obtain
2150     // a "by ref" pointer.
2151     let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2152
2153     // Compute final type. Note that we are loose with the region and
2154     // mutability, since those things don't matter in trans.
2155     let referent_ty = lv_datum.ty;
2156     let ptr_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), referent_ty);
2157
2158     // Get the pointer.
2159     let llref = lv_datum.to_llref();
2160
2161     // Construct the resulting datum, using what was the "by ref"
2162     // ValueRef of type `referent_ty` to be the "by value" ValueRef
2163     // of type `&referent_ty`.
2164     // Pointers to DST types are non-immediate, and therefore still use ByRef.
2165     let kind  = if type_is_sized(bcx.tcx(), referent_ty) { ByValue } else { ByRef };
2166     DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(kind))))
2167 }
2168
2169 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2170                               expr: &hir::Expr,
2171                               datum: Datum<'tcx, Expr>,
2172                               times: usize)
2173                               -> DatumBlock<'blk, 'tcx, Expr> {
2174     let mut bcx = bcx;
2175     let mut datum = datum;
2176     for i in 0..times {
2177         let method_call = MethodCall::autoderef(expr.id, i as u32);
2178         datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2179     }
2180     DatumBlock { bcx: bcx, datum: datum }
2181 }
2182
2183 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2184                           expr: &hir::Expr,
2185                           datum: Datum<'tcx, Expr>,
2186                           method_call: MethodCall)
2187                           -> DatumBlock<'blk, 'tcx, Expr> {
2188     let ccx = bcx.ccx();
2189
2190     debug!("deref_once(expr={:?}, datum={}, method_call={:?})",
2191            expr,
2192            datum.to_string(ccx),
2193            method_call);
2194
2195     let mut bcx = bcx;
2196
2197     // Check for overloaded deref.
2198     let method_ty = ccx.tcx()
2199                        .tables
2200                        .borrow()
2201                        .method_map
2202                        .get(&method_call).map(|method| method.ty);
2203
2204     let datum = match method_ty {
2205         Some(method_ty) => {
2206             let method_ty = monomorphize_type(bcx, method_ty);
2207
2208             // Overloaded. Evaluate `trans_overloaded_op`, which will
2209             // invoke the user's deref() method, which basically
2210             // converts from the `Smaht<T>` pointer that we have into
2211             // a `&T` pointer.  We can then proceed down the normal
2212             // path (below) to dereference that `&T`.
2213             let datum = if method_call.autoderef == 0 {
2214                 datum
2215             } else {
2216                 // Always perform an AutoPtr when applying an overloaded auto-deref
2217                 unpack_datum!(bcx, auto_ref(bcx, datum, expr))
2218             };
2219
2220             let ref_ty = // invoked methods have their LB regions instantiated
2221                 ccx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
2222             let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2223
2224             unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2225                                                     datum, None, Some(SaveIn(scratch.val)),
2226                                                     false));
2227             scratch.to_expr_datum()
2228         }
2229         None => {
2230             // Not overloaded. We already have a pointer we know how to deref.
2231             datum
2232         }
2233     };
2234
2235     let r = match datum.ty.sty {
2236         ty::TyBox(content_ty) => {
2237             // Make sure we have an lvalue datum here to get the
2238             // proper cleanups scheduled
2239             let datum = unpack_datum!(
2240                 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2241
2242             if type_is_sized(bcx.tcx(), content_ty) {
2243                 let ptr = load_ty(bcx, datum.val, datum.ty);
2244                 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(datum.kind)))
2245             } else {
2246                 // A fat pointer and a DST lvalue have the same representation
2247                 // just different types. Since there is no temporary for `*e`
2248                 // here (because it is unsized), we cannot emulate the sized
2249                 // object code path for running drop glue and free. Instead,
2250                 // we schedule cleanup for `e`, turning it into an lvalue.
2251
2252                 let lval = Lvalue::new("expr::deref_once ty_uniq");
2253                 let datum = Datum::new(datum.val, content_ty, LvalueExpr(lval));
2254                 DatumBlock::new(bcx, datum)
2255             }
2256         }
2257
2258         ty::TyRawPtr(ty::TypeAndMut { ty: content_ty, .. }) |
2259         ty::TyRef(_, ty::TypeAndMut { ty: content_ty, .. }) => {
2260             let lval = Lvalue::new("expr::deref_once ptr");
2261             if type_is_sized(bcx.tcx(), content_ty) {
2262                 let ptr = datum.to_llscalarish(bcx);
2263
2264                 // Always generate an lvalue datum, even if datum.mode is
2265                 // an rvalue.  This is because datum.mode is only an
2266                 // rvalue for non-owning pointers like &T or *T, in which
2267                 // case cleanup *is* scheduled elsewhere, by the true
2268                 // owner (or, in the case of *T, by the user).
2269                 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(lval)))
2270             } else {
2271                 // A fat pointer and a DST lvalue have the same representation
2272                 // just different types.
2273                 DatumBlock::new(bcx, Datum::new(datum.val, content_ty, LvalueExpr(lval)))
2274             }
2275         }
2276
2277         _ => {
2278             bcx.tcx().sess.span_bug(
2279                 expr.span,
2280                 &format!("deref invoked on expr of invalid type {:?}",
2281                         datum.ty));
2282         }
2283     };
2284
2285     debug!("deref_once(expr={}, method_call={:?}, result={})",
2286            expr.id, method_call, r.datum.to_string(ccx));
2287
2288     return r;
2289 }
2290
2291 #[derive(Debug)]
2292 enum OverflowOp {
2293     Add,
2294     Sub,
2295     Mul,
2296     Shl,
2297     Shr,
2298 }
2299
2300 impl OverflowOp {
2301     fn codegen_strategy(&self) -> OverflowCodegen {
2302         use self::OverflowCodegen::{ViaIntrinsic, ViaInputCheck};
2303         match *self {
2304             OverflowOp::Add => ViaIntrinsic(OverflowOpViaIntrinsic::Add),
2305             OverflowOp::Sub => ViaIntrinsic(OverflowOpViaIntrinsic::Sub),
2306             OverflowOp::Mul => ViaIntrinsic(OverflowOpViaIntrinsic::Mul),
2307
2308             OverflowOp::Shl => ViaInputCheck(OverflowOpViaInputCheck::Shl),
2309             OverflowOp::Shr => ViaInputCheck(OverflowOpViaInputCheck::Shr),
2310         }
2311     }
2312 }
2313
2314 enum OverflowCodegen {
2315     ViaIntrinsic(OverflowOpViaIntrinsic),
2316     ViaInputCheck(OverflowOpViaInputCheck),
2317 }
2318
2319 enum OverflowOpViaInputCheck { Shl, Shr, }
2320
2321 #[derive(Debug)]
2322 enum OverflowOpViaIntrinsic { Add, Sub, Mul, }
2323
2324 impl OverflowOpViaIntrinsic {
2325     fn to_intrinsic<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>, lhs_ty: Ty) -> ValueRef {
2326         let name = self.to_intrinsic_name(bcx.tcx(), lhs_ty);
2327         bcx.ccx().get_intrinsic(&name)
2328     }
2329     fn to_intrinsic_name(&self, tcx: &ty::ctxt, ty: Ty) -> &'static str {
2330         use rustc_front::hir::IntTy::*;
2331         use rustc_front::hir::UintTy::*;
2332         use middle::ty::{TyInt, TyUint};
2333
2334         let new_sty = match ty.sty {
2335             TyInt(TyIs) => match &tcx.sess.target.target.target_pointer_width[..] {
2336                 "32" => TyInt(TyI32),
2337                 "64" => TyInt(TyI64),
2338                 _ => panic!("unsupported target word size")
2339             },
2340             TyUint(TyUs) => match &tcx.sess.target.target.target_pointer_width[..] {
2341                 "32" => TyUint(TyU32),
2342                 "64" => TyUint(TyU64),
2343                 _ => panic!("unsupported target word size")
2344             },
2345             ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
2346             _ => panic!("tried to get overflow intrinsic for {:?} applied to non-int type",
2347                         *self)
2348         };
2349
2350         match *self {
2351             OverflowOpViaIntrinsic::Add => match new_sty {
2352                 TyInt(TyI8) => "llvm.sadd.with.overflow.i8",
2353                 TyInt(TyI16) => "llvm.sadd.with.overflow.i16",
2354                 TyInt(TyI32) => "llvm.sadd.with.overflow.i32",
2355                 TyInt(TyI64) => "llvm.sadd.with.overflow.i64",
2356
2357                 TyUint(TyU8) => "llvm.uadd.with.overflow.i8",
2358                 TyUint(TyU16) => "llvm.uadd.with.overflow.i16",
2359                 TyUint(TyU32) => "llvm.uadd.with.overflow.i32",
2360                 TyUint(TyU64) => "llvm.uadd.with.overflow.i64",
2361
2362                 _ => unreachable!(),
2363             },
2364             OverflowOpViaIntrinsic::Sub => match new_sty {
2365                 TyInt(TyI8) => "llvm.ssub.with.overflow.i8",
2366                 TyInt(TyI16) => "llvm.ssub.with.overflow.i16",
2367                 TyInt(TyI32) => "llvm.ssub.with.overflow.i32",
2368                 TyInt(TyI64) => "llvm.ssub.with.overflow.i64",
2369
2370                 TyUint(TyU8) => "llvm.usub.with.overflow.i8",
2371                 TyUint(TyU16) => "llvm.usub.with.overflow.i16",
2372                 TyUint(TyU32) => "llvm.usub.with.overflow.i32",
2373                 TyUint(TyU64) => "llvm.usub.with.overflow.i64",
2374
2375                 _ => unreachable!(),
2376             },
2377             OverflowOpViaIntrinsic::Mul => match new_sty {
2378                 TyInt(TyI8) => "llvm.smul.with.overflow.i8",
2379                 TyInt(TyI16) => "llvm.smul.with.overflow.i16",
2380                 TyInt(TyI32) => "llvm.smul.with.overflow.i32",
2381                 TyInt(TyI64) => "llvm.smul.with.overflow.i64",
2382
2383                 TyUint(TyU8) => "llvm.umul.with.overflow.i8",
2384                 TyUint(TyU16) => "llvm.umul.with.overflow.i16",
2385                 TyUint(TyU32) => "llvm.umul.with.overflow.i32",
2386                 TyUint(TyU64) => "llvm.umul.with.overflow.i64",
2387
2388                 _ => unreachable!(),
2389             },
2390         }
2391     }
2392
2393     fn build_intrinsic_call<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>,
2394                                         info: NodeIdAndSpan,
2395                                         lhs_t: Ty<'tcx>, lhs: ValueRef,
2396                                         rhs: ValueRef,
2397                                         binop_debug_loc: DebugLoc)
2398                                         -> (Block<'blk, 'tcx>, ValueRef) {
2399         let llfn = self.to_intrinsic(bcx, lhs_t);
2400
2401         let val = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
2402         let result = ExtractValue(bcx, val, 0); // iN operation result
2403         let overflow = ExtractValue(bcx, val, 1); // i1 "did it overflow?"
2404
2405         let cond = ICmp(bcx, llvm::IntEQ, overflow, C_integral(Type::i1(bcx.ccx()), 1, false),
2406                         binop_debug_loc);
2407
2408         let expect = bcx.ccx().get_intrinsic(&"llvm.expect.i1");
2409         Call(bcx, expect, &[cond, C_integral(Type::i1(bcx.ccx()), 0, false)],
2410              None, binop_debug_loc);
2411
2412         let bcx =
2413             base::with_cond(bcx, cond, |bcx|
2414                 controlflow::trans_fail(bcx, info,
2415                     InternedString::new("arithmetic operation overflowed")));
2416
2417         (bcx, result)
2418     }
2419 }
2420
2421 impl OverflowOpViaInputCheck {
2422     fn build_with_input_check<'blk, 'tcx>(&self,
2423                                           bcx: Block<'blk, 'tcx>,
2424                                           info: NodeIdAndSpan,
2425                                           lhs_t: Ty<'tcx>,
2426                                           lhs: ValueRef,
2427                                           rhs: ValueRef,
2428                                           binop_debug_loc: DebugLoc)
2429                                           -> (Block<'blk, 'tcx>, ValueRef)
2430     {
2431         let lhs_llty = val_ty(lhs);
2432         let rhs_llty = val_ty(rhs);
2433
2434         // Panic if any bits are set outside of bits that we always
2435         // mask in.
2436         //
2437         // Note that the mask's value is derived from the LHS type
2438         // (since that is where the 32/64 distinction is relevant) but
2439         // the mask's type must match the RHS type (since they will
2440         // both be fed into a and-binop)
2441         let invert_mask = shift_mask_val(bcx, lhs_llty, rhs_llty, true);
2442
2443         let outer_bits = And(bcx, rhs, invert_mask, binop_debug_loc);
2444         let cond = build_nonzero_check(bcx, outer_bits, binop_debug_loc);
2445         let result = match *self {
2446             OverflowOpViaInputCheck::Shl =>
2447                 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2448             OverflowOpViaInputCheck::Shr =>
2449                 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2450         };
2451         let bcx =
2452             base::with_cond(bcx, cond, |bcx|
2453                 controlflow::trans_fail(bcx, info,
2454                     InternedString::new("shift operation overflowed")));
2455
2456         (bcx, result)
2457     }
2458 }
2459
2460 fn shift_mask_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2461                               llty: Type,
2462                               mask_llty: Type,
2463                               invert: bool) -> ValueRef {
2464     let kind = llty.kind();
2465     match kind {
2466         TypeKind::Integer => {
2467             // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
2468             let val = llty.int_width() - 1;
2469             if invert {
2470                 C_integral(mask_llty, !val, true)
2471             } else {
2472                 C_integral(mask_llty, val, false)
2473             }
2474         },
2475         TypeKind::Vector => {
2476             let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
2477             VectorSplat(bcx, mask_llty.vector_length(), mask)
2478         },
2479         _ => panic!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
2480     }
2481 }
2482
2483 // Check if an integer or vector contains a nonzero element.
2484 fn build_nonzero_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2485                                    value: ValueRef,
2486                                    binop_debug_loc: DebugLoc) -> ValueRef {
2487     let llty = val_ty(value);
2488     let kind = llty.kind();
2489     match kind {
2490         TypeKind::Integer => ICmp(bcx, llvm::IntNE, value, C_null(llty), binop_debug_loc),
2491         TypeKind::Vector => {
2492             // Check if any elements of the vector are nonzero by treating
2493             // it as a wide integer and checking if the integer is nonzero.
2494             let width = llty.vector_length() as u64 * llty.element_type().int_width();
2495             let int_value = BitCast(bcx, value, Type::ix(bcx.ccx(), width));
2496             build_nonzero_check(bcx, int_value, binop_debug_loc)
2497         },
2498         _ => panic!("build_nonzero_check: expected Integer or Vector, found {:?}", kind),
2499     }
2500 }
2501
2502 // To avoid UB from LLVM, these two functions mask RHS with an
2503 // appropriate mask unconditionally (i.e. the fallback behavior for
2504 // all shifts). For 32- and 64-bit types, this matches the semantics
2505 // of Java. (See related discussion on #1877 and #10183.)
2506
2507 fn build_unchecked_lshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2508                                       lhs: ValueRef,
2509                                       rhs: ValueRef,
2510                                       binop_debug_loc: DebugLoc) -> ValueRef {
2511     let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShl, lhs, rhs);
2512     // #1877, #10183: Ensure that input is always valid
2513     let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2514     Shl(bcx, lhs, rhs, binop_debug_loc)
2515 }
2516
2517 fn build_unchecked_rshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2518                                       lhs_t: Ty<'tcx>,
2519                                       lhs: ValueRef,
2520                                       rhs: ValueRef,
2521                                       binop_debug_loc: DebugLoc) -> ValueRef {
2522     let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShr, lhs, rhs);
2523     // #1877, #10183: Ensure that input is always valid
2524     let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2525     let is_signed = lhs_t.is_signed();
2526     if is_signed {
2527         AShr(bcx, lhs, rhs, binop_debug_loc)
2528     } else {
2529         LShr(bcx, lhs, rhs, binop_debug_loc)
2530     }
2531 }
2532
2533 fn shift_mask_rhs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2534                               rhs: ValueRef,
2535                               debug_loc: DebugLoc) -> ValueRef {
2536     let rhs_llty = val_ty(rhs);
2537     And(bcx, rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false), debug_loc)
2538 }
2539
2540 fn with_overflow_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, oop: OverflowOp, info: NodeIdAndSpan,
2541                                    lhs_t: Ty<'tcx>, lhs: ValueRef,
2542                                    rhs: ValueRef,
2543                                    binop_debug_loc: DebugLoc)
2544                                    -> (Block<'blk, 'tcx>, ValueRef) {
2545     if bcx.unreachable.get() { return (bcx, _Undef(lhs)); }
2546     if bcx.ccx().check_overflow() {
2547
2548         match oop.codegen_strategy() {
2549             OverflowCodegen::ViaIntrinsic(oop) =>
2550                 oop.build_intrinsic_call(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2551             OverflowCodegen::ViaInputCheck(oop) =>
2552                 oop.build_with_input_check(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2553         }
2554     } else {
2555         let res = match oop {
2556             OverflowOp::Add => Add(bcx, lhs, rhs, binop_debug_loc),
2557             OverflowOp::Sub => Sub(bcx, lhs, rhs, binop_debug_loc),
2558             OverflowOp::Mul => Mul(bcx, lhs, rhs, binop_debug_loc),
2559
2560             OverflowOp::Shl =>
2561                 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2562             OverflowOp::Shr =>
2563                 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2564         };
2565         (bcx, res)
2566     }
2567 }
2568
2569 /// We categorize expressions into three kinds.  The distinction between
2570 /// lvalue/rvalue is fundamental to the language.  The distinction between the
2571 /// two kinds of rvalues is an artifact of trans which reflects how we will
2572 /// generate code for that kind of expression.  See trans/expr.rs for more
2573 /// information.
2574 #[derive(Copy, Clone)]
2575 enum ExprKind {
2576     Lvalue,
2577     RvalueDps,
2578     RvalueDatum,
2579     RvalueStmt
2580 }
2581
2582 fn expr_kind(tcx: &ty::ctxt, expr: &hir::Expr) -> ExprKind {
2583     if tcx.is_method_call(expr.id) {
2584         // Overloaded operations are generally calls, and hence they are
2585         // generated via DPS, but there are a few exceptions:
2586         return match expr.node {
2587             // `a += b` has a unit result.
2588             hir::ExprAssignOp(..) => ExprKind::RvalueStmt,
2589
2590             // the deref method invoked for `*a` always yields an `&T`
2591             hir::ExprUnary(hir::UnDeref, _) => ExprKind::Lvalue,
2592
2593             // the index method invoked for `a[i]` always yields an `&T`
2594             hir::ExprIndex(..) => ExprKind::Lvalue,
2595
2596             // in the general case, result could be any type, use DPS
2597             _ => ExprKind::RvalueDps
2598         };
2599     }
2600
2601     match expr.node {
2602         hir::ExprPath(..) => {
2603             match tcx.resolve_expr(expr) {
2604                 def::DefStruct(_) | def::DefVariant(..) => {
2605                     if let ty::TyBareFn(..) = tcx.node_id_to_type(expr.id).sty {
2606                         // ctor function
2607                         ExprKind::RvalueDatum
2608                     } else {
2609                         ExprKind::RvalueDps
2610                     }
2611                 }
2612
2613                 // Special case: A unit like struct's constructor must be called without () at the
2614                 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
2615                 // of unit structs this is should not be interpreted as function pointer but as
2616                 // call to the constructor.
2617                 def::DefFn(_, true) => ExprKind::RvalueDps,
2618
2619                 // Fn pointers are just scalar values.
2620                 def::DefFn(..) | def::DefMethod(..) => ExprKind::RvalueDatum,
2621
2622                 // Note: there is actually a good case to be made that
2623                 // DefArg's, particularly those of immediate type, ought to
2624                 // considered rvalues.
2625                 def::DefStatic(..) |
2626                 def::DefUpvar(..) |
2627                 def::DefLocal(..) => ExprKind::Lvalue,
2628
2629                 def::DefConst(..) |
2630                 def::DefAssociatedConst(..) => ExprKind::RvalueDatum,
2631
2632                 def => {
2633                     tcx.sess.span_bug(
2634                         expr.span,
2635                         &format!("uncategorized def for expr {}: {:?}",
2636                                 expr.id,
2637                                 def));
2638                 }
2639             }
2640         }
2641
2642         hir::ExprUnary(hir::UnDeref, _) |
2643         hir::ExprField(..) |
2644         hir::ExprTupField(..) |
2645         hir::ExprIndex(..) => {
2646             ExprKind::Lvalue
2647         }
2648
2649         hir::ExprCall(..) |
2650         hir::ExprMethodCall(..) |
2651         hir::ExprStruct(..) |
2652         hir::ExprRange(..) |
2653         hir::ExprTup(..) |
2654         hir::ExprIf(..) |
2655         hir::ExprMatch(..) |
2656         hir::ExprClosure(..) |
2657         hir::ExprBlock(..) |
2658         hir::ExprRepeat(..) |
2659         hir::ExprVec(..) => {
2660             ExprKind::RvalueDps
2661         }
2662
2663         hir::ExprLit(ref lit) if rustc_front::util::lit_is_str(&**lit) => {
2664             ExprKind::RvalueDps
2665         }
2666
2667         hir::ExprBreak(..) |
2668         hir::ExprAgain(..) |
2669         hir::ExprRet(..) |
2670         hir::ExprWhile(..) |
2671         hir::ExprLoop(..) |
2672         hir::ExprAssign(..) |
2673         hir::ExprInlineAsm(..) |
2674         hir::ExprAssignOp(..) => {
2675             ExprKind::RvalueStmt
2676         }
2677
2678         hir::ExprLit(_) | // Note: LitStr is carved out above
2679         hir::ExprUnary(..) |
2680         hir::ExprBox(None, _) |
2681         hir::ExprAddrOf(..) |
2682         hir::ExprBinary(..) |
2683         hir::ExprCast(..) => {
2684             ExprKind::RvalueDatum
2685         }
2686
2687         hir::ExprBox(Some(ref place), _) => {
2688             // Special case `Box<T>` for now:
2689             let def_id = match tcx.def_map.borrow().get(&place.id) {
2690                 Some(def) => def.def_id(),
2691                 None => panic!("no def for place"),
2692             };
2693             if tcx.lang_items.exchange_heap() == Some(def_id) {
2694                 ExprKind::RvalueDatum
2695             } else {
2696                 ExprKind::RvalueDps
2697             }
2698         }
2699
2700         hir::ExprParen(ref e) => expr_kind(tcx, &**e),
2701     }
2702 }