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