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.
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.
11 //! # Translation of Expressions
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.
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:
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`.
32 //! Public entry points:
34 //! - `trans_into(bcx, expr, dest) -> bcx`: evaluates an expression,
35 //! storing the result into `dest`. This is the preferred form, if you
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
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.
47 //! - `trans_var -> Datum`: looks up a local variable, upvar or static.
49 #![allow(non_camel_case_types)]
51 pub use self::Dest::*;
52 use self::lazy_binop_ty::*;
54 use llvm::{self, ValueRef, TypeKind};
55 use middle::const_qualif::ConstQualif;
57 use middle::subst::Substs;
58 use trans::{_match, abi, adt, asm, base, closure, consts, controlflow};
61 use trans::callee::{Callee, ArgExprs, ArgOverloadedCall, ArgOverloadedOp};
62 use trans::cleanup::{self, CleanupMethods, DropHintMethods};
65 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
71 use trans::value::Value;
73 use middle::ty::adjustment::{AdjustDerefRef, AdjustReifyFnPointer};
74 use middle::ty::adjustment::{AdjustUnsafeFnPointer, AdjustMutToConstPointer};
75 use middle::ty::adjustment::CustomCoerceUnsized;
76 use middle::ty::{self, Ty, TyCtxt};
77 use middle::ty::MethodCall;
78 use middle::ty::cast::{CastKind, CastTy};
79 use util::common::indenter;
80 use trans::machine::{llsize_of, llsize_of_alloc};
81 use trans::type_::Type;
86 use syntax::{ast, codemap};
87 use syntax::parse::token::InternedString;
93 // These are passed around by the code generating functions to track the
94 // destination of a computation's value.
96 #[derive(Copy, Clone, PartialEq)]
102 impl fmt::Debug for Dest {
103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105 SaveIn(v) => write!(f, "SaveIn({:?})", Value(v)),
106 Ignore => f.write_str("Ignore")
111 /// This function is equivalent to `trans(bcx, expr).store_to_dest(dest)` but it may generate
112 /// better optimized LLVM code.
113 pub fn trans_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
116 -> Block<'blk, 'tcx> {
119 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
121 if adjustment_required(bcx, expr) {
122 // use trans, which may be less efficient but
123 // which will perform the adjustments:
124 let datum = unpack_datum!(bcx, trans(bcx, expr));
125 return datum.store_to_dest(bcx, dest, expr.id);
128 let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
129 if !qualif.intersects(ConstQualif::NOT_CONST | ConstQualif::NEEDS_DROP) {
130 if !qualif.intersects(ConstQualif::PREFER_IN_PLACE) {
131 if let SaveIn(lldest) = dest {
132 match consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
133 bcx.fcx.param_substs,
134 consts::TrueConst::No) {
136 // Cast pointer to destination, because constants
137 // have different types.
138 let lldest = PointerCast(bcx, lldest, val_ty(global));
139 memcpy_ty(bcx, lldest, global, expr_ty_adjusted(bcx, expr));
142 Err(consts::ConstEvalFailure::Runtime(_)) => {
143 // in case const evaluation errors, translate normally
144 // debug assertions catch the same errors
147 Err(consts::ConstEvalFailure::Compiletime(_)) => {
153 // If we see a const here, that's because it evaluates to a type with zero size. We
154 // should be able to just discard it, since const expressions are guaranteed not to
155 // have side effects. This seems to be reached through tuple struct constructors being
156 // passed zero-size constants.
157 if let hir::ExprPath(..) = expr.node {
158 match bcx.def(expr.id) {
159 Def::Const(_) | Def::AssociatedConst(_) => {
160 assert!(type_is_zero_size(bcx.ccx(), bcx.tcx().node_id_to_type(expr.id)));
167 // Even if we don't have a value to emit, and the expression
168 // doesn't have any side-effects, we still have to translate the
169 // body of any closures.
170 // FIXME: Find a better way of handling this case.
172 // The only way we're going to see a `const` at this point is if
173 // it prefers in-place instantiation, likely because it contains
174 // `[x; N]` somewhere within.
176 hir::ExprPath(..) => {
177 match bcx.def(expr.id) {
178 Def::Const(did) | Def::AssociatedConst(did) => {
179 let empty_substs = bcx.tcx().mk_substs(Substs::trans_empty());
180 let const_expr = consts::get_const_expr(bcx.ccx(), did, expr,
182 // Temporarily get cleanup scopes out of the way,
183 // as they require sub-expressions to be contained
184 // inside the current AST scope.
185 // These should record no cleanups anyways, `const`
186 // can't have destructors.
187 let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
189 // Lock emitted debug locations to the location of
190 // the constant reference expression.
191 debuginfo::with_source_location_override(bcx.fcx,
194 bcx = trans_into(bcx, const_expr, dest)
196 let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
198 assert!(scopes.is_empty());
209 debug!("trans_into() expr={:?}", expr);
211 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
215 bcx.fcx.push_ast_cleanup_scope(cleanup_debug_loc);
217 let kind = expr_kind(bcx.tcx(), expr);
219 ExprKind::Lvalue | ExprKind::RvalueDatum => {
220 trans_unadjusted(bcx, expr).store_to_dest(dest, expr.id)
222 ExprKind::RvalueDps => {
223 trans_rvalue_dps_unadjusted(bcx, expr, dest)
225 ExprKind::RvalueStmt => {
226 trans_rvalue_stmt_unadjusted(bcx, expr)
230 bcx.fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id)
233 /// Translates an expression, returning a datum (and new block) encapsulating the result. When
234 /// possible, it is preferred to use `trans_into`, as that may avoid creating a temporary on the
236 pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
238 -> DatumBlock<'blk, 'tcx, Expr> {
239 debug!("trans(expr={:?})", expr);
243 let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
244 let adjusted_global = !qualif.intersects(ConstQualif::NON_STATIC_BORROWS);
245 let global = if !qualif.intersects(ConstQualif::NOT_CONST | ConstQualif::NEEDS_DROP) {
246 match consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
247 bcx.fcx.param_substs,
248 consts::TrueConst::No) {
250 if qualif.intersects(ConstQualif::HAS_STATIC_BORROWS) {
251 // Is borrowed as 'static, must return lvalue.
253 // Cast pointer to global, because constants have different types.
254 let const_ty = expr_ty_adjusted(bcx, expr);
255 let llty = type_of::type_of(bcx.ccx(), const_ty);
256 let global = PointerCast(bcx, global, llty.ptr_to());
257 let datum = Datum::new(global, const_ty, Lvalue::new("expr::trans"));
258 return DatumBlock::new(bcx, datum.to_expr_datum());
261 // Otherwise, keep around and perform adjustments, if needed.
262 let const_ty = if adjusted_global {
263 expr_ty_adjusted(bcx, expr)
268 // This could use a better heuristic.
269 Some(if type_is_immediate(bcx.ccx(), const_ty) {
270 // Cast pointer to global, because constants have different types.
271 let llty = type_of::type_of(bcx.ccx(), const_ty);
272 let global = PointerCast(bcx, global, llty.ptr_to());
273 // Maybe just get the value directly, instead of loading it?
274 immediate_rvalue(load_ty(bcx, global, const_ty), const_ty)
276 let scratch = alloc_ty(bcx, const_ty, "const");
277 call_lifetime_start(bcx, scratch);
278 let lldest = if !const_ty.is_structural() {
279 // Cast pointer to slot, because constants have different types.
280 PointerCast(bcx, scratch, val_ty(global))
282 // In this case, memcpy_ty calls llvm.memcpy after casting both
283 // source and destination to i8*, so we don't need any casts.
286 memcpy_ty(bcx, lldest, global, const_ty);
287 Datum::new(scratch, const_ty, Rvalue::new(ByRef))
290 Err(consts::ConstEvalFailure::Runtime(_)) => {
291 // in case const evaluation errors, translate normally
292 // debug assertions catch the same errors
296 Err(consts::ConstEvalFailure::Compiletime(_)) => {
297 // generate a dummy llvm value
298 let const_ty = expr_ty(bcx, expr);
299 let llty = type_of::type_of(bcx.ccx(), const_ty);
300 let dummy = C_undef(llty.ptr_to());
301 Some(Datum::new(dummy, const_ty, Rvalue::new(ByRef)))
308 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
312 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
313 let datum = match global {
314 Some(rvalue) => rvalue.to_expr_datum(),
315 None => unpack_datum!(bcx, trans_unadjusted(bcx, expr))
317 let datum = if adjusted_global {
318 datum // trans::consts already performed adjustments.
320 unpack_datum!(bcx, apply_adjustments(bcx, expr, datum))
322 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id);
323 return DatumBlock::new(bcx, datum);
326 pub fn get_meta(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
327 StructGEP(bcx, fat_ptr, abi::FAT_PTR_EXTRA)
330 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
331 StructGEP(bcx, fat_ptr, abi::FAT_PTR_ADDR)
334 pub fn copy_fat_ptr(bcx: Block, src_ptr: ValueRef, dst_ptr: ValueRef) {
335 Store(bcx, Load(bcx, get_dataptr(bcx, src_ptr)), get_dataptr(bcx, dst_ptr));
336 Store(bcx, Load(bcx, get_meta(bcx, src_ptr)), get_meta(bcx, dst_ptr));
339 fn adjustment_required<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
340 expr: &hir::Expr) -> bool {
341 let adjustment = match bcx.tcx().tables.borrow().adjustments.get(&expr.id).cloned() {
342 None => { return false; }
346 // Don't skip a conversion from Box<T> to &T, etc.
347 if bcx.tcx().is_overloaded_autoderef(expr.id, 0) {
352 AdjustReifyFnPointer => true,
353 AdjustUnsafeFnPointer | AdjustMutToConstPointer => {
354 // purely a type-level thing
357 AdjustDerefRef(ref adj) => {
358 // We are a bit paranoid about adjustments and thus might have a re-
359 // borrow here which merely derefs and then refs again (it might have
360 // a different region or mutability, but we don't care here).
361 !(adj.autoderefs == 1 && adj.autoref.is_some() && adj.unsize.is_none())
366 /// Helper for trans that apply adjustments from `expr` to `datum`, which should be the unadjusted
367 /// translation of `expr`.
368 fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
370 datum: Datum<'tcx, Expr>)
371 -> DatumBlock<'blk, 'tcx, Expr>
374 let mut datum = datum;
375 let adjustment = match bcx.tcx().tables.borrow().adjustments.get(&expr.id).cloned() {
377 return DatumBlock::new(bcx, datum);
381 debug!("unadjusted datum for expr {:?}: {:?} adjustment={:?}",
382 expr, datum, adjustment);
384 AdjustReifyFnPointer => {
386 ty::TyFnDef(def_id, substs, _) => {
387 datum = Callee::def(bcx.ccx(), def_id, substs)
388 .reify(bcx.ccx()).to_expr_datum();
391 unreachable!("{} cannot be reified to a fn ptr", datum.ty)
395 AdjustUnsafeFnPointer | AdjustMutToConstPointer => {
396 // purely a type-level thing
398 AdjustDerefRef(ref adj) => {
399 let skip_reborrows = if adj.autoderefs == 1 && adj.autoref.is_some() {
400 // We are a bit paranoid about adjustments and thus might have a re-
401 // borrow here which merely derefs and then refs again (it might have
402 // a different region or mutability, but we don't care here).
404 // Don't skip a conversion from Box<T> to &T, etc.
406 if bcx.tcx().is_overloaded_autoderef(expr.id, 0) {
407 // Don't skip an overloaded deref.
419 if adj.autoderefs > skip_reborrows {
421 let lval = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "auto_deref", expr.id));
422 datum = unpack_datum!(bcx, deref_multiple(bcx, expr,
423 lval.to_expr_datum(),
424 adj.autoderefs - skip_reborrows));
427 // (You might think there is a more elegant way to do this than a
428 // skip_reborrows bool, but then you remember that the borrow checker exists).
429 if skip_reborrows == 0 && adj.autoref.is_some() {
430 datum = unpack_datum!(bcx, auto_ref(bcx, datum, expr));
433 if let Some(target) = adj.unsize {
434 // We do not arrange cleanup ourselves; if we already are an
435 // L-value, then cleanup will have already been scheduled (and
436 // the `datum.to_rvalue_datum` call below will emit code to zero
437 // the drop flag when moving out of the L-value). If we are an
438 // R-value, then we do not need to schedule cleanup.
439 let source_datum = unpack_datum!(bcx,
440 datum.to_rvalue_datum(bcx, "__coerce_source"));
442 let target = bcx.monomorphize(&target);
444 let scratch = alloc_ty(bcx, target, "__coerce_target");
445 call_lifetime_start(bcx, scratch);
446 let target_datum = Datum::new(scratch, target,
448 bcx = coerce_unsized(bcx, expr.span, source_datum, target_datum);
449 datum = Datum::new(scratch, target,
450 RvalueExpr(Rvalue::new(ByRef)));
454 debug!("after adjustments, datum={:?}", datum);
455 DatumBlock::new(bcx, datum)
458 fn coerce_unsized<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
460 source: Datum<'tcx, Rvalue>,
461 target: Datum<'tcx, Rvalue>)
462 -> Block<'blk, 'tcx> {
464 debug!("coerce_unsized({:?} -> {:?})", source, target);
466 match (&source.ty.sty, &target.ty.sty) {
467 (&ty::TyBox(a), &ty::TyBox(b)) |
468 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
469 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
470 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
471 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
472 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
473 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
474 let (inner_source, inner_target) = (a, b);
476 let (base, old_info) = if !type_is_sized(bcx.tcx(), inner_source) {
477 // Normally, the source is a thin pointer and we are
478 // adding extra info to make a fat pointer. The exception
479 // is when we are upcasting an existing object fat pointer
480 // to use a different vtable. In that case, we want to
481 // load out the original data pointer so we can repackage
483 (Load(bcx, get_dataptr(bcx, source.val)),
484 Some(Load(bcx, get_meta(bcx, source.val))))
486 let val = if source.kind.is_by_ref() {
487 load_ty(bcx, source.val, source.ty)
494 let info = unsized_info(bcx.ccx(), inner_source, inner_target, old_info);
496 // Compute the base pointer. This doesn't change the pointer value,
497 // but merely its type.
498 let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), inner_target).ptr_to();
499 let base = PointerCast(bcx, base, ptr_ty);
501 Store(bcx, base, get_dataptr(bcx, target.val));
502 Store(bcx, info, get_meta(bcx, target.val));
505 // This can be extended to enums and tuples in the future.
506 // (&ty::TyEnum(def_id_a, _), &ty::TyEnum(def_id_b, _)) |
507 (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
508 assert_eq!(def_id_a, def_id_b);
510 // The target is already by-ref because it's to be written to.
511 let source = unpack_datum!(bcx, source.to_ref_datum(bcx));
512 assert!(target.kind.is_by_ref());
514 let kind = custom_coerce_unsize_info(bcx.ccx(), source.ty, target.ty);
516 let repr_source = adt::represent_type(bcx.ccx(), source.ty);
517 let src_fields = match &*repr_source {
518 &adt::Repr::Univariant(ref s, _) => &s.fields,
519 _ => bcx.sess().span_bug(span,
520 &format!("Non univariant struct? (repr_source: {:?})",
523 let repr_target = adt::represent_type(bcx.ccx(), target.ty);
524 let target_fields = match &*repr_target {
525 &adt::Repr::Univariant(ref s, _) => &s.fields,
526 _ => bcx.sess().span_bug(span,
527 &format!("Non univariant struct? (repr_target: {:?})",
531 let coerce_index = match kind {
532 CustomCoerceUnsized::Struct(i) => i
534 assert!(coerce_index < src_fields.len() && src_fields.len() == target_fields.len());
536 let source_val = adt::MaybeSizedValue::sized(source.val);
537 let target_val = adt::MaybeSizedValue::sized(target.val);
539 let iter = src_fields.iter().zip(target_fields).enumerate();
540 for (i, (src_ty, target_ty)) in iter {
541 let ll_source = adt::trans_field_ptr(bcx, &repr_source, source_val, Disr(0), i);
542 let ll_target = adt::trans_field_ptr(bcx, &repr_target, target_val, Disr(0), i);
544 // If this is the field we need to coerce, recurse on it.
545 if i == coerce_index {
546 coerce_unsized(bcx, span,
547 Datum::new(ll_source, src_ty,
549 Datum::new(ll_target, target_ty,
550 Rvalue::new(ByRef)));
552 // Otherwise, simply copy the data from the source.
553 assert!(src_ty.is_phantom_data() || src_ty == target_ty);
554 memcpy_ty(bcx, ll_target, ll_source, src_ty);
558 _ => bcx.sess().bug(&format!("coerce_unsized: invalid coercion {:?} -> {:?}",
565 /// Translates an expression in "lvalue" mode -- meaning that it returns a reference to the memory
566 /// that the expr represents.
568 /// If this expression is an rvalue, this implies introducing a temporary. In other words,
569 /// something like `x().f` is translated into roughly the equivalent of
571 /// { tmp = x(); tmp.f }
572 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
575 -> DatumBlock<'blk, 'tcx, Lvalue> {
577 let datum = unpack_datum!(bcx, trans(bcx, expr));
578 return datum.to_lvalue_datum(bcx, name, expr.id);
581 /// A version of `trans` that ignores adjustments. You almost certainly do not want to call this
583 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
585 -> DatumBlock<'blk, 'tcx, Expr> {
588 debug!("trans_unadjusted(expr={:?})", expr);
589 let _indenter = indenter();
591 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
593 return match expr_kind(bcx.tcx(), expr) {
594 ExprKind::Lvalue | ExprKind::RvalueDatum => {
595 let datum = unpack_datum!(bcx, {
596 trans_datum_unadjusted(bcx, expr)
599 DatumBlock {bcx: bcx, datum: datum}
602 ExprKind::RvalueStmt => {
603 bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
604 nil(bcx, expr_ty(bcx, expr))
607 ExprKind::RvalueDps => {
608 let ty = expr_ty(bcx, expr);
609 if type_is_zero_size(bcx.ccx(), ty) {
610 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
613 let scratch = rvalue_scratch_datum(bcx, ty, "");
614 bcx = trans_rvalue_dps_unadjusted(
615 bcx, expr, SaveIn(scratch.val));
617 // Note: this is not obviously a good idea. It causes
618 // immediate values to be loaded immediately after a
619 // return from a call or other similar expression,
620 // which in turn leads to alloca's having shorter
621 // lifetimes and hence larger stack frames. However,
622 // in turn it can lead to more register pressure.
623 // Still, in practice it seems to increase
624 // performance, since we have fewer problems with
626 let scratch = unpack_datum!(
627 bcx, scratch.to_appropriate_datum(bcx));
629 DatumBlock::new(bcx, scratch.to_expr_datum())
634 fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: Ty<'tcx>)
635 -> DatumBlock<'blk, 'tcx, Expr> {
636 let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
637 let datum = immediate_rvalue(llval, ty);
638 DatumBlock::new(bcx, datum.to_expr_datum())
642 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
644 -> DatumBlock<'blk, 'tcx, Expr> {
647 let _icx = push_ctxt("trans_datum_unadjusted");
650 hir::ExprType(ref e, _) => {
653 hir::ExprPath(..) => {
654 let var = trans_var(bcx, bcx.def(expr.id));
655 DatumBlock::new(bcx, var.to_expr_datum())
657 hir::ExprField(ref base, name) => {
658 trans_rec_field(bcx, &base, name.node)
660 hir::ExprTupField(ref base, idx) => {
661 trans_rec_tup_field(bcx, &base, idx.node)
663 hir::ExprIndex(ref base, ref idx) => {
664 trans_index(bcx, expr, &base, &idx, MethodCall::expr(expr.id))
666 hir::ExprBox(ref contents) => {
667 // Special case for `Box<T>`
668 let box_ty = expr_ty(bcx, expr);
669 let contents_ty = expr_ty(bcx, &contents);
672 trans_uniq_expr(bcx, expr, box_ty, &contents, contents_ty)
674 _ => bcx.sess().span_bug(expr.span,
675 "expected unique box")
679 hir::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, &lit),
680 hir::ExprBinary(op, ref lhs, ref rhs) => {
681 trans_binary(bcx, expr, op, &lhs, &rhs)
683 hir::ExprUnary(op, ref x) => {
684 trans_unary(bcx, expr, op, &x)
686 hir::ExprAddrOf(_, ref x) => {
688 hir::ExprRepeat(..) | hir::ExprVec(..) => {
689 // Special case for slices.
690 let cleanup_debug_loc =
691 debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
695 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
696 let datum = unpack_datum!(
697 bcx, tvec::trans_slice_vec(bcx, expr, &x));
698 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
699 DatumBlock::new(bcx, datum)
702 trans_addr_of(bcx, expr, &x)
706 hir::ExprCast(ref val, _) => {
707 // Datum output mode means this is a scalar cast:
708 trans_imm_cast(bcx, &val, expr.id)
711 bcx.tcx().sess.span_bug(
713 &format!("trans_rvalue_datum_unadjusted reached \
714 fall-through case: {:?}",
720 fn trans_field<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
723 -> DatumBlock<'blk, 'tcx, Expr> where
724 F: FnOnce(&'blk TyCtxt<'tcx>, &VariantInfo<'tcx>) -> usize,
727 let _icx = push_ctxt("trans_rec_field");
729 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
730 let bare_ty = base_datum.ty;
731 let repr = adt::represent_type(bcx.ccx(), bare_ty);
732 let vinfo = VariantInfo::from_ty(bcx.tcx(), bare_ty, None);
734 let ix = get_idx(bcx.tcx(), &vinfo);
735 let d = base_datum.get_element(
739 adt::trans_field_ptr(bcx, &repr, srcval, vinfo.discr, ix)
742 if type_is_sized(bcx.tcx(), d.ty) {
743 DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
745 let scratch = rvalue_scratch_datum(bcx, d.ty, "");
746 Store(bcx, d.val, get_dataptr(bcx, scratch.val));
747 let info = Load(bcx, get_meta(bcx, base_datum.val));
748 Store(bcx, info, get_meta(bcx, scratch.val));
750 // Always generate an lvalue datum, because this pointer doesn't own
751 // the data and cleanup is scheduled elsewhere.
752 DatumBlock::new(bcx, Datum::new(scratch.val, scratch.ty, LvalueExpr(d.kind)))
756 /// Translates `base.field`.
757 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
760 -> DatumBlock<'blk, 'tcx, Expr> {
761 trans_field(bcx, base, |_, vinfo| vinfo.field_index(field))
764 /// Translates `base.<idx>`.
765 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
768 -> DatumBlock<'blk, 'tcx, Expr> {
769 trans_field(bcx, base, |_, _| idx)
772 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
773 index_expr: &hir::Expr,
776 method_call: MethodCall)
777 -> DatumBlock<'blk, 'tcx, Expr> {
778 //! Translates `base[idx]`.
780 let _icx = push_ctxt("trans_index");
784 let index_expr_debug_loc = index_expr.debug_loc();
786 // Check for overloaded index.
787 let method = ccx.tcx().tables.borrow().method_map.get(&method_call).cloned();
788 let elt_datum = match method {
790 let method_ty = monomorphize_type(bcx, method.ty);
792 let base_datum = unpack_datum!(bcx, trans(bcx, base));
794 // Translate index expression.
795 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
797 let ref_ty = // invoked methods have LB regions instantiated:
798 bcx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
799 let elt_ty = match ref_ty.builtin_deref(true, ty::NoPreference) {
801 bcx.tcx().sess.span_bug(index_expr.span,
802 "index method didn't return a \
803 dereferenceable type?!")
805 Some(elt_tm) => elt_tm.ty,
808 // Overloaded. Invoke the index() method, which basically
809 // yields a `&T` pointer. We can then proceed down the
810 // normal path (below) to dereference that `&T`.
811 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_index_elt");
813 bcx = Callee::method(bcx, method)
814 .call(bcx, index_expr_debug_loc,
815 ArgOverloadedOp(base_datum, Some(ix_datum)),
816 Some(SaveIn(scratch.val))).bcx;
818 let datum = scratch.to_expr_datum();
819 let lval = Lvalue::new("expr::trans_index overload");
820 if type_is_sized(bcx.tcx(), elt_ty) {
821 Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr(lval))
823 Datum::new(datum.val, elt_ty, LvalueExpr(lval))
827 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
831 // Translate index expression and cast to a suitable LLVM integer.
832 // Rust is less strict than LLVM in this regard.
833 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
834 let ix_val = ix_datum.to_llscalarish(bcx);
835 let ix_size = machine::llbitsize_of_real(bcx.ccx(),
837 let int_size = machine::llbitsize_of_real(bcx.ccx(),
840 if ix_size < int_size {
841 if expr_ty(bcx, idx).is_signed() {
842 SExt(bcx, ix_val, ccx.int_type())
843 } else { ZExt(bcx, ix_val, ccx.int_type()) }
844 } else if ix_size > int_size {
845 Trunc(bcx, ix_val, ccx.int_type())
851 let unit_ty = base_datum.ty.sequence_element_type(bcx.tcx());
853 let (base, len) = base_datum.get_vec_base_and_len(bcx);
855 debug!("trans_index: base {:?}", Value(base));
856 debug!("trans_index: len {:?}", Value(len));
858 let bounds_check = ICmp(bcx,
862 index_expr_debug_loc);
863 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
864 let expected = Call(bcx,
866 &[bounds_check, C_bool(ccx, false)],
867 index_expr_debug_loc);
868 bcx = with_cond(bcx, expected, |bcx| {
869 controlflow::trans_fail_bounds_check(bcx,
870 expr_info(index_expr),
874 let elt = InBoundsGEP(bcx, base, &[ix_val]);
875 let elt = PointerCast(bcx, elt, type_of::type_of(ccx, unit_ty).ptr_to());
876 let lval = Lvalue::new("expr::trans_index fallback");
877 Datum::new(elt, unit_ty, LvalueExpr(lval))
881 DatumBlock::new(bcx, elt_datum)
884 /// Translates a reference to a variable.
885 pub fn trans_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, def: Def)
886 -> Datum<'tcx, Lvalue> {
889 Def::Static(did, _) => consts::get_static(bcx.ccx(), did),
890 Def::Upvar(_, nid, _, _) => {
891 // Can't move upvars, so this is never a ZeroMemLastUse.
892 let local_ty = node_id_type(bcx, nid);
893 let lval = Lvalue::new_with_hint("expr::trans_var (upvar)",
894 bcx, nid, HintKind::ZeroAndMaintain);
895 match bcx.fcx.llupvars.borrow().get(&nid) {
896 Some(&val) => Datum::new(val, local_ty, lval),
898 bcx.sess().bug(&format!(
899 "trans_var: no llval for upvar {} found",
904 Def::Local(_, nid) => {
905 let datum = match bcx.fcx.lllocals.borrow().get(&nid) {
908 bcx.sess().bug(&format!(
909 "trans_var: no datum for local/arg {} found",
913 debug!("take_local(nid={}, v={:?}, ty={})",
914 nid, Value(datum.val), datum.ty);
917 _ => unreachable!("{:?} should not reach expr::trans_var", def)
921 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
923 -> Block<'blk, 'tcx> {
925 let _icx = push_ctxt("trans_rvalue_stmt");
927 if bcx.unreachable.get() {
931 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
934 hir::ExprBreak(label_opt) => {
935 controlflow::trans_break(bcx, expr, label_opt.map(|l| l.node.name))
937 hir::ExprType(ref e, _) => {
938 trans_into(bcx, &e, Ignore)
940 hir::ExprAgain(label_opt) => {
941 controlflow::trans_cont(bcx, expr, label_opt.map(|l| l.node.name))
943 hir::ExprRet(ref ex) => {
944 // Check to see if the return expression itself is reachable.
945 // This can occur when the inner expression contains a return
946 let reachable = if let Some(ref cfg) = bcx.fcx.cfg {
947 cfg.node_is_reachable(expr.id)
953 controlflow::trans_ret(bcx, expr, ex.as_ref().map(|e| &**e))
955 // If it's not reachable, just translate the inner expression
956 // directly. This avoids having to manage a return slot when
957 // it won't actually be used anyway.
958 if let &Some(ref x) = ex {
959 bcx = trans_into(bcx, &x, Ignore);
961 // Mark the end of the block as unreachable. Once we get to
962 // a return expression, there's no more we should be doing
968 hir::ExprWhile(ref cond, ref body, _) => {
969 controlflow::trans_while(bcx, expr, &cond, &body)
971 hir::ExprLoop(ref body, _) => {
972 controlflow::trans_loop(bcx, expr, &body)
974 hir::ExprAssign(ref dst, ref src) => {
975 let src_datum = unpack_datum!(bcx, trans(bcx, &src));
976 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &dst, "assign"));
978 if bcx.fcx.type_needs_drop(dst_datum.ty) {
979 // If there are destructors involved, make sure we
980 // are copying from an rvalue, since that cannot possible
981 // alias an lvalue. We are concerned about code like:
989 // where e.g. a : Option<Foo> and a.b :
990 // Option<Foo>. In that case, freeing `a` before the
991 // assignment may also free `a.b`!
993 // We could avoid this intermediary with some analysis
994 // to determine whether `dst` may possibly own `src`.
995 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
996 let src_datum = unpack_datum!(
997 bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
998 let opt_hint_datum = dst_datum.kind.drop_flag_info.hint_datum(bcx);
999 let opt_hint_val = opt_hint_datum.map(|d|d.to_value());
1001 // 1. Drop the data at the destination, passing the
1002 // drop-hint in case the lvalue has already been
1003 // dropped or moved.
1004 bcx = glue::drop_ty_core(bcx,
1011 // 2. We are overwriting the destination; ensure that
1012 // its drop-hint (if any) says "initialized."
1013 if let Some(hint_val) = opt_hint_val {
1014 let hint_llval = hint_val.value();
1015 let drop_needed = C_u8(bcx.fcx.ccx, adt::DTOR_NEEDED_HINT);
1016 Store(bcx, drop_needed, hint_llval);
1018 src_datum.store_to(bcx, dst_datum.val)
1020 src_datum.store_to(bcx, dst_datum.val)
1023 hir::ExprAssignOp(op, ref dst, ref src) => {
1024 let method = bcx.tcx().tables
1027 .get(&MethodCall::expr(expr.id)).cloned();
1029 if let Some(method) = method {
1030 let dst = unpack_datum!(bcx, trans(bcx, &dst));
1031 let src_datum = unpack_datum!(bcx, trans(bcx, &src));
1033 Callee::method(bcx, method)
1034 .call(bcx, expr.debug_loc(),
1035 ArgOverloadedOp(dst, Some(src_datum)), None).bcx
1037 trans_assign_op(bcx, expr, op, &dst, &src)
1040 hir::ExprInlineAsm(ref a) => {
1041 asm::trans_inline_asm(bcx, a)
1044 bcx.tcx().sess.span_bug(
1046 &format!("trans_rvalue_stmt_unadjusted reached \
1047 fall-through case: {:?}",
1053 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1056 -> Block<'blk, 'tcx> {
1057 let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
1060 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
1062 // Entry into the method table if this is an overloaded call/op.
1063 let method_call = MethodCall::expr(expr.id);
1066 hir::ExprType(ref e, _) => {
1067 trans_into(bcx, &e, dest)
1069 hir::ExprPath(..) => {
1070 trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
1072 hir::ExprIf(ref cond, ref thn, ref els) => {
1073 controlflow::trans_if(bcx, expr.id, &cond, &thn, els.as_ref().map(|e| &**e), dest)
1075 hir::ExprMatch(ref discr, ref arms, _) => {
1076 _match::trans_match(bcx, expr, &discr, &arms[..], dest)
1078 hir::ExprBlock(ref blk) => {
1079 controlflow::trans_block(bcx, &blk, dest)
1081 hir::ExprStruct(_, ref fields, ref base) => {
1084 base.as_ref().map(|e| &**e),
1087 node_id_type(bcx, expr.id),
1090 hir::ExprTup(ref args) => {
1091 let numbered_fields: Vec<(usize, &hir::Expr)> =
1092 args.iter().enumerate().map(|(i, arg)| (i, &**arg)).collect();
1096 &numbered_fields[..],
1101 hir::ExprLit(ref lit) => {
1103 ast::LitKind::Str(ref s, _) => {
1104 tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1109 .span_bug(expr.span,
1110 "trans_rvalue_dps_unadjusted shouldn't be \
1111 translating this type of literal")
1115 hir::ExprVec(..) | hir::ExprRepeat(..) => {
1116 tvec::trans_fixed_vstore(bcx, expr, dest)
1118 hir::ExprClosure(_, ref decl, ref body) => {
1119 let dest = match dest {
1120 SaveIn(lldest) => closure::Dest::SaveIn(bcx, lldest),
1121 Ignore => closure::Dest::Ignore(bcx.ccx())
1124 // NB. To get the id of the closure, we don't use
1125 // `local_def_id(id)`, but rather we extract the closure
1126 // def-id from the expr's type. This is because this may
1127 // be an inlined expression from another crate, and we
1128 // want to get the ORIGINAL closure def-id, since that is
1129 // the key we need to find the closure-kind and
1130 // closure-type etc.
1131 let (def_id, substs) = match expr_ty(bcx, expr).sty {
1132 ty::TyClosure(def_id, ref substs) => (def_id, substs),
1134 bcx.tcx().sess.span_bug(
1136 &format!("closure expr without closure type: {:?}", t)),
1139 closure::trans_closure_expr(dest,
1145 &expr.attrs).unwrap_or(bcx)
1147 hir::ExprCall(ref f, ref args) => {
1148 let method = bcx.tcx().tables.borrow().method_map.get(&method_call).cloned();
1149 let (callee, args) = if let Some(method) = method {
1150 let mut all_args = vec![&**f];
1151 all_args.extend(args.iter().map(|e| &**e));
1153 (Callee::method(bcx, method), ArgOverloadedCall(all_args))
1155 let f = unpack_datum!(bcx, trans(bcx, f));
1157 ty::TyFnDef(def_id, substs, _) => {
1158 Callee::def(bcx.ccx(), def_id, substs)
1161 let f = unpack_datum!(bcx,
1162 f.to_rvalue_datum(bcx, "callee"));
1166 bcx.tcx().sess.span_bug(expr.span,
1167 &format!("type of callee is not a fn: {}", f.ty));
1171 callee.call(bcx, expr.debug_loc(), args, Some(dest)).bcx
1173 hir::ExprMethodCall(_, _, ref args) => {
1174 Callee::method_call(bcx, method_call)
1175 .call(bcx, expr.debug_loc(), ArgExprs(&args), Some(dest)).bcx
1177 hir::ExprBinary(op, ref lhs, ref rhs_expr) => {
1178 // if not overloaded, would be RvalueDatumExpr
1179 let lhs = unpack_datum!(bcx, trans(bcx, &lhs));
1180 let mut rhs = unpack_datum!(bcx, trans(bcx, &rhs_expr));
1181 if !rustc_front::util::is_by_value_binop(op.node) {
1182 rhs = unpack_datum!(bcx, auto_ref(bcx, rhs, rhs_expr));
1185 Callee::method_call(bcx, method_call)
1186 .call(bcx, expr.debug_loc(),
1187 ArgOverloadedOp(lhs, Some(rhs)), Some(dest)).bcx
1189 hir::ExprUnary(_, ref subexpr) => {
1190 // if not overloaded, would be RvalueDatumExpr
1191 let arg = unpack_datum!(bcx, trans(bcx, &subexpr));
1193 Callee::method_call(bcx, method_call)
1194 .call(bcx, expr.debug_loc(),
1195 ArgOverloadedOp(arg, None), Some(dest)).bcx
1197 hir::ExprCast(..) => {
1198 // Trait casts used to come this way, now they should be coercions.
1199 bcx.tcx().sess.span_bug(expr.span, "DPS expr_cast (residual trait cast?)")
1201 hir::ExprAssignOp(op, _, _) => {
1202 bcx.tcx().sess.span_bug(
1204 &format!("augmented assignment `{}=` should always be a rvalue_stmt",
1205 rustc_front::util::binop_to_string(op.node)))
1208 bcx.tcx().sess.span_bug(
1210 &format!("trans_rvalue_dps_unadjusted reached fall-through \
1217 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1218 ref_expr: &hir::Expr,
1221 -> Block<'blk, 'tcx> {
1222 let _icx = push_ctxt("trans_def_dps_unadjusted");
1224 let lldest = match dest {
1225 SaveIn(lldest) => lldest,
1226 Ignore => { return bcx; }
1229 let ty = expr_ty(bcx, ref_expr);
1230 if let ty::TyFnDef(..) = ty.sty {
1231 // Zero-sized function or ctor.
1236 Def::Variant(tid, vid) => {
1237 let variant = bcx.tcx().lookup_adt_def(tid).variant_with_id(vid);
1239 let ty = expr_ty(bcx, ref_expr);
1240 let repr = adt::represent_type(bcx.ccx(), ty);
1241 adt::trans_set_discr(bcx, &repr, lldest, Disr::from(variant.disr_val));
1244 Def::Struct(..) => {
1246 ty::TyStruct(def, _) if def.has_dtor() => {
1247 let repr = adt::represent_type(bcx.ccx(), ty);
1248 adt::trans_set_discr(bcx, &repr, lldest, Disr(0));
1255 bcx.tcx().sess.span_bug(ref_expr.span, &format!(
1256 "Non-DPS def {:?} referened by {}",
1257 def, bcx.node_id_to_string(ref_expr.id)));
1262 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1263 fields: &[hir::Field],
1264 base: Option<&hir::Expr>,
1265 expr_span: codemap::Span,
1266 expr_id: ast::NodeId,
1268 dest: Dest) -> Block<'blk, 'tcx> {
1269 let _icx = push_ctxt("trans_rec");
1271 let tcx = bcx.tcx();
1272 let vinfo = VariantInfo::of_node(tcx, ty, expr_id);
1274 let mut need_base = vec![true; vinfo.fields.len()];
1276 let numbered_fields = fields.iter().map(|field| {
1277 let pos = vinfo.field_index(field.name.node);
1278 need_base[pos] = false;
1280 }).collect::<Vec<_>>();
1282 let optbase = match base {
1283 Some(base_expr) => {
1284 let mut leftovers = Vec::new();
1285 for (i, b) in need_base.iter().enumerate() {
1287 leftovers.push((i, vinfo.fields[i].1));
1290 Some(StructBaseInfo {expr: base_expr,
1291 fields: leftovers })
1294 if need_base.iter().any(|b| *b) {
1295 tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1307 DebugLoc::At(expr_id, expr_span))
1310 /// Information that `trans_adt` needs in order to fill in the fields
1311 /// of a struct copied from a base struct (e.g., from an expression
1312 /// like `Foo { a: b, ..base }`.
1314 /// Note that `fields` may be empty; the base expression must always be
1315 /// evaluated for side-effects.
1316 pub struct StructBaseInfo<'a, 'tcx> {
1317 /// The base expression; will be evaluated after all explicit fields.
1318 expr: &'a hir::Expr,
1319 /// The indices of fields to copy paired with their types.
1320 fields: Vec<(usize, Ty<'tcx>)>
1323 /// Constructs an ADT instance:
1325 /// - `fields` should be a list of field indices paired with the
1326 /// expression to store into that field. The initializers will be
1327 /// evaluated in the order specified by `fields`.
1329 /// - `optbase` contains information on the base struct (if any) from
1330 /// which remaining fields are copied; see comments on `StructBaseInfo`.
1331 pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1334 fields: &[(usize, &hir::Expr)],
1335 optbase: Option<StructBaseInfo<'a, 'tcx>>,
1337 debug_location: DebugLoc)
1338 -> Block<'blk, 'tcx> {
1339 let _icx = push_ctxt("trans_adt");
1341 let repr = adt::represent_type(bcx.ccx(), ty);
1343 debug_location.apply(bcx.fcx);
1345 // If we don't care about the result, just make a
1346 // temporary stack slot
1347 let addr = match dest {
1350 let llresult = alloc_ty(bcx, ty, "temp");
1351 call_lifetime_start(bcx, llresult);
1356 debug!("trans_adt");
1358 // This scope holds intermediates that must be cleaned should
1359 // panic occur before the ADT as a whole is ready.
1360 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1363 // Issue 23112: The original logic appeared vulnerable to same
1364 // order-of-eval bug. But, SIMD values are tuple-structs;
1365 // i.e. functional record update (FRU) syntax is unavailable.
1367 // To be safe, double-check that we did not get here via FRU.
1368 assert!(optbase.is_none());
1370 // This is the constructor of a SIMD type, such types are
1371 // always primitive machine types and so do not have a
1372 // destructor or require any clean-up.
1373 let llty = type_of::type_of(bcx.ccx(), ty);
1375 // keep a vector as a register, and running through the field
1376 // `insertelement`ing them directly into that register
1377 // (i.e. avoid GEPi and `store`s to an alloca) .
1378 let mut vec_val = C_undef(llty);
1380 for &(i, ref e) in fields {
1381 let block_datum = trans(bcx, &e);
1382 bcx = block_datum.bcx;
1383 let position = C_uint(bcx.ccx(), i);
1384 let value = block_datum.datum.to_llscalarish(bcx);
1385 vec_val = InsertElement(bcx, vec_val, value, position);
1387 Store(bcx, vec_val, addr);
1388 } else if let Some(base) = optbase {
1389 // Issue 23112: If there is a base, then order-of-eval
1390 // requires field expressions eval'ed before base expression.
1392 // First, trans field expressions to temporary scratch values.
1393 let scratch_vals: Vec<_> = fields.iter().map(|&(i, ref e)| {
1394 let datum = unpack_datum!(bcx, trans(bcx, &e));
1398 debug_location.apply(bcx.fcx);
1400 // Second, trans the base to the dest.
1401 assert_eq!(discr, Disr(0));
1403 let addr = adt::MaybeSizedValue::sized(addr);
1404 match expr_kind(bcx.tcx(), &base.expr) {
1405 ExprKind::RvalueDps | ExprKind::RvalueDatum if !bcx.fcx.type_needs_drop(ty) => {
1406 bcx = trans_into(bcx, &base.expr, SaveIn(addr.value));
1408 ExprKind::RvalueStmt => {
1409 bcx.tcx().sess.bug("unexpected expr kind for struct base expr")
1412 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &base.expr, "base"));
1413 for &(i, t) in &base.fields {
1414 let datum = base_datum.get_element(
1415 bcx, t, |srcval| adt::trans_field_ptr(bcx, &repr, srcval, discr, i));
1416 assert!(type_is_sized(bcx.tcx(), datum.ty));
1417 let dest = adt::trans_field_ptr(bcx, &repr, addr, discr, i);
1418 bcx = datum.store_to(bcx, dest);
1423 // Finally, move scratch field values into actual field locations
1424 for (i, datum) in scratch_vals {
1425 let dest = adt::trans_field_ptr(bcx, &repr, addr, discr, i);
1426 bcx = datum.store_to(bcx, dest);
1429 // No base means we can write all fields directly in place.
1430 let addr = adt::MaybeSizedValue::sized(addr);
1431 for &(i, ref e) in fields {
1432 let dest = adt::trans_field_ptr(bcx, &repr, addr, discr, i);
1433 let e_ty = expr_ty_adjusted(bcx, &e);
1434 bcx = trans_into(bcx, &e, SaveIn(dest));
1435 let scope = cleanup::CustomScope(custom_cleanup_scope);
1436 fcx.schedule_lifetime_end(scope, dest);
1437 // FIXME: nonzeroing move should generalize to fields
1438 fcx.schedule_drop_mem(scope, dest, e_ty, None);
1442 adt::trans_set_discr(bcx, &repr, addr, discr);
1444 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1446 // If we don't care about the result drop the temporary we made
1450 bcx = glue::drop_ty(bcx, addr, ty, debug_location);
1451 base::call_lifetime_end(bcx, addr);
1458 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1461 -> DatumBlock<'blk, 'tcx, Expr> {
1462 // must not be a string constant, that is a RvalueDpsExpr
1463 let _icx = push_ctxt("trans_immediate_lit");
1464 let ty = expr_ty(bcx, expr);
1465 let v = consts::const_lit(bcx.ccx(), expr, lit);
1466 immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1469 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1472 sub_expr: &hir::Expr)
1473 -> DatumBlock<'blk, 'tcx, Expr> {
1474 let ccx = bcx.ccx();
1476 let _icx = push_ctxt("trans_unary_datum");
1478 let method_call = MethodCall::expr(expr.id);
1480 // The only overloaded operator that is translated to a datum
1481 // is an overloaded deref, since it is always yields a `&T`.
1482 // Otherwise, we should be in the RvalueDpsExpr path.
1483 assert!(op == hir::UnDeref || !ccx.tcx().is_method_call(expr.id));
1485 let un_ty = expr_ty(bcx, expr);
1487 let debug_loc = expr.debug_loc();
1491 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1492 let llresult = Not(bcx, datum.to_llscalarish(bcx), debug_loc);
1493 immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1496 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1497 let val = datum.to_llscalarish(bcx);
1498 let (bcx, llneg) = {
1500 let result = FNeg(bcx, val, debug_loc);
1503 let is_signed = un_ty.is_signed();
1504 let result = Neg(bcx, val, debug_loc);
1505 let bcx = if bcx.ccx().check_overflow() && is_signed {
1506 let (llty, min) = base::llty_and_min_for_signed_ty(bcx, un_ty);
1507 let is_min = ICmp(bcx, llvm::IntEQ, val,
1508 C_integral(llty, min, true), debug_loc);
1509 with_cond(bcx, is_min, |bcx| {
1510 let msg = InternedString::new(
1511 "attempted to negate with overflow");
1512 controlflow::trans_fail(bcx, expr_info(expr), msg)
1520 immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1523 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1524 deref_once(bcx, expr, datum, method_call)
1529 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1530 box_expr: &hir::Expr,
1532 contents: &hir::Expr,
1533 contents_ty: Ty<'tcx>)
1534 -> DatumBlock<'blk, 'tcx, Expr> {
1535 let _icx = push_ctxt("trans_uniq_expr");
1537 assert!(type_is_sized(bcx.tcx(), contents_ty));
1538 let llty = type_of::type_of(bcx.ccx(), contents_ty);
1539 let size = llsize_of(bcx.ccx(), llty);
1540 let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty));
1541 let llty_ptr = llty.ptr_to();
1542 let Result { bcx, val } = malloc_raw_dyn(bcx,
1547 box_expr.debug_loc());
1548 // Unique boxes do not allocate for zero-size types. The standard library
1549 // may assume that `free` is never called on the pointer returned for
1550 // `Box<ZeroSizeType>`.
1551 let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1552 trans_into(bcx, contents, SaveIn(val))
1554 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1555 fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1556 val, cleanup::HeapExchange, contents_ty);
1557 let bcx = trans_into(bcx, contents, SaveIn(val));
1558 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1561 immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1564 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1566 subexpr: &hir::Expr)
1567 -> DatumBlock<'blk, 'tcx, Expr> {
1568 let _icx = push_ctxt("trans_addr_of");
1570 let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1571 let ty = expr_ty(bcx, expr);
1572 if !type_is_sized(bcx.tcx(), sub_datum.ty) {
1573 // Always generate an lvalue datum, because this pointer doesn't own
1574 // the data and cleanup is scheduled elsewhere.
1575 DatumBlock::new(bcx, Datum::new(sub_datum.val, ty, LvalueExpr(sub_datum.kind)))
1577 // Sized value, ref to a thin pointer
1578 immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1582 fn trans_scalar_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1583 binop_expr: &hir::Expr,
1586 lhs: Datum<'tcx, Rvalue>,
1587 rhs: Datum<'tcx, Rvalue>)
1588 -> DatumBlock<'blk, 'tcx, Expr>
1590 let _icx = push_ctxt("trans_scalar_binop");
1592 let tcx = bcx.tcx();
1594 assert!(!lhs_t.is_simd());
1595 let is_float = lhs_t.is_fp();
1596 let is_signed = lhs_t.is_signed();
1597 let info = expr_info(binop_expr);
1599 let binop_debug_loc = binop_expr.debug_loc();
1602 let lhs = lhs.to_llscalarish(bcx);
1603 let rhs = rhs.to_llscalarish(bcx);
1604 let val = match op.node {
1607 FAdd(bcx, lhs, rhs, binop_debug_loc)
1609 let (newbcx, res) = with_overflow_check(
1610 bcx, OverflowOp::Add, info, lhs_t, lhs, rhs, binop_debug_loc);
1617 FSub(bcx, lhs, rhs, binop_debug_loc)
1619 let (newbcx, res) = with_overflow_check(
1620 bcx, OverflowOp::Sub, info, lhs_t, lhs, rhs, binop_debug_loc);
1627 FMul(bcx, lhs, rhs, binop_debug_loc)
1629 let (newbcx, res) = with_overflow_check(
1630 bcx, OverflowOp::Mul, info, lhs_t, lhs, rhs, binop_debug_loc);
1637 FDiv(bcx, lhs, rhs, binop_debug_loc)
1639 // Only zero-check integers; fp /0 is NaN
1640 bcx = base::fail_if_zero_or_overflows(bcx,
1641 expr_info(binop_expr),
1647 SDiv(bcx, lhs, rhs, binop_debug_loc)
1649 UDiv(bcx, lhs, rhs, binop_debug_loc)
1655 // LLVM currently always lowers the `frem` instructions appropriate
1656 // library calls typically found in libm. Notably f64 gets wired up
1657 // to `fmod` and f32 gets wired up to `fmodf`. Inconveniently for
1658 // us, 32-bit MSVC does not actually have a `fmodf` symbol, it's
1659 // instead just an inline function in a header that goes up to a
1660 // f64, uses `fmod`, and then comes back down to a f32.
1662 // Although LLVM knows that `fmodf` doesn't exist on MSVC, it will
1663 // still unconditionally lower frem instructions over 32-bit floats
1664 // to a call to `fmodf`. To work around this we special case MSVC
1665 // 32-bit float rem instructions and instead do the call out to
1666 // `fmod` ourselves.
1668 // Note that this is currently duplicated with src/libcore/ops.rs
1669 // which does the same thing, and it would be nice to perhaps unify
1670 // these two implementations on day! Also note that we call `fmod`
1671 // for both 32 and 64-bit floats because if we emit any FRem
1672 // instruction at all then LLVM is capable of optimizing it into a
1673 // 32-bit FRem (which we're trying to avoid).
1674 let use_fmod = tcx.sess.target.target.options.is_like_msvc &&
1675 tcx.sess.target.target.arch == "x86";
1677 let f64t = Type::f64(bcx.ccx());
1678 let fty = Type::func(&[f64t, f64t], &f64t);
1679 let llfn = declare::declare_cfn(bcx.ccx(), "fmod", fty);
1680 if lhs_t == tcx.types.f32 {
1681 let lhs = FPExt(bcx, lhs, f64t);
1682 let rhs = FPExt(bcx, rhs, f64t);
1683 let res = Call(bcx, llfn, &[lhs, rhs], binop_debug_loc);
1684 FPTrunc(bcx, res, Type::f32(bcx.ccx()))
1686 Call(bcx, llfn, &[lhs, rhs], binop_debug_loc)
1689 FRem(bcx, lhs, rhs, binop_debug_loc)
1692 // Only zero-check integers; fp %0 is NaN
1693 bcx = base::fail_if_zero_or_overflows(bcx,
1694 expr_info(binop_expr),
1695 op, lhs, rhs, lhs_t);
1697 SRem(bcx, lhs, rhs, binop_debug_loc)
1699 URem(bcx, lhs, rhs, binop_debug_loc)
1703 hir::BiBitOr => Or(bcx, lhs, rhs, binop_debug_loc),
1704 hir::BiBitAnd => And(bcx, lhs, rhs, binop_debug_loc),
1705 hir::BiBitXor => Xor(bcx, lhs, rhs, binop_debug_loc),
1707 let (newbcx, res) = with_overflow_check(
1708 bcx, OverflowOp::Shl, info, lhs_t, lhs, rhs, binop_debug_loc);
1713 let (newbcx, res) = with_overflow_check(
1714 bcx, OverflowOp::Shr, info, lhs_t, lhs, rhs, binop_debug_loc);
1718 hir::BiEq | hir::BiNe | hir::BiLt | hir::BiGe | hir::BiLe | hir::BiGt => {
1719 base::compare_scalar_types(bcx, lhs, rhs, lhs_t, op.node, binop_debug_loc)
1722 bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1726 immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1729 // refinement types would obviate the need for this
1730 enum lazy_binop_ty {
1735 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1736 binop_expr: &hir::Expr,
1740 -> DatumBlock<'blk, 'tcx, Expr> {
1741 let _icx = push_ctxt("trans_lazy_binop");
1742 let binop_ty = expr_ty(bcx, binop_expr);
1745 let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1746 let lhs = lhs.to_llscalarish(past_lhs);
1748 if past_lhs.unreachable.get() {
1749 return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1752 let join = fcx.new_id_block("join", binop_expr.id);
1753 let before_rhs = fcx.new_id_block("before_rhs", b.id);
1756 lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb, DebugLoc::None),
1757 lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb, DebugLoc::None)
1760 let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1761 let rhs = rhs.to_llscalarish(past_rhs);
1763 if past_rhs.unreachable.get() {
1764 return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1767 Br(past_rhs, join.llbb, DebugLoc::None);
1768 let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1769 &[past_lhs.llbb, past_rhs.llbb]);
1771 return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1774 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1779 -> DatumBlock<'blk, 'tcx, Expr> {
1780 let _icx = push_ctxt("trans_binary");
1781 let ccx = bcx.ccx();
1783 // if overloaded, would be RvalueDpsExpr
1784 assert!(!ccx.tcx().is_method_call(expr.id));
1788 trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1791 trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1795 let binop_ty = expr_ty(bcx, expr);
1797 let lhs = unpack_datum!(bcx, trans(bcx, lhs));
1798 let lhs = unpack_datum!(bcx, lhs.to_rvalue_datum(bcx, "binop_lhs"));
1799 debug!("trans_binary (expr {}): lhs={:?}", expr.id, lhs);
1800 let rhs = unpack_datum!(bcx, trans(bcx, rhs));
1801 let rhs = unpack_datum!(bcx, rhs.to_rvalue_datum(bcx, "binop_rhs"));
1802 debug!("trans_binary (expr {}): rhs={:?}", expr.id, rhs);
1804 if type_is_fat_ptr(ccx.tcx(), lhs.ty) {
1805 assert!(type_is_fat_ptr(ccx.tcx(), rhs.ty),
1806 "built-in binary operators on fat pointers are homogeneous");
1807 assert_eq!(binop_ty, bcx.tcx().types.bool);
1808 let val = base::compare_scalar_types(
1815 immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1817 assert!(!type_is_fat_ptr(ccx.tcx(), rhs.ty),
1818 "built-in binary operators on fat pointers are homogeneous");
1819 trans_scalar_binop(bcx, expr, binop_ty, op, lhs, rhs)
1825 pub fn cast_is_noop<'tcx>(tcx: &TyCtxt<'tcx>,
1830 if let Some(&CastKind::CoercionCast) = tcx.cast_kinds.borrow().get(&expr.id) {
1834 match (t_in.builtin_deref(true, ty::NoPreference),
1835 t_out.builtin_deref(true, ty::NoPreference)) {
1836 (Some(ty::TypeAndMut{ ty: t_in, .. }), Some(ty::TypeAndMut{ ty: t_out, .. })) => {
1840 // This condition isn't redundant with the check for CoercionCast:
1841 // different types can be substituted into the same type, and
1842 // == equality can be overconservative if there are regions.
1848 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1851 -> DatumBlock<'blk, 'tcx, Expr>
1853 use middle::ty::cast::CastTy::*;
1854 use middle::ty::cast::IntTy::*;
1856 fn int_cast(bcx: Block,
1863 let _icx = push_ctxt("int_cast");
1864 let srcsz = llsrctype.int_width();
1865 let dstsz = lldsttype.int_width();
1866 return if dstsz == srcsz {
1867 BitCast(bcx, llsrc, lldsttype)
1868 } else if srcsz > dstsz {
1869 TruncOrBitCast(bcx, llsrc, lldsttype)
1871 SExtOrBitCast(bcx, llsrc, lldsttype)
1873 ZExtOrBitCast(bcx, llsrc, lldsttype)
1877 fn float_cast(bcx: Block,
1883 let _icx = push_ctxt("float_cast");
1884 let srcsz = llsrctype.float_width();
1885 let dstsz = lldsttype.float_width();
1886 return if dstsz > srcsz {
1887 FPExt(bcx, llsrc, lldsttype)
1888 } else if srcsz > dstsz {
1889 FPTrunc(bcx, llsrc, lldsttype)
1893 let _icx = push_ctxt("trans_cast");
1895 let ccx = bcx.ccx();
1897 let t_in = expr_ty_adjusted(bcx, expr);
1898 let t_out = node_id_type(bcx, id);
1900 debug!("trans_cast({:?} as {:?})", t_in, t_out);
1901 let mut ll_t_in = type_of::immediate_type_of(ccx, t_in);
1902 let ll_t_out = type_of::immediate_type_of(ccx, t_out);
1903 // Convert the value to be cast into a ValueRef, either by-ref or
1904 // by-value as appropriate given its type:
1905 let mut datum = unpack_datum!(bcx, trans(bcx, expr));
1907 let datum_ty = monomorphize_type(bcx, datum.ty);
1909 if cast_is_noop(bcx.tcx(), expr, datum_ty, t_out) {
1911 return DatumBlock::new(bcx, datum);
1914 if type_is_fat_ptr(bcx.tcx(), t_in) {
1915 assert!(datum.kind.is_by_ref());
1916 if type_is_fat_ptr(bcx.tcx(), t_out) {
1917 return DatumBlock::new(bcx, Datum::new(
1918 PointerCast(bcx, datum.val, ll_t_out.ptr_to()),
1921 )).to_expr_datumblock();
1923 // Return the address
1924 return immediate_rvalue_bcx(bcx,
1926 Load(bcx, get_dataptr(bcx, datum.val)),
1928 t_out).to_expr_datumblock();
1932 let r_t_in = CastTy::from_ty(t_in).expect("bad input type for cast");
1933 let r_t_out = CastTy::from_ty(t_out).expect("bad output type for cast");
1935 let (llexpr, signed) = if let Int(CEnum) = r_t_in {
1936 let repr = adt::represent_type(ccx, t_in);
1937 let datum = unpack_datum!(
1938 bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
1939 let llexpr_ptr = datum.to_llref();
1940 let discr = adt::trans_get_discr(bcx, &repr, llexpr_ptr,
1941 Some(Type::i64(ccx)), true);
1942 ll_t_in = val_ty(discr);
1943 (discr, adt::is_discr_signed(&repr))
1945 (datum.to_llscalarish(bcx), t_in.is_signed())
1948 let newval = match (r_t_in, r_t_out) {
1949 (Ptr(_), Ptr(_)) | (FnPtr, Ptr(_)) | (RPtr(_), Ptr(_)) => {
1950 PointerCast(bcx, llexpr, ll_t_out)
1952 (Ptr(_), Int(_)) | (FnPtr, Int(_)) => PtrToInt(bcx, llexpr, ll_t_out),
1953 (Int(_), Ptr(_)) => IntToPtr(bcx, llexpr, ll_t_out),
1955 (Int(_), Int(_)) => int_cast(bcx, ll_t_out, ll_t_in, llexpr, signed),
1956 (Float, Float) => float_cast(bcx, ll_t_out, ll_t_in, llexpr),
1957 (Int(_), Float) if signed => SIToFP(bcx, llexpr, ll_t_out),
1958 (Int(_), Float) => UIToFP(bcx, llexpr, ll_t_out),
1959 (Float, Int(I)) => FPToSI(bcx, llexpr, ll_t_out),
1960 (Float, Int(_)) => FPToUI(bcx, llexpr, ll_t_out),
1962 _ => ccx.sess().span_bug(expr.span,
1963 &format!("translating unsupported cast: \
1969 return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
1972 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1977 -> Block<'blk, 'tcx> {
1978 let _icx = push_ctxt("trans_assign_op");
1981 debug!("trans_assign_op(expr={:?})", expr);
1983 // User-defined operator methods cannot be used with `+=` etc right now
1984 assert!(!bcx.tcx().is_method_call(expr.id));
1986 // Evaluate LHS (destination), which should be an lvalue
1987 let dst = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
1988 assert!(!bcx.fcx.type_needs_drop(dst.ty));
1989 let lhs = load_ty(bcx, dst.val, dst.ty);
1990 let lhs = immediate_rvalue(lhs, dst.ty);
1992 // Evaluate RHS - FIXME(#28160) this sucks
1993 let rhs = unpack_datum!(bcx, trans(bcx, &src));
1994 let rhs = unpack_datum!(bcx, rhs.to_rvalue_datum(bcx, "assign_op_rhs"));
1996 // Perform computation and store the result
1997 let result_datum = unpack_datum!(
1998 bcx, trans_scalar_binop(bcx, expr, dst.ty, op, lhs, rhs));
1999 return result_datum.store_to(bcx, dst.val);
2002 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2003 datum: Datum<'tcx, Expr>,
2005 -> DatumBlock<'blk, 'tcx, Expr> {
2008 // Ensure cleanup of `datum` if not already scheduled and obtain
2009 // a "by ref" pointer.
2010 let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2012 // Compute final type. Note that we are loose with the region and
2013 // mutability, since those things don't matter in trans.
2014 let referent_ty = lv_datum.ty;
2015 let ptr_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), referent_ty);
2017 // Construct the resulting datum. The right datum to return here would be an Lvalue datum,
2018 // because there is cleanup scheduled and the datum doesn't own the data, but for thin pointers
2019 // we microoptimize it to be an Rvalue datum to avoid the extra alloca and level of
2020 // indirection and for thin pointers, this has no ill effects.
2021 let kind = if type_is_sized(bcx.tcx(), referent_ty) {
2022 RvalueExpr(Rvalue::new(ByValue))
2024 LvalueExpr(lv_datum.kind)
2028 let llref = lv_datum.to_llref();
2029 DatumBlock::new(bcx, Datum::new(llref, ptr_ty, kind))
2032 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2034 datum: Datum<'tcx, Expr>,
2036 -> DatumBlock<'blk, 'tcx, Expr> {
2038 let mut datum = datum;
2040 let method_call = MethodCall::autoderef(expr.id, i as u32);
2041 datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2043 DatumBlock { bcx: bcx, datum: datum }
2046 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2048 datum: Datum<'tcx, Expr>,
2049 method_call: MethodCall)
2050 -> DatumBlock<'blk, 'tcx, Expr> {
2051 let ccx = bcx.ccx();
2053 debug!("deref_once(expr={:?}, datum={:?}, method_call={:?})",
2054 expr, datum, method_call);
2058 // Check for overloaded deref.
2059 let method = ccx.tcx().tables.borrow().method_map.get(&method_call).cloned();
2060 let datum = match method {
2062 let method_ty = monomorphize_type(bcx, method.ty);
2064 // Overloaded. Invoke the deref() method, which basically
2065 // converts from the `Smaht<T>` pointer that we have into
2066 // a `&T` pointer. We can then proceed down the normal
2067 // path (below) to dereference that `&T`.
2068 let datum = if method_call.autoderef == 0 {
2071 // Always perform an AutoPtr when applying an overloaded auto-deref
2072 unpack_datum!(bcx, auto_ref(bcx, datum, expr))
2075 let ref_ty = // invoked methods have their LB regions instantiated
2076 ccx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
2077 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2079 bcx = Callee::method(bcx, method)
2080 .call(bcx, expr.debug_loc(),
2081 ArgOverloadedOp(datum, None),
2082 Some(SaveIn(scratch.val))).bcx;
2083 scratch.to_expr_datum()
2086 // Not overloaded. We already have a pointer we know how to deref.
2091 let r = match datum.ty.sty {
2092 ty::TyBox(content_ty) => {
2093 // Make sure we have an lvalue datum here to get the
2094 // proper cleanups scheduled
2095 let datum = unpack_datum!(
2096 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2098 if type_is_sized(bcx.tcx(), content_ty) {
2099 let ptr = load_ty(bcx, datum.val, datum.ty);
2100 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(datum.kind)))
2102 // A fat pointer and a DST lvalue have the same representation
2103 // just different types. Since there is no temporary for `*e`
2104 // here (because it is unsized), we cannot emulate the sized
2105 // object code path for running drop glue and free. Instead,
2106 // we schedule cleanup for `e`, turning it into an lvalue.
2108 let lval = Lvalue::new("expr::deref_once ty_uniq");
2109 let datum = Datum::new(datum.val, content_ty, LvalueExpr(lval));
2110 DatumBlock::new(bcx, datum)
2114 ty::TyRawPtr(ty::TypeAndMut { ty: content_ty, .. }) |
2115 ty::TyRef(_, ty::TypeAndMut { ty: content_ty, .. }) => {
2116 let lval = Lvalue::new("expr::deref_once ptr");
2117 if type_is_sized(bcx.tcx(), content_ty) {
2118 let ptr = datum.to_llscalarish(bcx);
2120 // Always generate an lvalue datum, even if datum.mode is
2121 // an rvalue. This is because datum.mode is only an
2122 // rvalue for non-owning pointers like &T or *T, in which
2123 // case cleanup *is* scheduled elsewhere, by the true
2124 // owner (or, in the case of *T, by the user).
2125 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(lval)))
2127 // A fat pointer and a DST lvalue have the same representation
2128 // just different types.
2129 DatumBlock::new(bcx, Datum::new(datum.val, content_ty, LvalueExpr(lval)))
2134 bcx.tcx().sess.span_bug(
2136 &format!("deref invoked on expr of invalid type {:?}",
2141 debug!("deref_once(expr={}, method_call={:?}, result={:?})",
2142 expr.id, method_call, r.datum);
2157 fn codegen_strategy(&self) -> OverflowCodegen {
2158 use self::OverflowCodegen::{ViaIntrinsic, ViaInputCheck};
2160 OverflowOp::Add => ViaIntrinsic(OverflowOpViaIntrinsic::Add),
2161 OverflowOp::Sub => ViaIntrinsic(OverflowOpViaIntrinsic::Sub),
2162 OverflowOp::Mul => ViaIntrinsic(OverflowOpViaIntrinsic::Mul),
2164 OverflowOp::Shl => ViaInputCheck(OverflowOpViaInputCheck::Shl),
2165 OverflowOp::Shr => ViaInputCheck(OverflowOpViaInputCheck::Shr),
2170 enum OverflowCodegen {
2171 ViaIntrinsic(OverflowOpViaIntrinsic),
2172 ViaInputCheck(OverflowOpViaInputCheck),
2175 enum OverflowOpViaInputCheck { Shl, Shr, }
2178 enum OverflowOpViaIntrinsic { Add, Sub, Mul, }
2180 impl OverflowOpViaIntrinsic {
2181 fn to_intrinsic<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>, lhs_ty: Ty) -> ValueRef {
2182 let name = self.to_intrinsic_name(bcx.tcx(), lhs_ty);
2183 bcx.ccx().get_intrinsic(&name)
2185 fn to_intrinsic_name(&self, tcx: &TyCtxt, ty: Ty) -> &'static str {
2186 use syntax::ast::IntTy::*;
2187 use syntax::ast::UintTy::*;
2188 use middle::ty::{TyInt, TyUint};
2190 let new_sty = match ty.sty {
2191 TyInt(Is) => match &tcx.sess.target.target.target_pointer_width[..] {
2194 _ => panic!("unsupported target word size")
2196 TyUint(Us) => match &tcx.sess.target.target.target_pointer_width[..] {
2197 "32" => TyUint(U32),
2198 "64" => TyUint(U64),
2199 _ => panic!("unsupported target word size")
2201 ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
2202 _ => panic!("tried to get overflow intrinsic for {:?} applied to non-int type",
2207 OverflowOpViaIntrinsic::Add => match new_sty {
2208 TyInt(I8) => "llvm.sadd.with.overflow.i8",
2209 TyInt(I16) => "llvm.sadd.with.overflow.i16",
2210 TyInt(I32) => "llvm.sadd.with.overflow.i32",
2211 TyInt(I64) => "llvm.sadd.with.overflow.i64",
2213 TyUint(U8) => "llvm.uadd.with.overflow.i8",
2214 TyUint(U16) => "llvm.uadd.with.overflow.i16",
2215 TyUint(U32) => "llvm.uadd.with.overflow.i32",
2216 TyUint(U64) => "llvm.uadd.with.overflow.i64",
2218 _ => unreachable!(),
2220 OverflowOpViaIntrinsic::Sub => match new_sty {
2221 TyInt(I8) => "llvm.ssub.with.overflow.i8",
2222 TyInt(I16) => "llvm.ssub.with.overflow.i16",
2223 TyInt(I32) => "llvm.ssub.with.overflow.i32",
2224 TyInt(I64) => "llvm.ssub.with.overflow.i64",
2226 TyUint(U8) => "llvm.usub.with.overflow.i8",
2227 TyUint(U16) => "llvm.usub.with.overflow.i16",
2228 TyUint(U32) => "llvm.usub.with.overflow.i32",
2229 TyUint(U64) => "llvm.usub.with.overflow.i64",
2231 _ => unreachable!(),
2233 OverflowOpViaIntrinsic::Mul => match new_sty {
2234 TyInt(I8) => "llvm.smul.with.overflow.i8",
2235 TyInt(I16) => "llvm.smul.with.overflow.i16",
2236 TyInt(I32) => "llvm.smul.with.overflow.i32",
2237 TyInt(I64) => "llvm.smul.with.overflow.i64",
2239 TyUint(U8) => "llvm.umul.with.overflow.i8",
2240 TyUint(U16) => "llvm.umul.with.overflow.i16",
2241 TyUint(U32) => "llvm.umul.with.overflow.i32",
2242 TyUint(U64) => "llvm.umul.with.overflow.i64",
2244 _ => unreachable!(),
2249 fn build_intrinsic_call<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>,
2250 info: NodeIdAndSpan,
2251 lhs_t: Ty<'tcx>, lhs: ValueRef,
2253 binop_debug_loc: DebugLoc)
2254 -> (Block<'blk, 'tcx>, ValueRef) {
2255 let llfn = self.to_intrinsic(bcx, lhs_t);
2257 let val = Call(bcx, llfn, &[lhs, rhs], binop_debug_loc);
2258 let result = ExtractValue(bcx, val, 0); // iN operation result
2259 let overflow = ExtractValue(bcx, val, 1); // i1 "did it overflow?"
2261 let cond = ICmp(bcx, llvm::IntEQ, overflow, C_integral(Type::i1(bcx.ccx()), 1, false),
2264 let expect = bcx.ccx().get_intrinsic(&"llvm.expect.i1");
2265 Call(bcx, expect, &[cond, C_integral(Type::i1(bcx.ccx()), 0, false)],
2269 base::with_cond(bcx, cond, |bcx|
2270 controlflow::trans_fail(bcx, info,
2271 InternedString::new("arithmetic operation overflowed")));
2277 impl OverflowOpViaInputCheck {
2278 fn build_with_input_check<'blk, 'tcx>(&self,
2279 bcx: Block<'blk, 'tcx>,
2280 info: NodeIdAndSpan,
2284 binop_debug_loc: DebugLoc)
2285 -> (Block<'blk, 'tcx>, ValueRef)
2287 let lhs_llty = val_ty(lhs);
2288 let rhs_llty = val_ty(rhs);
2290 // Panic if any bits are set outside of bits that we always
2293 // Note that the mask's value is derived from the LHS type
2294 // (since that is where the 32/64 distinction is relevant) but
2295 // the mask's type must match the RHS type (since they will
2296 // both be fed into an and-binop)
2297 let invert_mask = shift_mask_val(bcx, lhs_llty, rhs_llty, true);
2299 let outer_bits = And(bcx, rhs, invert_mask, binop_debug_loc);
2300 let cond = build_nonzero_check(bcx, outer_bits, binop_debug_loc);
2301 let result = match *self {
2302 OverflowOpViaInputCheck::Shl =>
2303 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2304 OverflowOpViaInputCheck::Shr =>
2305 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2308 base::with_cond(bcx, cond, |bcx|
2309 controlflow::trans_fail(bcx, info,
2310 InternedString::new("shift operation overflowed")));
2316 // Check if an integer or vector contains a nonzero element.
2317 fn build_nonzero_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2319 binop_debug_loc: DebugLoc) -> ValueRef {
2320 let llty = val_ty(value);
2321 let kind = llty.kind();
2323 TypeKind::Integer => ICmp(bcx, llvm::IntNE, value, C_null(llty), binop_debug_loc),
2324 TypeKind::Vector => {
2325 // Check if any elements of the vector are nonzero by treating
2326 // it as a wide integer and checking if the integer is nonzero.
2327 let width = llty.vector_length() as u64 * llty.element_type().int_width();
2328 let int_value = BitCast(bcx, value, Type::ix(bcx.ccx(), width));
2329 build_nonzero_check(bcx, int_value, binop_debug_loc)
2331 _ => panic!("build_nonzero_check: expected Integer or Vector, found {:?}", kind),
2335 fn with_overflow_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, oop: OverflowOp, info: NodeIdAndSpan,
2336 lhs_t: Ty<'tcx>, lhs: ValueRef,
2338 binop_debug_loc: DebugLoc)
2339 -> (Block<'blk, 'tcx>, ValueRef) {
2340 if bcx.unreachable.get() { return (bcx, _Undef(lhs)); }
2341 if bcx.ccx().check_overflow() {
2343 match oop.codegen_strategy() {
2344 OverflowCodegen::ViaIntrinsic(oop) =>
2345 oop.build_intrinsic_call(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2346 OverflowCodegen::ViaInputCheck(oop) =>
2347 oop.build_with_input_check(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2350 let res = match oop {
2351 OverflowOp::Add => Add(bcx, lhs, rhs, binop_debug_loc),
2352 OverflowOp::Sub => Sub(bcx, lhs, rhs, binop_debug_loc),
2353 OverflowOp::Mul => Mul(bcx, lhs, rhs, binop_debug_loc),
2356 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2358 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2364 /// We categorize expressions into three kinds. The distinction between
2365 /// lvalue/rvalue is fundamental to the language. The distinction between the
2366 /// two kinds of rvalues is an artifact of trans which reflects how we will
2367 /// generate code for that kind of expression. See trans/expr.rs for more
2369 #[derive(Copy, Clone)]
2377 fn expr_kind(tcx: &TyCtxt, expr: &hir::Expr) -> ExprKind {
2378 if tcx.is_method_call(expr.id) {
2379 // Overloaded operations are generally calls, and hence they are
2380 // generated via DPS, but there are a few exceptions:
2381 return match expr.node {
2382 // `a += b` has a unit result.
2383 hir::ExprAssignOp(..) => ExprKind::RvalueStmt,
2385 // the deref method invoked for `*a` always yields an `&T`
2386 hir::ExprUnary(hir::UnDeref, _) => ExprKind::Lvalue,
2388 // the index method invoked for `a[i]` always yields an `&T`
2389 hir::ExprIndex(..) => ExprKind::Lvalue,
2391 // in the general case, result could be any type, use DPS
2392 _ => ExprKind::RvalueDps
2397 hir::ExprPath(..) => {
2398 match tcx.resolve_expr(expr) {
2399 // Put functions and ctors with the ADTs, as they
2400 // are zero-sized, so DPS is the cheapest option.
2401 Def::Struct(..) | Def::Variant(..) |
2402 Def::Fn(..) | Def::Method(..) => {
2406 // Note: there is actually a good case to be made that
2407 // DefArg's, particularly those of immediate type, ought to
2408 // considered rvalues.
2411 Def::Local(..) => ExprKind::Lvalue,
2414 Def::AssociatedConst(..) => ExprKind::RvalueDatum,
2419 &format!("uncategorized def for expr {}: {:?}",
2426 hir::ExprType(ref expr, _) => {
2427 expr_kind(tcx, expr)
2430 hir::ExprUnary(hir::UnDeref, _) |
2431 hir::ExprField(..) |
2432 hir::ExprTupField(..) |
2433 hir::ExprIndex(..) => {
2438 hir::ExprMethodCall(..) |
2439 hir::ExprStruct(..) |
2442 hir::ExprMatch(..) |
2443 hir::ExprClosure(..) |
2444 hir::ExprBlock(..) |
2445 hir::ExprRepeat(..) |
2446 hir::ExprVec(..) => {
2450 hir::ExprLit(ref lit) if lit.node.is_str() => {
2454 hir::ExprBreak(..) |
2455 hir::ExprAgain(..) |
2457 hir::ExprWhile(..) |
2459 hir::ExprAssign(..) |
2460 hir::ExprInlineAsm(..) |
2461 hir::ExprAssignOp(..) => {
2462 ExprKind::RvalueStmt
2465 hir::ExprLit(_) | // Note: LitStr is carved out above
2466 hir::ExprUnary(..) |
2468 hir::ExprAddrOf(..) |
2469 hir::ExprBinary(..) |
2470 hir::ExprCast(..) => {
2471 ExprKind::RvalueDatum