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