]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/expr.rs
Auto merge of #28286 - matklad:remove-dead-code, r=eddyb
[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 fn trans_fat_ptr_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1686                                    binop_expr: &hir::Expr,
1687                                    binop_ty: Ty<'tcx>,
1688                                    op: hir::BinOp,
1689                                    lhs: Datum<'tcx, Rvalue>,
1690                                    rhs: Datum<'tcx, Rvalue>)
1691                                    -> DatumBlock<'blk, 'tcx, Expr>
1692 {
1693     let debug_loc = binop_expr.debug_loc();
1694
1695     let lhs_addr = Load(bcx, GEPi(bcx, lhs.val, &[0, abi::FAT_PTR_ADDR]));
1696     let lhs_extra = Load(bcx, GEPi(bcx, lhs.val, &[0, abi::FAT_PTR_EXTRA]));
1697
1698     let rhs_addr = Load(bcx, GEPi(bcx, rhs.val, &[0, abi::FAT_PTR_ADDR]));
1699     let rhs_extra = Load(bcx, GEPi(bcx, rhs.val, &[0, abi::FAT_PTR_EXTRA]));
1700
1701     let val = match op.node {
1702         hir::BiEq => {
1703             let addr_eq = ICmp(bcx, llvm::IntEQ, lhs_addr, rhs_addr, debug_loc);
1704             let extra_eq = ICmp(bcx, llvm::IntEQ, lhs_extra, rhs_extra, debug_loc);
1705             And(bcx, addr_eq, extra_eq, debug_loc)
1706         }
1707         hir::BiNe => {
1708             let addr_eq = ICmp(bcx, llvm::IntNE, lhs_addr, rhs_addr, debug_loc);
1709             let extra_eq = ICmp(bcx, llvm::IntNE, lhs_extra, rhs_extra, debug_loc);
1710             Or(bcx, addr_eq, extra_eq, debug_loc)
1711         }
1712         hir::BiLe | hir::BiLt | hir::BiGe | hir::BiGt => {
1713             // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
1714             let (op, strict_op) = match op.node {
1715                 hir::BiLt => (llvm::IntULT, llvm::IntULT),
1716                 hir::BiLe => (llvm::IntULE, llvm::IntULT),
1717                 hir::BiGt => (llvm::IntUGT, llvm::IntUGT),
1718                 hir::BiGe => (llvm::IntUGE, llvm::IntUGT),
1719                 _ => unreachable!()
1720             };
1721
1722             let addr_eq = ICmp(bcx, llvm::IntEQ, lhs_addr, rhs_addr, debug_loc);
1723             let extra_op = ICmp(bcx, op, lhs_extra, rhs_extra, debug_loc);
1724             let addr_eq_extra_op = And(bcx, addr_eq, extra_op, debug_loc);
1725
1726             let addr_strict = ICmp(bcx, strict_op, lhs_addr, rhs_addr, debug_loc);
1727             Or(bcx, addr_strict, addr_eq_extra_op, debug_loc)
1728         }
1729         _ => {
1730             bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1731         }
1732     };
1733
1734     immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1735 }
1736
1737 fn trans_scalar_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1738                                   binop_expr: &hir::Expr,
1739                                   binop_ty: Ty<'tcx>,
1740                                   op: hir::BinOp,
1741                                   lhs: Datum<'tcx, Rvalue>,
1742                                   rhs: Datum<'tcx, Rvalue>)
1743                                   -> DatumBlock<'blk, 'tcx, Expr>
1744 {
1745     let _icx = push_ctxt("trans_scalar_binop");
1746
1747     let tcx = bcx.tcx();
1748     let lhs_t = lhs.ty;
1749     assert!(!lhs_t.is_simd());
1750     let is_float = lhs_t.is_fp();
1751     let is_signed = lhs_t.is_signed();
1752     let info = expr_info(binop_expr);
1753
1754     let binop_debug_loc = binop_expr.debug_loc();
1755
1756     let mut bcx = bcx;
1757     let lhs = lhs.to_llscalarish(bcx);
1758     let rhs = rhs.to_llscalarish(bcx);
1759     let val = match op.node {
1760       hir::BiAdd => {
1761         if is_float {
1762             FAdd(bcx, lhs, rhs, binop_debug_loc)
1763         } else {
1764             let (newbcx, res) = with_overflow_check(
1765                 bcx, OverflowOp::Add, info, lhs_t, lhs, rhs, binop_debug_loc);
1766             bcx = newbcx;
1767             res
1768         }
1769       }
1770       hir::BiSub => {
1771         if is_float {
1772             FSub(bcx, lhs, rhs, binop_debug_loc)
1773         } else {
1774             let (newbcx, res) = with_overflow_check(
1775                 bcx, OverflowOp::Sub, info, lhs_t, lhs, rhs, binop_debug_loc);
1776             bcx = newbcx;
1777             res
1778         }
1779       }
1780       hir::BiMul => {
1781         if is_float {
1782             FMul(bcx, lhs, rhs, binop_debug_loc)
1783         } else {
1784             let (newbcx, res) = with_overflow_check(
1785                 bcx, OverflowOp::Mul, info, lhs_t, lhs, rhs, binop_debug_loc);
1786             bcx = newbcx;
1787             res
1788         }
1789       }
1790       hir::BiDiv => {
1791         if is_float {
1792             FDiv(bcx, lhs, rhs, binop_debug_loc)
1793         } else {
1794             // Only zero-check integers; fp /0 is NaN
1795             bcx = base::fail_if_zero_or_overflows(bcx,
1796                                                   expr_info(binop_expr),
1797                                                   op,
1798                                                   lhs,
1799                                                   rhs,
1800                                                   lhs_t);
1801             if is_signed {
1802                 SDiv(bcx, lhs, rhs, binop_debug_loc)
1803             } else {
1804                 UDiv(bcx, lhs, rhs, binop_debug_loc)
1805             }
1806         }
1807       }
1808       hir::BiRem => {
1809         if is_float {
1810             // LLVM currently always lowers the `frem` instructions appropriate
1811             // library calls typically found in libm. Notably f64 gets wired up
1812             // to `fmod` and f32 gets wired up to `fmodf`. Inconveniently for
1813             // us, 32-bit MSVC does not actually have a `fmodf` symbol, it's
1814             // instead just an inline function in a header that goes up to a
1815             // f64, uses `fmod`, and then comes back down to a f32.
1816             //
1817             // Although LLVM knows that `fmodf` doesn't exist on MSVC, it will
1818             // still unconditionally lower frem instructions over 32-bit floats
1819             // to a call to `fmodf`. To work around this we special case MSVC
1820             // 32-bit float rem instructions and instead do the call out to
1821             // `fmod` ourselves.
1822             //
1823             // Note that this is currently duplicated with src/libcore/ops.rs
1824             // which does the same thing, and it would be nice to perhaps unify
1825             // these two implementations on day! Also note that we call `fmod`
1826             // for both 32 and 64-bit floats because if we emit any FRem
1827             // instruction at all then LLVM is capable of optimizing it into a
1828             // 32-bit FRem (which we're trying to avoid).
1829             let use_fmod = tcx.sess.target.target.options.is_like_msvc &&
1830                            tcx.sess.target.target.arch == "x86";
1831             if use_fmod {
1832                 let f64t = Type::f64(bcx.ccx());
1833                 let fty = Type::func(&[f64t, f64t], &f64t);
1834                 let llfn = declare::declare_cfn(bcx.ccx(), "fmod", fty,
1835                                                 tcx.types.f64);
1836                 if lhs_t == tcx.types.f32 {
1837                     let lhs = FPExt(bcx, lhs, f64t);
1838                     let rhs = FPExt(bcx, rhs, f64t);
1839                     let res = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
1840                     FPTrunc(bcx, res, Type::f32(bcx.ccx()))
1841                 } else {
1842                     Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc)
1843                 }
1844             } else {
1845                 FRem(bcx, lhs, rhs, binop_debug_loc)
1846             }
1847         } else {
1848             // Only zero-check integers; fp %0 is NaN
1849             bcx = base::fail_if_zero_or_overflows(bcx,
1850                                                   expr_info(binop_expr),
1851                                                   op, lhs, rhs, lhs_t);
1852             if is_signed {
1853                 SRem(bcx, lhs, rhs, binop_debug_loc)
1854             } else {
1855                 URem(bcx, lhs, rhs, binop_debug_loc)
1856             }
1857         }
1858       }
1859       hir::BiBitOr => Or(bcx, lhs, rhs, binop_debug_loc),
1860       hir::BiBitAnd => And(bcx, lhs, rhs, binop_debug_loc),
1861       hir::BiBitXor => Xor(bcx, lhs, rhs, binop_debug_loc),
1862       hir::BiShl => {
1863           let (newbcx, res) = with_overflow_check(
1864               bcx, OverflowOp::Shl, info, lhs_t, lhs, rhs, binop_debug_loc);
1865           bcx = newbcx;
1866           res
1867       }
1868       hir::BiShr => {
1869           let (newbcx, res) = with_overflow_check(
1870               bcx, OverflowOp::Shr, info, lhs_t, lhs, rhs, binop_debug_loc);
1871           bcx = newbcx;
1872           res
1873       }
1874       hir::BiEq | hir::BiNe | hir::BiLt | hir::BiGe | hir::BiLe | hir::BiGt => {
1875           base::compare_scalar_types(bcx, lhs, rhs, lhs_t, op.node, binop_debug_loc)
1876       }
1877       _ => {
1878         bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1879       }
1880     };
1881
1882     immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1883 }
1884
1885 // refinement types would obviate the need for this
1886 enum lazy_binop_ty {
1887     lazy_and,
1888     lazy_or,
1889 }
1890
1891 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1892                                 binop_expr: &hir::Expr,
1893                                 op: lazy_binop_ty,
1894                                 a: &hir::Expr,
1895                                 b: &hir::Expr)
1896                                 -> DatumBlock<'blk, 'tcx, Expr> {
1897     let _icx = push_ctxt("trans_lazy_binop");
1898     let binop_ty = expr_ty(bcx, binop_expr);
1899     let fcx = bcx.fcx;
1900
1901     let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1902     let lhs = lhs.to_llscalarish(past_lhs);
1903
1904     if past_lhs.unreachable.get() {
1905         return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1906     }
1907
1908     let join = fcx.new_id_block("join", binop_expr.id);
1909     let before_rhs = fcx.new_id_block("before_rhs", b.id);
1910
1911     match op {
1912       lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb, DebugLoc::None),
1913       lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb, DebugLoc::None)
1914     }
1915
1916     let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1917     let rhs = rhs.to_llscalarish(past_rhs);
1918
1919     if past_rhs.unreachable.get() {
1920         return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1921     }
1922
1923     Br(past_rhs, join.llbb, DebugLoc::None);
1924     let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1925                   &[past_lhs.llbb, past_rhs.llbb]);
1926
1927     return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1928 }
1929
1930 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1931                             expr: &hir::Expr,
1932                             op: hir::BinOp,
1933                             lhs: &hir::Expr,
1934                             rhs: &hir::Expr)
1935                             -> DatumBlock<'blk, 'tcx, Expr> {
1936     let _icx = push_ctxt("trans_binary");
1937     let ccx = bcx.ccx();
1938
1939     // if overloaded, would be RvalueDpsExpr
1940     assert!(!ccx.tcx().is_method_call(expr.id));
1941
1942     match op.node {
1943         hir::BiAnd => {
1944             trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1945         }
1946         hir::BiOr => {
1947             trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1948         }
1949         _ => {
1950             let mut bcx = bcx;
1951             let binop_ty = expr_ty(bcx, expr);
1952
1953             let lhs = unpack_datum!(bcx, trans(bcx, lhs));
1954             let lhs = unpack_datum!(bcx, lhs.to_rvalue_datum(bcx, "binop_lhs"));
1955             debug!("trans_binary (expr {}): lhs={}",
1956                    expr.id, lhs.to_string(ccx));
1957             let rhs = unpack_datum!(bcx, trans(bcx, rhs));
1958             let rhs = unpack_datum!(bcx, rhs.to_rvalue_datum(bcx, "binop_rhs"));
1959             debug!("trans_binary (expr {}): rhs={}",
1960                    expr.id, rhs.to_string(ccx));
1961
1962             if type_is_fat_ptr(ccx.tcx(), lhs.ty) {
1963                 assert!(type_is_fat_ptr(ccx.tcx(), rhs.ty),
1964                         "built-in binary operators on fat pointers are homogeneous");
1965                 trans_fat_ptr_binop(bcx, expr, binop_ty, op, lhs, rhs)
1966             } else {
1967                 assert!(!type_is_fat_ptr(ccx.tcx(), rhs.ty),
1968                         "built-in binary operators on fat pointers are homogeneous");
1969                 trans_scalar_binop(bcx, expr, binop_ty, op, lhs, rhs)
1970             }
1971         }
1972     }
1973 }
1974
1975 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1976                                    expr: &hir::Expr,
1977                                    method_call: MethodCall,
1978                                    lhs: Datum<'tcx, Expr>,
1979                                    rhs: Option<(Datum<'tcx, Expr>, ast::NodeId)>,
1980                                    dest: Option<Dest>,
1981                                    autoref: bool)
1982                                    -> Result<'blk, 'tcx> {
1983     callee::trans_call_inner(bcx,
1984                              expr.debug_loc(),
1985                              |bcx, arg_cleanup_scope| {
1986                                 meth::trans_method_callee(bcx,
1987                                                           method_call,
1988                                                           None,
1989                                                           arg_cleanup_scope)
1990                              },
1991                              callee::ArgOverloadedOp(lhs, rhs, autoref),
1992                              dest)
1993 }
1994
1995 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1996                                          expr: &hir::Expr,
1997                                          callee: &'a hir::Expr,
1998                                          args: &'a [P<hir::Expr>],
1999                                          dest: Option<Dest>)
2000                                          -> Block<'blk, 'tcx> {
2001     debug!("trans_overloaded_call {}", expr.id);
2002     let method_call = MethodCall::expr(expr.id);
2003     let mut all_args = vec!(callee);
2004     all_args.extend(args.iter().map(|e| &**e));
2005     unpack_result!(bcx,
2006                    callee::trans_call_inner(bcx,
2007                                             expr.debug_loc(),
2008                                             |bcx, arg_cleanup_scope| {
2009                                                 meth::trans_method_callee(
2010                                                     bcx,
2011                                                     method_call,
2012                                                     None,
2013                                                     arg_cleanup_scope)
2014                                             },
2015                                             callee::ArgOverloadedCall(all_args),
2016                                             dest));
2017     bcx
2018 }
2019
2020 pub fn cast_is_noop<'tcx>(tcx: &ty::ctxt<'tcx>,
2021                           expr: &hir::Expr,
2022                           t_in: Ty<'tcx>,
2023                           t_out: Ty<'tcx>)
2024                           -> bool {
2025     if let Some(&CastKind::CoercionCast) = tcx.cast_kinds.borrow().get(&expr.id) {
2026         return true;
2027     }
2028
2029     match (t_in.builtin_deref(true, ty::NoPreference),
2030            t_out.builtin_deref(true, ty::NoPreference)) {
2031         (Some(ty::TypeAndMut{ ty: t_in, .. }), Some(ty::TypeAndMut{ ty: t_out, .. })) => {
2032             t_in == t_out
2033         }
2034         _ => {
2035             // This condition isn't redundant with the check for CoercionCast:
2036             // different types can be substituted into the same type, and
2037             // == equality can be overconservative if there are regions.
2038             t_in == t_out
2039         }
2040     }
2041 }
2042
2043 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2044                               expr: &hir::Expr,
2045                               id: ast::NodeId)
2046                               -> DatumBlock<'blk, 'tcx, Expr>
2047 {
2048     use middle::cast::CastTy::*;
2049     use middle::cast::IntTy::*;
2050
2051     fn int_cast(bcx: Block,
2052                 lldsttype: Type,
2053                 llsrctype: Type,
2054                 llsrc: ValueRef,
2055                 signed: bool)
2056                 -> ValueRef
2057     {
2058         let _icx = push_ctxt("int_cast");
2059         let srcsz = llsrctype.int_width();
2060         let dstsz = lldsttype.int_width();
2061         return if dstsz == srcsz {
2062             BitCast(bcx, llsrc, lldsttype)
2063         } else if srcsz > dstsz {
2064             TruncOrBitCast(bcx, llsrc, lldsttype)
2065         } else if signed {
2066             SExtOrBitCast(bcx, llsrc, lldsttype)
2067         } else {
2068             ZExtOrBitCast(bcx, llsrc, lldsttype)
2069         }
2070     }
2071
2072     fn float_cast(bcx: Block,
2073                   lldsttype: Type,
2074                   llsrctype: Type,
2075                   llsrc: ValueRef)
2076                   -> ValueRef
2077     {
2078         let _icx = push_ctxt("float_cast");
2079         let srcsz = llsrctype.float_width();
2080         let dstsz = lldsttype.float_width();
2081         return if dstsz > srcsz {
2082             FPExt(bcx, llsrc, lldsttype)
2083         } else if srcsz > dstsz {
2084             FPTrunc(bcx, llsrc, lldsttype)
2085         } else { llsrc };
2086     }
2087
2088     let _icx = push_ctxt("trans_cast");
2089     let mut bcx = bcx;
2090     let ccx = bcx.ccx();
2091
2092     let t_in = expr_ty_adjusted(bcx, expr);
2093     let t_out = node_id_type(bcx, id);
2094
2095     debug!("trans_cast({:?} as {:?})", t_in, t_out);
2096     let mut ll_t_in = type_of::arg_type_of(ccx, t_in);
2097     let ll_t_out = type_of::arg_type_of(ccx, t_out);
2098     // Convert the value to be cast into a ValueRef, either by-ref or
2099     // by-value as appropriate given its type:
2100     let mut datum = unpack_datum!(bcx, trans(bcx, expr));
2101
2102     let datum_ty = monomorphize_type(bcx, datum.ty);
2103
2104     if cast_is_noop(bcx.tcx(), expr, datum_ty, t_out) {
2105         datum.ty = t_out;
2106         return DatumBlock::new(bcx, datum);
2107     }
2108
2109     if type_is_fat_ptr(bcx.tcx(), t_in) {
2110         assert!(datum.kind.is_by_ref());
2111         if type_is_fat_ptr(bcx.tcx(), t_out) {
2112             return DatumBlock::new(bcx, Datum::new(
2113                 PointerCast(bcx, datum.val, ll_t_out.ptr_to()),
2114                 t_out,
2115                 Rvalue::new(ByRef)
2116             )).to_expr_datumblock();
2117         } else {
2118             // Return the address
2119             return immediate_rvalue_bcx(bcx,
2120                                         PointerCast(bcx,
2121                                                     Load(bcx, get_dataptr(bcx, datum.val)),
2122                                                     ll_t_out),
2123                                         t_out).to_expr_datumblock();
2124         }
2125     }
2126
2127     let r_t_in = CastTy::from_ty(t_in).expect("bad input type for cast");
2128     let r_t_out = CastTy::from_ty(t_out).expect("bad output type for cast");
2129
2130     let (llexpr, signed) = if let Int(CEnum) = r_t_in {
2131         let repr = adt::represent_type(ccx, t_in);
2132         let datum = unpack_datum!(
2133             bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
2134         let llexpr_ptr = datum.to_llref();
2135         let discr = adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
2136         ll_t_in = val_ty(discr);
2137         (discr, adt::is_discr_signed(&*repr))
2138     } else {
2139         (datum.to_llscalarish(bcx), t_in.is_signed())
2140     };
2141
2142     let newval = match (r_t_in, r_t_out) {
2143         (Ptr(_), Ptr(_)) | (FnPtr, Ptr(_)) | (RPtr(_), Ptr(_)) => {
2144             PointerCast(bcx, llexpr, ll_t_out)
2145         }
2146         (Ptr(_), Int(_)) | (FnPtr, Int(_)) => PtrToInt(bcx, llexpr, ll_t_out),
2147         (Int(_), Ptr(_)) => IntToPtr(bcx, llexpr, ll_t_out),
2148
2149         (Int(_), Int(_)) => int_cast(bcx, ll_t_out, ll_t_in, llexpr, signed),
2150         (Float, Float) => float_cast(bcx, ll_t_out, ll_t_in, llexpr),
2151         (Int(_), Float) if signed => SIToFP(bcx, llexpr, ll_t_out),
2152         (Int(_), Float) => UIToFP(bcx, llexpr, ll_t_out),
2153         (Float, Int(I)) => FPToSI(bcx, llexpr, ll_t_out),
2154         (Float, Int(_)) => FPToUI(bcx, llexpr, ll_t_out),
2155
2156         _ => ccx.sess().span_bug(expr.span,
2157                                   &format!("translating unsupported cast: \
2158                                             {:?} -> {:?}",
2159                                            t_in,
2160                                            t_out)
2161                                  )
2162     };
2163     return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
2164 }
2165
2166 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2167                                expr: &hir::Expr,
2168                                op: hir::BinOp,
2169                                dst: &hir::Expr,
2170                                src: &hir::Expr)
2171                                -> Block<'blk, 'tcx> {
2172     let _icx = push_ctxt("trans_assign_op");
2173     let mut bcx = bcx;
2174
2175     debug!("trans_assign_op(expr={:?})", expr);
2176
2177     // User-defined operator methods cannot be used with `+=` etc right now
2178     assert!(!bcx.tcx().is_method_call(expr.id));
2179
2180     // Evaluate LHS (destination), which should be an lvalue
2181     let dst = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2182     assert!(!bcx.fcx.type_needs_drop(dst.ty));
2183     let lhs = load_ty(bcx, dst.val, dst.ty);
2184     let lhs = immediate_rvalue(lhs, dst.ty);
2185
2186     // Evaluate RHS - FIXME(#28160) this sucks
2187     let rhs = unpack_datum!(bcx, trans(bcx, &*src));
2188     let rhs = unpack_datum!(bcx, rhs.to_rvalue_datum(bcx, "assign_op_rhs"));
2189
2190     // Perform computation and store the result
2191     let result_datum = unpack_datum!(
2192         bcx, trans_scalar_binop(bcx, expr, dst.ty, op, lhs, rhs));
2193     return result_datum.store_to(bcx, dst.val);
2194 }
2195
2196 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2197                         datum: Datum<'tcx, Expr>,
2198                         expr: &hir::Expr)
2199                         -> DatumBlock<'blk, 'tcx, Expr> {
2200     let mut bcx = bcx;
2201
2202     // Ensure cleanup of `datum` if not already scheduled and obtain
2203     // a "by ref" pointer.
2204     let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2205
2206     // Compute final type. Note that we are loose with the region and
2207     // mutability, since those things don't matter in trans.
2208     let referent_ty = lv_datum.ty;
2209     let ptr_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), referent_ty);
2210
2211     // Get the pointer.
2212     let llref = lv_datum.to_llref();
2213
2214     // Construct the resulting datum, using what was the "by ref"
2215     // ValueRef of type `referent_ty` to be the "by value" ValueRef
2216     // of type `&referent_ty`.
2217     // Pointers to DST types are non-immediate, and therefore still use ByRef.
2218     let kind  = if type_is_sized(bcx.tcx(), referent_ty) { ByValue } else { ByRef };
2219     DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(kind))))
2220 }
2221
2222 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2223                               expr: &hir::Expr,
2224                               datum: Datum<'tcx, Expr>,
2225                               times: usize)
2226                               -> DatumBlock<'blk, 'tcx, Expr> {
2227     let mut bcx = bcx;
2228     let mut datum = datum;
2229     for i in 0..times {
2230         let method_call = MethodCall::autoderef(expr.id, i as u32);
2231         datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2232     }
2233     DatumBlock { bcx: bcx, datum: datum }
2234 }
2235
2236 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2237                           expr: &hir::Expr,
2238                           datum: Datum<'tcx, Expr>,
2239                           method_call: MethodCall)
2240                           -> DatumBlock<'blk, 'tcx, Expr> {
2241     let ccx = bcx.ccx();
2242
2243     debug!("deref_once(expr={:?}, datum={}, method_call={:?})",
2244            expr,
2245            datum.to_string(ccx),
2246            method_call);
2247
2248     let mut bcx = bcx;
2249
2250     // Check for overloaded deref.
2251     let method_ty = ccx.tcx()
2252                        .tables
2253                        .borrow()
2254                        .method_map
2255                        .get(&method_call).map(|method| method.ty);
2256
2257     let datum = match method_ty {
2258         Some(method_ty) => {
2259             let method_ty = monomorphize_type(bcx, method_ty);
2260
2261             // Overloaded. Evaluate `trans_overloaded_op`, which will
2262             // invoke the user's deref() method, which basically
2263             // converts from the `Smaht<T>` pointer that we have into
2264             // a `&T` pointer.  We can then proceed down the normal
2265             // path (below) to dereference that `&T`.
2266             let datum = if method_call.autoderef == 0 {
2267                 datum
2268             } else {
2269                 // Always perform an AutoPtr when applying an overloaded auto-deref
2270                 unpack_datum!(bcx, auto_ref(bcx, datum, expr))
2271             };
2272
2273             let ref_ty = // invoked methods have their LB regions instantiated
2274                 ccx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
2275             let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2276
2277             unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2278                                                     datum, None, Some(SaveIn(scratch.val)),
2279                                                     false));
2280             scratch.to_expr_datum()
2281         }
2282         None => {
2283             // Not overloaded. We already have a pointer we know how to deref.
2284             datum
2285         }
2286     };
2287
2288     let r = match datum.ty.sty {
2289         ty::TyBox(content_ty) => {
2290             // Make sure we have an lvalue datum here to get the
2291             // proper cleanups scheduled
2292             let datum = unpack_datum!(
2293                 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2294
2295             if type_is_sized(bcx.tcx(), content_ty) {
2296                 let ptr = load_ty(bcx, datum.val, datum.ty);
2297                 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(datum.kind)))
2298             } else {
2299                 // A fat pointer and a DST lvalue have the same representation
2300                 // just different types. Since there is no temporary for `*e`
2301                 // here (because it is unsized), we cannot emulate the sized
2302                 // object code path for running drop glue and free. Instead,
2303                 // we schedule cleanup for `e`, turning it into an lvalue.
2304
2305                 let lval = Lvalue::new("expr::deref_once ty_uniq");
2306                 let datum = Datum::new(datum.val, content_ty, LvalueExpr(lval));
2307                 DatumBlock::new(bcx, datum)
2308             }
2309         }
2310
2311         ty::TyRawPtr(ty::TypeAndMut { ty: content_ty, .. }) |
2312         ty::TyRef(_, ty::TypeAndMut { ty: content_ty, .. }) => {
2313             let lval = Lvalue::new("expr::deref_once ptr");
2314             if type_is_sized(bcx.tcx(), content_ty) {
2315                 let ptr = datum.to_llscalarish(bcx);
2316
2317                 // Always generate an lvalue datum, even if datum.mode is
2318                 // an rvalue.  This is because datum.mode is only an
2319                 // rvalue for non-owning pointers like &T or *T, in which
2320                 // case cleanup *is* scheduled elsewhere, by the true
2321                 // owner (or, in the case of *T, by the user).
2322                 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(lval)))
2323             } else {
2324                 // A fat pointer and a DST lvalue have the same representation
2325                 // just different types.
2326                 DatumBlock::new(bcx, Datum::new(datum.val, content_ty, LvalueExpr(lval)))
2327             }
2328         }
2329
2330         _ => {
2331             bcx.tcx().sess.span_bug(
2332                 expr.span,
2333                 &format!("deref invoked on expr of invalid type {:?}",
2334                         datum.ty));
2335         }
2336     };
2337
2338     debug!("deref_once(expr={}, method_call={:?}, result={})",
2339            expr.id, method_call, r.datum.to_string(ccx));
2340
2341     return r;
2342 }
2343
2344 #[derive(Debug)]
2345 enum OverflowOp {
2346     Add,
2347     Sub,
2348     Mul,
2349     Shl,
2350     Shr,
2351 }
2352
2353 impl OverflowOp {
2354     fn codegen_strategy(&self) -> OverflowCodegen {
2355         use self::OverflowCodegen::{ViaIntrinsic, ViaInputCheck};
2356         match *self {
2357             OverflowOp::Add => ViaIntrinsic(OverflowOpViaIntrinsic::Add),
2358             OverflowOp::Sub => ViaIntrinsic(OverflowOpViaIntrinsic::Sub),
2359             OverflowOp::Mul => ViaIntrinsic(OverflowOpViaIntrinsic::Mul),
2360
2361             OverflowOp::Shl => ViaInputCheck(OverflowOpViaInputCheck::Shl),
2362             OverflowOp::Shr => ViaInputCheck(OverflowOpViaInputCheck::Shr),
2363         }
2364     }
2365 }
2366
2367 enum OverflowCodegen {
2368     ViaIntrinsic(OverflowOpViaIntrinsic),
2369     ViaInputCheck(OverflowOpViaInputCheck),
2370 }
2371
2372 enum OverflowOpViaInputCheck { Shl, Shr, }
2373
2374 #[derive(Debug)]
2375 enum OverflowOpViaIntrinsic { Add, Sub, Mul, }
2376
2377 impl OverflowOpViaIntrinsic {
2378     fn to_intrinsic<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>, lhs_ty: Ty) -> ValueRef {
2379         let name = self.to_intrinsic_name(bcx.tcx(), lhs_ty);
2380         bcx.ccx().get_intrinsic(&name)
2381     }
2382     fn to_intrinsic_name(&self, tcx: &ty::ctxt, ty: Ty) -> &'static str {
2383         use rustc_front::hir::IntTy::*;
2384         use rustc_front::hir::UintTy::*;
2385         use middle::ty::{TyInt, TyUint};
2386
2387         let new_sty = match ty.sty {
2388             TyInt(TyIs) => match &tcx.sess.target.target.target_pointer_width[..] {
2389                 "32" => TyInt(TyI32),
2390                 "64" => TyInt(TyI64),
2391                 _ => panic!("unsupported target word size")
2392             },
2393             TyUint(TyUs) => match &tcx.sess.target.target.target_pointer_width[..] {
2394                 "32" => TyUint(TyU32),
2395                 "64" => TyUint(TyU64),
2396                 _ => panic!("unsupported target word size")
2397             },
2398             ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
2399             _ => panic!("tried to get overflow intrinsic for {:?} applied to non-int type",
2400                         *self)
2401         };
2402
2403         match *self {
2404             OverflowOpViaIntrinsic::Add => match new_sty {
2405                 TyInt(TyI8) => "llvm.sadd.with.overflow.i8",
2406                 TyInt(TyI16) => "llvm.sadd.with.overflow.i16",
2407                 TyInt(TyI32) => "llvm.sadd.with.overflow.i32",
2408                 TyInt(TyI64) => "llvm.sadd.with.overflow.i64",
2409
2410                 TyUint(TyU8) => "llvm.uadd.with.overflow.i8",
2411                 TyUint(TyU16) => "llvm.uadd.with.overflow.i16",
2412                 TyUint(TyU32) => "llvm.uadd.with.overflow.i32",
2413                 TyUint(TyU64) => "llvm.uadd.with.overflow.i64",
2414
2415                 _ => unreachable!(),
2416             },
2417             OverflowOpViaIntrinsic::Sub => match new_sty {
2418                 TyInt(TyI8) => "llvm.ssub.with.overflow.i8",
2419                 TyInt(TyI16) => "llvm.ssub.with.overflow.i16",
2420                 TyInt(TyI32) => "llvm.ssub.with.overflow.i32",
2421                 TyInt(TyI64) => "llvm.ssub.with.overflow.i64",
2422
2423                 TyUint(TyU8) => "llvm.usub.with.overflow.i8",
2424                 TyUint(TyU16) => "llvm.usub.with.overflow.i16",
2425                 TyUint(TyU32) => "llvm.usub.with.overflow.i32",
2426                 TyUint(TyU64) => "llvm.usub.with.overflow.i64",
2427
2428                 _ => unreachable!(),
2429             },
2430             OverflowOpViaIntrinsic::Mul => match new_sty {
2431                 TyInt(TyI8) => "llvm.smul.with.overflow.i8",
2432                 TyInt(TyI16) => "llvm.smul.with.overflow.i16",
2433                 TyInt(TyI32) => "llvm.smul.with.overflow.i32",
2434                 TyInt(TyI64) => "llvm.smul.with.overflow.i64",
2435
2436                 TyUint(TyU8) => "llvm.umul.with.overflow.i8",
2437                 TyUint(TyU16) => "llvm.umul.with.overflow.i16",
2438                 TyUint(TyU32) => "llvm.umul.with.overflow.i32",
2439                 TyUint(TyU64) => "llvm.umul.with.overflow.i64",
2440
2441                 _ => unreachable!(),
2442             },
2443         }
2444     }
2445
2446     fn build_intrinsic_call<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>,
2447                                         info: NodeIdAndSpan,
2448                                         lhs_t: Ty<'tcx>, lhs: ValueRef,
2449                                         rhs: ValueRef,
2450                                         binop_debug_loc: DebugLoc)
2451                                         -> (Block<'blk, 'tcx>, ValueRef) {
2452         let llfn = self.to_intrinsic(bcx, lhs_t);
2453
2454         let val = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
2455         let result = ExtractValue(bcx, val, 0); // iN operation result
2456         let overflow = ExtractValue(bcx, val, 1); // i1 "did it overflow?"
2457
2458         let cond = ICmp(bcx, llvm::IntEQ, overflow, C_integral(Type::i1(bcx.ccx()), 1, false),
2459                         binop_debug_loc);
2460
2461         let expect = bcx.ccx().get_intrinsic(&"llvm.expect.i1");
2462         Call(bcx, expect, &[cond, C_integral(Type::i1(bcx.ccx()), 0, false)],
2463              None, binop_debug_loc);
2464
2465         let bcx =
2466             base::with_cond(bcx, cond, |bcx|
2467                 controlflow::trans_fail(bcx, info,
2468                     InternedString::new("arithmetic operation overflowed")));
2469
2470         (bcx, result)
2471     }
2472 }
2473
2474 impl OverflowOpViaInputCheck {
2475     fn build_with_input_check<'blk, 'tcx>(&self,
2476                                           bcx: Block<'blk, 'tcx>,
2477                                           info: NodeIdAndSpan,
2478                                           lhs_t: Ty<'tcx>,
2479                                           lhs: ValueRef,
2480                                           rhs: ValueRef,
2481                                           binop_debug_loc: DebugLoc)
2482                                           -> (Block<'blk, 'tcx>, ValueRef)
2483     {
2484         let lhs_llty = val_ty(lhs);
2485         let rhs_llty = val_ty(rhs);
2486
2487         // Panic if any bits are set outside of bits that we always
2488         // mask in.
2489         //
2490         // Note that the mask's value is derived from the LHS type
2491         // (since that is where the 32/64 distinction is relevant) but
2492         // the mask's type must match the RHS type (since they will
2493         // both be fed into a and-binop)
2494         let invert_mask = shift_mask_val(bcx, lhs_llty, rhs_llty, true);
2495
2496         let outer_bits = And(bcx, rhs, invert_mask, binop_debug_loc);
2497         let cond = build_nonzero_check(bcx, outer_bits, binop_debug_loc);
2498         let result = match *self {
2499             OverflowOpViaInputCheck::Shl =>
2500                 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2501             OverflowOpViaInputCheck::Shr =>
2502                 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2503         };
2504         let bcx =
2505             base::with_cond(bcx, cond, |bcx|
2506                 controlflow::trans_fail(bcx, info,
2507                     InternedString::new("shift operation overflowed")));
2508
2509         (bcx, result)
2510     }
2511 }
2512
2513 fn shift_mask_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2514                               llty: Type,
2515                               mask_llty: Type,
2516                               invert: bool) -> ValueRef {
2517     let kind = llty.kind();
2518     match kind {
2519         TypeKind::Integer => {
2520             // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
2521             let val = llty.int_width() - 1;
2522             if invert {
2523                 C_integral(mask_llty, !val, true)
2524             } else {
2525                 C_integral(mask_llty, val, false)
2526             }
2527         },
2528         TypeKind::Vector => {
2529             let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
2530             VectorSplat(bcx, mask_llty.vector_length(), mask)
2531         },
2532         _ => panic!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
2533     }
2534 }
2535
2536 // Check if an integer or vector contains a nonzero element.
2537 fn build_nonzero_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2538                                    value: ValueRef,
2539                                    binop_debug_loc: DebugLoc) -> ValueRef {
2540     let llty = val_ty(value);
2541     let kind = llty.kind();
2542     match kind {
2543         TypeKind::Integer => ICmp(bcx, llvm::IntNE, value, C_null(llty), binop_debug_loc),
2544         TypeKind::Vector => {
2545             // Check if any elements of the vector are nonzero by treating
2546             // it as a wide integer and checking if the integer is nonzero.
2547             let width = llty.vector_length() as u64 * llty.element_type().int_width();
2548             let int_value = BitCast(bcx, value, Type::ix(bcx.ccx(), width));
2549             build_nonzero_check(bcx, int_value, binop_debug_loc)
2550         },
2551         _ => panic!("build_nonzero_check: expected Integer or Vector, found {:?}", kind),
2552     }
2553 }
2554
2555 // To avoid UB from LLVM, these two functions mask RHS with an
2556 // appropriate mask unconditionally (i.e. the fallback behavior for
2557 // all shifts). For 32- and 64-bit types, this matches the semantics
2558 // of Java. (See related discussion on #1877 and #10183.)
2559
2560 fn build_unchecked_lshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2561                                       lhs: ValueRef,
2562                                       rhs: ValueRef,
2563                                       binop_debug_loc: DebugLoc) -> ValueRef {
2564     let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShl, lhs, rhs);
2565     // #1877, #10183: Ensure that input is always valid
2566     let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2567     Shl(bcx, lhs, rhs, binop_debug_loc)
2568 }
2569
2570 fn build_unchecked_rshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2571                                       lhs_t: Ty<'tcx>,
2572                                       lhs: ValueRef,
2573                                       rhs: ValueRef,
2574                                       binop_debug_loc: DebugLoc) -> ValueRef {
2575     let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShr, lhs, rhs);
2576     // #1877, #10183: Ensure that input is always valid
2577     let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2578     let is_signed = lhs_t.is_signed();
2579     if is_signed {
2580         AShr(bcx, lhs, rhs, binop_debug_loc)
2581     } else {
2582         LShr(bcx, lhs, rhs, binop_debug_loc)
2583     }
2584 }
2585
2586 fn shift_mask_rhs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2587                               rhs: ValueRef,
2588                               debug_loc: DebugLoc) -> ValueRef {
2589     let rhs_llty = val_ty(rhs);
2590     And(bcx, rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false), debug_loc)
2591 }
2592
2593 fn with_overflow_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, oop: OverflowOp, info: NodeIdAndSpan,
2594                                    lhs_t: Ty<'tcx>, lhs: ValueRef,
2595                                    rhs: ValueRef,
2596                                    binop_debug_loc: DebugLoc)
2597                                    -> (Block<'blk, 'tcx>, ValueRef) {
2598     if bcx.unreachable.get() { return (bcx, _Undef(lhs)); }
2599     if bcx.ccx().check_overflow() {
2600
2601         match oop.codegen_strategy() {
2602             OverflowCodegen::ViaIntrinsic(oop) =>
2603                 oop.build_intrinsic_call(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2604             OverflowCodegen::ViaInputCheck(oop) =>
2605                 oop.build_with_input_check(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2606         }
2607     } else {
2608         let res = match oop {
2609             OverflowOp::Add => Add(bcx, lhs, rhs, binop_debug_loc),
2610             OverflowOp::Sub => Sub(bcx, lhs, rhs, binop_debug_loc),
2611             OverflowOp::Mul => Mul(bcx, lhs, rhs, binop_debug_loc),
2612
2613             OverflowOp::Shl =>
2614                 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2615             OverflowOp::Shr =>
2616                 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2617         };
2618         (bcx, res)
2619     }
2620 }
2621
2622 /// We categorize expressions into three kinds.  The distinction between
2623 /// lvalue/rvalue is fundamental to the language.  The distinction between the
2624 /// two kinds of rvalues is an artifact of trans which reflects how we will
2625 /// generate code for that kind of expression.  See trans/expr.rs for more
2626 /// information.
2627 #[derive(Copy, Clone)]
2628 enum ExprKind {
2629     Lvalue,
2630     RvalueDps,
2631     RvalueDatum,
2632     RvalueStmt
2633 }
2634
2635 fn expr_kind(tcx: &ty::ctxt, expr: &hir::Expr) -> ExprKind {
2636     if tcx.is_method_call(expr.id) {
2637         // Overloaded operations are generally calls, and hence they are
2638         // generated via DPS, but there are a few exceptions:
2639         return match expr.node {
2640             // `a += b` has a unit result.
2641             hir::ExprAssignOp(..) => ExprKind::RvalueStmt,
2642
2643             // the deref method invoked for `*a` always yields an `&T`
2644             hir::ExprUnary(hir::UnDeref, _) => ExprKind::Lvalue,
2645
2646             // the index method invoked for `a[i]` always yields an `&T`
2647             hir::ExprIndex(..) => ExprKind::Lvalue,
2648
2649             // in the general case, result could be any type, use DPS
2650             _ => ExprKind::RvalueDps
2651         };
2652     }
2653
2654     match expr.node {
2655         hir::ExprPath(..) => {
2656             match tcx.resolve_expr(expr) {
2657                 def::DefStruct(_) | def::DefVariant(..) => {
2658                     if let ty::TyBareFn(..) = tcx.node_id_to_type(expr.id).sty {
2659                         // ctor function
2660                         ExprKind::RvalueDatum
2661                     } else {
2662                         ExprKind::RvalueDps
2663                     }
2664                 }
2665
2666                 // Special case: A unit like struct's constructor must be called without () at the
2667                 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
2668                 // of unit structs this is should not be interpreted as function pointer but as
2669                 // call to the constructor.
2670                 def::DefFn(_, true) => ExprKind::RvalueDps,
2671
2672                 // Fn pointers are just scalar values.
2673                 def::DefFn(..) | def::DefMethod(..) => ExprKind::RvalueDatum,
2674
2675                 // Note: there is actually a good case to be made that
2676                 // DefArg's, particularly those of immediate type, ought to
2677                 // considered rvalues.
2678                 def::DefStatic(..) |
2679                 def::DefUpvar(..) |
2680                 def::DefLocal(..) => ExprKind::Lvalue,
2681
2682                 def::DefConst(..) |
2683                 def::DefAssociatedConst(..) => ExprKind::RvalueDatum,
2684
2685                 def => {
2686                     tcx.sess.span_bug(
2687                         expr.span,
2688                         &format!("uncategorized def for expr {}: {:?}",
2689                                 expr.id,
2690                                 def));
2691                 }
2692             }
2693         }
2694
2695         hir::ExprUnary(hir::UnDeref, _) |
2696         hir::ExprField(..) |
2697         hir::ExprTupField(..) |
2698         hir::ExprIndex(..) => {
2699             ExprKind::Lvalue
2700         }
2701
2702         hir::ExprCall(..) |
2703         hir::ExprMethodCall(..) |
2704         hir::ExprStruct(..) |
2705         hir::ExprRange(..) |
2706         hir::ExprTup(..) |
2707         hir::ExprIf(..) |
2708         hir::ExprMatch(..) |
2709         hir::ExprClosure(..) |
2710         hir::ExprBlock(..) |
2711         hir::ExprRepeat(..) |
2712         hir::ExprVec(..) => {
2713             ExprKind::RvalueDps
2714         }
2715
2716         hir::ExprLit(ref lit) if rustc_front::util::lit_is_str(&**lit) => {
2717             ExprKind::RvalueDps
2718         }
2719
2720         hir::ExprBreak(..) |
2721         hir::ExprAgain(..) |
2722         hir::ExprRet(..) |
2723         hir::ExprWhile(..) |
2724         hir::ExprLoop(..) |
2725         hir::ExprAssign(..) |
2726         hir::ExprInlineAsm(..) |
2727         hir::ExprAssignOp(..) => {
2728             ExprKind::RvalueStmt
2729         }
2730
2731         hir::ExprLit(_) | // Note: LitStr is carved out above
2732         hir::ExprUnary(..) |
2733         hir::ExprBox(None, _) |
2734         hir::ExprAddrOf(..) |
2735         hir::ExprBinary(..) |
2736         hir::ExprCast(..) => {
2737             ExprKind::RvalueDatum
2738         }
2739
2740         hir::ExprBox(Some(ref place), _) => {
2741             // Special case `Box<T>` for now:
2742             let def_id = match tcx.def_map.borrow().get(&place.id) {
2743                 Some(def) => def.def_id(),
2744                 None => panic!("no def for place"),
2745             };
2746             if tcx.lang_items.exchange_heap() == Some(def_id) {
2747                 ExprKind::RvalueDatum
2748             } else {
2749                 ExprKind::RvalueDps
2750             }
2751         }
2752
2753         hir::ExprParen(ref e) => expr_kind(tcx, &**e),
2754     }
2755 }