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