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