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_local_var -> Datum`: looks up a local variable or upvar.
49 #![allow(non_camel_case_types)]
51 pub use self::Dest::*;
52 use self::lazy_binop_ty::*;
55 use llvm::{self, ValueRef, TypeKind};
56 use middle::check_const;
58 use middle::lang_items::CoerceUnsizedTraitLangItem;
59 use middle::subst::{Substs, VecPerParamSpace};
61 use trans::{_match, adt, asm, base, callee, closure, consts, controlflow};
64 use trans::cleanup::{self, CleanupMethods, DropHintMethods};
67 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
74 use middle::ty::adjustment::{AdjustDerefRef, AdjustReifyFnPointer};
75 use middle::ty::adjustment::{AdjustUnsafeFnPointer, CustomCoerceUnsized};
76 use middle::ty::{self, Ty};
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;
89 use syntax::parse::token;
94 // These are passed around by the code generating functions to track the
95 // destination of a computation's value.
97 #[derive(Copy, Clone, PartialEq)]
104 pub fn to_string(&self, ccx: &CrateContext) -> String {
106 SaveIn(v) => format!("SaveIn({})", ccx.tn().val_to_string(v)),
107 Ignore => "Ignore".to_string()
112 /// This function is equivalent to `trans(bcx, expr).store_to_dest(dest)` but it may generate
113 /// better optimized LLVM code.
114 pub fn trans_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
117 -> Block<'blk, 'tcx> {
120 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
122 if bcx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
123 // use trans, which may be less efficient but
124 // which will perform the adjustments:
125 let datum = unpack_datum!(bcx, trans(bcx, expr));
126 return datum.store_to_dest(bcx, dest, expr.id);
129 let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
130 if !qualif.intersects(
131 check_const::ConstQualif::NOT_CONST |
132 check_const::ConstQualif::NEEDS_DROP
134 if !qualif.intersects(check_const::ConstQualif::PREFER_IN_PLACE) {
135 if let SaveIn(lldest) = dest {
136 let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
137 bcx.fcx.param_substs);
138 // Cast pointer to destination, because constants
139 // have different types.
140 let lldest = PointerCast(bcx, lldest, val_ty(global));
141 memcpy_ty(bcx, lldest, global, expr_ty_adjusted(bcx, expr));
144 // Even if we don't have a value to emit, and the expression
145 // doesn't have any side-effects, we still have to translate the
146 // body of any closures.
147 // FIXME: Find a better way of handling this case.
149 // The only way we're going to see a `const` at this point is if
150 // it prefers in-place instantiation, likely because it contains
151 // `[x; N]` somewhere within.
153 hir::ExprPath(..) => {
154 match bcx.def(expr.id) {
155 def::DefConst(did) => {
156 let const_expr = consts::get_const_expr(bcx.ccx(), did, expr);
157 // Temporarily get cleanup scopes out of the way,
158 // as they require sub-expressions to be contained
159 // inside the current AST scope.
160 // These should record no cleanups anyways, `const`
161 // can't have destructors.
162 let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
164 // Lock emitted debug locations to the location of
165 // the constant reference expression.
166 debuginfo::with_source_location_override(bcx.fcx,
169 bcx = trans_into(bcx, const_expr, dest)
171 let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
173 assert!(scopes.is_empty());
184 debug!("trans_into() expr={:?}", expr);
186 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
190 bcx.fcx.push_ast_cleanup_scope(cleanup_debug_loc);
192 let kind = expr_kind(bcx.tcx(), expr);
194 ExprKind::Lvalue | ExprKind::RvalueDatum => {
195 trans_unadjusted(bcx, expr).store_to_dest(dest, expr.id)
197 ExprKind::RvalueDps => {
198 trans_rvalue_dps_unadjusted(bcx, expr, dest)
200 ExprKind::RvalueStmt => {
201 trans_rvalue_stmt_unadjusted(bcx, expr)
205 bcx.fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id)
208 /// Translates an expression, returning a datum (and new block) encapsulating the result. When
209 /// possible, it is preferred to use `trans_into`, as that may avoid creating a temporary on the
211 pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
213 -> DatumBlock<'blk, 'tcx, Expr> {
214 debug!("trans(expr={:?})", expr);
218 let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
219 let adjusted_global = !qualif.intersects(check_const::ConstQualif::NON_STATIC_BORROWS);
220 let global = if !qualif.intersects(
221 check_const::ConstQualif::NOT_CONST |
222 check_const::ConstQualif::NEEDS_DROP
224 let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
225 bcx.fcx.param_substs);
227 if qualif.intersects(check_const::ConstQualif::HAS_STATIC_BORROWS) {
228 // Is borrowed as 'static, must return lvalue.
230 // Cast pointer to global, because constants have different types.
231 let const_ty = expr_ty_adjusted(bcx, expr);
232 let llty = type_of::type_of(bcx.ccx(), const_ty);
233 let global = PointerCast(bcx, global, llty.ptr_to());
234 let datum = Datum::new(global, const_ty, Lvalue::new("expr::trans"));
235 return DatumBlock::new(bcx, datum.to_expr_datum());
238 // Otherwise, keep around and perform adjustments, if needed.
239 let const_ty = if adjusted_global {
240 expr_ty_adjusted(bcx, expr)
245 // This could use a better heuristic.
246 Some(if type_is_immediate(bcx.ccx(), const_ty) {
247 // Cast pointer to global, because constants have different types.
248 let llty = type_of::type_of(bcx.ccx(), const_ty);
249 let global = PointerCast(bcx, global, llty.ptr_to());
250 // Maybe just get the value directly, instead of loading it?
251 immediate_rvalue(load_ty(bcx, global, const_ty), const_ty)
253 let scratch = alloc_ty(bcx, const_ty, "const");
254 call_lifetime_start(bcx, scratch);
255 let lldest = if !const_ty.is_structural() {
256 // Cast pointer to slot, because constants have different types.
257 PointerCast(bcx, scratch, val_ty(global))
259 // In this case, memcpy_ty calls llvm.memcpy after casting both
260 // source and destination to i8*, so we don't need any casts.
263 memcpy_ty(bcx, lldest, global, const_ty);
264 Datum::new(scratch, const_ty, Rvalue::new(ByRef))
270 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
274 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
275 let datum = match global {
276 Some(rvalue) => rvalue.to_expr_datum(),
277 None => unpack_datum!(bcx, trans_unadjusted(bcx, expr))
279 let datum = if adjusted_global {
280 datum // trans::consts already performed adjustments.
282 unpack_datum!(bcx, apply_adjustments(bcx, expr, datum))
284 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id);
285 return DatumBlock::new(bcx, datum);
288 pub fn get_meta(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
289 StructGEP(bcx, fat_ptr, abi::FAT_PTR_EXTRA)
292 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
293 StructGEP(bcx, fat_ptr, abi::FAT_PTR_ADDR)
296 pub fn copy_fat_ptr(bcx: Block, src_ptr: ValueRef, dst_ptr: ValueRef) {
297 Store(bcx, Load(bcx, get_dataptr(bcx, src_ptr)), get_dataptr(bcx, dst_ptr));
298 Store(bcx, Load(bcx, get_meta(bcx, src_ptr)), get_meta(bcx, dst_ptr));
301 /// Retrieve the information we are losing (making dynamic) in an unsizing
304 /// The `old_info` argument is a bit funny. It is intended for use
305 /// in an upcast, where the new vtable for an object will be drived
306 /// from the old one.
307 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
310 old_info: Option<ValueRef>,
311 param_substs: &'tcx Substs<'tcx>)
313 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
314 match (&source.sty, &target.sty) {
315 (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
316 (&ty::TyTrait(_), &ty::TyTrait(_)) => {
317 // For now, upcasts are limited to changes in marker
318 // traits, and hence never actually require an actual
319 // change to the vtable.
320 old_info.expect("unsized_info: missing old info for trait upcast")
322 (_, &ty::TyTrait(box ty::TraitTy { ref principal, .. })) => {
323 // Note that we preserve binding levels here:
324 let substs = principal.0.substs.with_self_ty(source).erase_regions();
325 let substs = ccx.tcx().mk_substs(substs);
326 let trait_ref = ty::Binder(ty::TraitRef { def_id: principal.def_id(),
328 consts::ptrcast(meth::get_vtable(ccx, trait_ref, param_substs),
329 Type::vtable_ptr(ccx))
331 _ => ccx.sess().bug(&format!("unsized_info: invalid unsizing {:?} -> {:?}",
337 /// Helper for trans that apply adjustments from `expr` to `datum`, which should be the unadjusted
338 /// translation of `expr`.
339 fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
341 datum: Datum<'tcx, Expr>)
342 -> DatumBlock<'blk, 'tcx, Expr>
345 let mut datum = datum;
346 let adjustment = match bcx.tcx().tables.borrow().adjustments.get(&expr.id).cloned() {
348 return DatumBlock::new(bcx, datum);
352 debug!("unadjusted datum for expr {:?}: {} adjustment={:?}",
354 datum.to_string(bcx.ccx()),
357 AdjustReifyFnPointer => {
358 // FIXME(#19925) once fn item types are
359 // zero-sized, we'll need to do something here
361 AdjustUnsafeFnPointer => {
362 // purely a type-level thing
364 AdjustDerefRef(ref adj) => {
365 let skip_reborrows = if adj.autoderefs == 1 && adj.autoref.is_some() {
366 // We are a bit paranoid about adjustments and thus might have a re-
367 // borrow here which merely derefs and then refs again (it might have
368 // a different region or mutability, but we don't care here).
370 // Don't skip a conversion from Box<T> to &T, etc.
372 if bcx.tcx().is_overloaded_autoderef(expr.id, 0) {
373 // Don't skip an overloaded deref.
385 if adj.autoderefs > skip_reborrows {
387 let lval = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "auto_deref", expr.id));
388 datum = unpack_datum!(bcx, deref_multiple(bcx, expr,
389 lval.to_expr_datum(),
390 adj.autoderefs - skip_reborrows));
393 // (You might think there is a more elegant way to do this than a
394 // skip_reborrows bool, but then you remember that the borrow checker exists).
395 if skip_reborrows == 0 && adj.autoref.is_some() {
396 datum = unpack_datum!(bcx, auto_ref(bcx, datum, expr));
399 if let Some(target) = adj.unsize {
400 // We do not arrange cleanup ourselves; if we already are an
401 // L-value, then cleanup will have already been scheduled (and
402 // the `datum.to_rvalue_datum` call below will emit code to zero
403 // the drop flag when moving out of the L-value). If we are an
404 // R-value, then we do not need to schedule cleanup.
405 let source_datum = unpack_datum!(bcx,
406 datum.to_rvalue_datum(bcx, "__coerce_source"));
408 let target = bcx.monomorphize(&target);
410 let scratch = alloc_ty(bcx, target, "__coerce_target");
411 call_lifetime_start(bcx, scratch);
412 let target_datum = Datum::new(scratch, target,
414 bcx = coerce_unsized(bcx, expr.span, source_datum, target_datum);
415 datum = Datum::new(scratch, target,
416 RvalueExpr(Rvalue::new(ByRef)));
420 debug!("after adjustments, datum={}", datum.to_string(bcx.ccx()));
421 DatumBlock::new(bcx, datum)
424 fn coerce_unsized<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
426 source: Datum<'tcx, Rvalue>,
427 target: Datum<'tcx, Rvalue>)
428 -> Block<'blk, 'tcx> {
430 debug!("coerce_unsized({} -> {})",
431 source.to_string(bcx.ccx()),
432 target.to_string(bcx.ccx()));
434 match (&source.ty.sty, &target.ty.sty) {
435 (&ty::TyBox(a), &ty::TyBox(b)) |
436 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
437 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
438 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
439 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
440 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
441 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
442 let (inner_source, inner_target) = (a, b);
444 let (base, old_info) = if !type_is_sized(bcx.tcx(), inner_source) {
445 // Normally, the source is a thin pointer and we are
446 // adding extra info to make a fat pointer. The exception
447 // is when we are upcasting an existing object fat pointer
448 // to use a different vtable. In that case, we want to
449 // load out the original data pointer so we can repackage
451 (Load(bcx, get_dataptr(bcx, source.val)),
452 Some(Load(bcx, get_meta(bcx, source.val))))
454 let val = if source.kind.is_by_ref() {
455 load_ty(bcx, source.val, source.ty)
462 let info = unsized_info(bcx.ccx(), inner_source, inner_target,
463 old_info, bcx.fcx.param_substs);
465 // Compute the base pointer. This doesn't change the pointer value,
466 // but merely its type.
467 let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), inner_target).ptr_to();
468 let base = PointerCast(bcx, base, ptr_ty);
470 Store(bcx, base, get_dataptr(bcx, target.val));
471 Store(bcx, info, get_meta(bcx, target.val));
474 // This can be extended to enums and tuples in the future.
475 // (&ty::TyEnum(def_id_a, _), &ty::TyEnum(def_id_b, _)) |
476 (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
477 assert_eq!(def_id_a, def_id_b);
479 // The target is already by-ref because it's to be written to.
480 let source = unpack_datum!(bcx, source.to_ref_datum(bcx));
481 assert!(target.kind.is_by_ref());
483 let trait_substs = Substs::erased(VecPerParamSpace::new(vec![target.ty],
486 let trait_ref = ty::Binder(ty::TraitRef {
487 def_id: langcall(bcx, Some(span), "coercion",
488 CoerceUnsizedTraitLangItem),
489 substs: bcx.tcx().mk_substs(trait_substs)
492 let kind = match fulfill_obligation(bcx.ccx(), span, trait_ref) {
493 traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
494 bcx.tcx().custom_coerce_unsized_kind(impl_def_id)
497 bcx.sess().span_bug(span, &format!("invalid CoerceUnsized vtable: {:?}",
502 let repr_source = adt::represent_type(bcx.ccx(), source.ty);
503 let src_fields = match &*repr_source {
504 &adt::Repr::Univariant(ref s, _) => &s.fields,
505 _ => bcx.sess().span_bug(span,
506 &format!("Non univariant struct? (repr_source: {:?})",
509 let repr_target = adt::represent_type(bcx.ccx(), target.ty);
510 let target_fields = match &*repr_target {
511 &adt::Repr::Univariant(ref s, _) => &s.fields,
512 _ => bcx.sess().span_bug(span,
513 &format!("Non univariant struct? (repr_target: {:?})",
517 let coerce_index = match kind {
518 CustomCoerceUnsized::Struct(i) => i
520 assert!(coerce_index < src_fields.len() && src_fields.len() == target_fields.len());
522 let iter = src_fields.iter().zip(target_fields).enumerate();
523 for (i, (src_ty, target_ty)) in iter {
524 let ll_source = adt::trans_field_ptr(bcx, &repr_source, source.val, 0, i);
525 let ll_target = adt::trans_field_ptr(bcx, &repr_target, target.val, 0, i);
527 // If this is the field we need to coerce, recurse on it.
528 if i == coerce_index {
529 coerce_unsized(bcx, span,
530 Datum::new(ll_source, src_ty,
532 Datum::new(ll_target, target_ty,
533 Rvalue::new(ByRef)));
535 // Otherwise, simply copy the data from the source.
536 assert_eq!(src_ty, target_ty);
537 memcpy_ty(bcx, ll_target, ll_source, src_ty);
541 _ => bcx.sess().bug(&format!("coerce_unsized: invalid coercion {:?} -> {:?}",
548 /// Translates an expression in "lvalue" mode -- meaning that it returns a reference to the memory
549 /// that the expr represents.
551 /// If this expression is an rvalue, this implies introducing a temporary. In other words,
552 /// something like `x().f` is translated into roughly the equivalent of
554 /// { tmp = x(); tmp.f }
555 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
558 -> DatumBlock<'blk, 'tcx, Lvalue> {
560 let datum = unpack_datum!(bcx, trans(bcx, expr));
561 return datum.to_lvalue_datum(bcx, name, expr.id);
564 /// A version of `trans` that ignores adjustments. You almost certainly do not want to call this
566 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
568 -> DatumBlock<'blk, 'tcx, Expr> {
571 debug!("trans_unadjusted(expr={:?})", expr);
572 let _indenter = indenter();
574 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
576 return match expr_kind(bcx.tcx(), expr) {
577 ExprKind::Lvalue | ExprKind::RvalueDatum => {
578 let datum = unpack_datum!(bcx, {
579 trans_datum_unadjusted(bcx, expr)
582 DatumBlock {bcx: bcx, datum: datum}
585 ExprKind::RvalueStmt => {
586 bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
587 nil(bcx, expr_ty(bcx, expr))
590 ExprKind::RvalueDps => {
591 let ty = expr_ty(bcx, expr);
592 if type_is_zero_size(bcx.ccx(), ty) {
593 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
596 let scratch = rvalue_scratch_datum(bcx, ty, "");
597 bcx = trans_rvalue_dps_unadjusted(
598 bcx, expr, SaveIn(scratch.val));
600 // Note: this is not obviously a good idea. It causes
601 // immediate values to be loaded immediately after a
602 // return from a call or other similar expression,
603 // which in turn leads to alloca's having shorter
604 // lifetimes and hence larger stack frames. However,
605 // in turn it can lead to more register pressure.
606 // Still, in practice it seems to increase
607 // performance, since we have fewer problems with
609 let scratch = unpack_datum!(
610 bcx, scratch.to_appropriate_datum(bcx));
612 DatumBlock::new(bcx, scratch.to_expr_datum())
617 fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: Ty<'tcx>)
618 -> DatumBlock<'blk, 'tcx, Expr> {
619 let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
620 let datum = immediate_rvalue(llval, ty);
621 DatumBlock::new(bcx, datum.to_expr_datum())
625 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
627 -> DatumBlock<'blk, 'tcx, Expr> {
630 let _icx = push_ctxt("trans_datum_unadjusted");
633 hir::ExprParen(ref e) => {
636 hir::ExprPath(..) => {
637 trans_def(bcx, expr, bcx.def(expr.id))
639 hir::ExprField(ref base, ident) => {
640 trans_rec_field(bcx, &**base, ident.node.name)
642 hir::ExprTupField(ref base, idx) => {
643 trans_rec_tup_field(bcx, &**base, idx.node)
645 hir::ExprIndex(ref base, ref idx) => {
646 trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id))
648 hir::ExprBox(_, ref contents) => {
649 // Special case for `Box<T>`
650 let box_ty = expr_ty(bcx, expr);
651 let contents_ty = expr_ty(bcx, &**contents);
654 trans_uniq_expr(bcx, expr, box_ty, &**contents, contents_ty)
656 _ => bcx.sess().span_bug(expr.span,
657 "expected unique box")
661 hir::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, &**lit),
662 hir::ExprBinary(op, ref lhs, ref rhs) => {
663 trans_binary(bcx, expr, op, &**lhs, &**rhs)
665 hir::ExprUnary(op, ref x) => {
666 trans_unary(bcx, expr, op, &**x)
668 hir::ExprAddrOf(_, ref x) => {
670 hir::ExprRepeat(..) | hir::ExprVec(..) => {
671 // Special case for slices.
672 let cleanup_debug_loc =
673 debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
677 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
678 let datum = unpack_datum!(
679 bcx, tvec::trans_slice_vec(bcx, expr, &**x));
680 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
681 DatumBlock::new(bcx, datum)
684 trans_addr_of(bcx, expr, &**x)
688 hir::ExprCast(ref val, _) => {
689 // Datum output mode means this is a scalar cast:
690 trans_imm_cast(bcx, &**val, expr.id)
693 bcx.tcx().sess.span_bug(
695 &format!("trans_rvalue_datum_unadjusted reached \
696 fall-through case: {:?}",
702 fn trans_field<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
705 -> DatumBlock<'blk, 'tcx, Expr> where
706 F: FnOnce(&'blk ty::ctxt<'tcx>, &VariantInfo<'tcx>) -> usize,
709 let _icx = push_ctxt("trans_rec_field");
711 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
712 let bare_ty = base_datum.ty;
713 let repr = adt::represent_type(bcx.ccx(), bare_ty);
714 let vinfo = VariantInfo::from_ty(bcx.tcx(), bare_ty, None);
716 let ix = get_idx(bcx.tcx(), &vinfo);
717 let d = base_datum.get_element(
720 |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, vinfo.discr, ix));
722 if type_is_sized(bcx.tcx(), d.ty) {
723 DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
725 let scratch = rvalue_scratch_datum(bcx, d.ty, "");
726 Store(bcx, d.val, get_dataptr(bcx, scratch.val));
727 let info = Load(bcx, get_meta(bcx, base_datum.val));
728 Store(bcx, info, get_meta(bcx, scratch.val));
730 // Always generate an lvalue datum, because this pointer doesn't own
731 // the data and cleanup is scheduled elsewhere.
732 DatumBlock::new(bcx, Datum::new(scratch.val, scratch.ty, LvalueExpr(d.kind)))
736 /// Translates `base.field`.
737 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
740 -> DatumBlock<'blk, 'tcx, Expr> {
741 trans_field(bcx, base, |_, vinfo| vinfo.field_index(field))
744 /// Translates `base.<idx>`.
745 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
748 -> DatumBlock<'blk, 'tcx, Expr> {
749 trans_field(bcx, base, |_, _| idx)
752 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
753 index_expr: &hir::Expr,
756 method_call: MethodCall)
757 -> DatumBlock<'blk, 'tcx, Expr> {
758 //! Translates `base[idx]`.
760 let _icx = push_ctxt("trans_index");
764 let index_expr_debug_loc = index_expr.debug_loc();
766 // Check for overloaded index.
767 let method_ty = ccx.tcx()
772 .map(|method| method.ty);
773 let elt_datum = match method_ty {
775 let method_ty = monomorphize_type(bcx, method_ty);
777 let base_datum = unpack_datum!(bcx, trans(bcx, base));
779 // Translate index expression.
780 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
782 let ref_ty = // invoked methods have LB regions instantiated:
783 bcx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
784 let elt_ty = match ref_ty.builtin_deref(true, ty::NoPreference) {
786 bcx.tcx().sess.span_bug(index_expr.span,
787 "index method didn't return a \
788 dereferenceable type?!")
790 Some(elt_tm) => elt_tm.ty,
793 // Overloaded. Evaluate `trans_overloaded_op`, which will
794 // invoke the user's index() method, which basically yields
795 // a `&T` pointer. We can then proceed down the normal
796 // path (below) to dereference that `&T`.
797 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_index_elt");
799 trans_overloaded_op(bcx,
803 Some((ix_datum, idx.id)),
804 Some(SaveIn(scratch.val)),
806 let datum = scratch.to_expr_datum();
807 let lval = Lvalue::new("expr::trans_index overload");
808 if type_is_sized(bcx.tcx(), elt_ty) {
809 Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr(lval))
811 Datum::new(datum.val, elt_ty, LvalueExpr(lval))
815 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
819 // Translate index expression and cast to a suitable LLVM integer.
820 // Rust is less strict than LLVM in this regard.
821 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
822 let ix_val = ix_datum.to_llscalarish(bcx);
823 let ix_size = machine::llbitsize_of_real(bcx.ccx(),
825 let int_size = machine::llbitsize_of_real(bcx.ccx(),
828 if ix_size < int_size {
829 if expr_ty(bcx, idx).is_signed() {
830 SExt(bcx, ix_val, ccx.int_type())
831 } else { ZExt(bcx, ix_val, ccx.int_type()) }
832 } else if ix_size > int_size {
833 Trunc(bcx, ix_val, ccx.int_type())
839 let unit_ty = base_datum.ty.sequence_element_type(bcx.tcx());
841 let (base, len) = base_datum.get_vec_base_and_len(bcx);
843 debug!("trans_index: base {}", bcx.val_to_string(base));
844 debug!("trans_index: len {}", bcx.val_to_string(len));
846 let bounds_check = ICmp(bcx,
850 index_expr_debug_loc);
851 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
852 let expected = Call(bcx,
854 &[bounds_check, C_bool(ccx, false)],
856 index_expr_debug_loc);
857 bcx = with_cond(bcx, expected, |bcx| {
858 controlflow::trans_fail_bounds_check(bcx,
859 expr_info(index_expr),
863 let elt = InBoundsGEP(bcx, base, &[ix_val]);
864 let elt = PointerCast(bcx, elt, type_of::type_of(ccx, unit_ty).ptr_to());
865 let lval = Lvalue::new("expr::trans_index fallback");
866 Datum::new(elt, unit_ty, LvalueExpr(lval))
870 DatumBlock::new(bcx, elt_datum)
873 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
874 ref_expr: &hir::Expr,
876 -> DatumBlock<'blk, 'tcx, Expr> {
877 //! Translates a reference to a path.
879 let _icx = push_ctxt("trans_def_lvalue");
881 def::DefFn(..) | def::DefMethod(..) |
882 def::DefStruct(_) | def::DefVariant(..) => {
883 let datum = trans_def_fn_unadjusted(bcx.ccx(), ref_expr, def,
884 bcx.fcx.param_substs);
885 DatumBlock::new(bcx, datum.to_expr_datum())
887 def::DefStatic(did, _) => {
888 // There are two things that may happen here:
889 // 1) If the static item is defined in this crate, it will be
890 // translated using `get_item_val`, and we return a pointer to
892 // 2) If the static item is defined in another crate then we add
893 // (or reuse) a declaration of an external global, and return a
895 let const_ty = expr_ty(bcx, ref_expr);
897 // For external constants, we don't inline.
898 let val = if did.is_local() {
901 // The LLVM global has the type of its initializer,
902 // which may not be equal to the enum's type for
904 let val = base::get_item_val(bcx.ccx(), did.node);
905 let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to();
906 PointerCast(bcx, val, pty)
909 base::get_extern_const(bcx.ccx(), did, const_ty)
911 let lval = Lvalue::new("expr::trans_def");
912 DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr(lval)))
914 def::DefConst(_) => {
915 bcx.sess().span_bug(ref_expr.span,
916 "constant expression should not reach expr::trans_def")
919 DatumBlock::new(bcx, trans_local_var(bcx, def).to_expr_datum())
924 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
926 -> Block<'blk, 'tcx> {
928 let _icx = push_ctxt("trans_rvalue_stmt");
930 if bcx.unreachable.get() {
934 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
937 hir::ExprParen(ref e) => {
938 trans_into(bcx, &**e, Ignore)
940 hir::ExprBreak(label_opt) => {
941 controlflow::trans_break(bcx, expr, label_opt.map(|l| l.node))
943 hir::ExprAgain(label_opt) => {
944 controlflow::trans_cont(bcx, expr, label_opt.map(|l| l.node))
946 hir::ExprRet(ref ex) => {
947 // Check to see if the return expression itself is reachable.
948 // This can occur when the inner expression contains a return
949 let reachable = if let Some(ref cfg) = bcx.fcx.cfg {
950 cfg.node_is_reachable(expr.id)
956 controlflow::trans_ret(bcx, expr, ex.as_ref().map(|e| &**e))
958 // If it's not reachable, just translate the inner expression
959 // directly. This avoids having to manage a return slot when
960 // it won't actually be used anyway.
961 if let &Some(ref x) = ex {
962 bcx = trans_into(bcx, &**x, Ignore);
964 // Mark the end of the block as unreachable. Once we get to
965 // a return expression, there's no more we should be doing
971 hir::ExprWhile(ref cond, ref body, _) => {
972 controlflow::trans_while(bcx, expr, &**cond, &**body)
974 hir::ExprLoop(ref body, _) => {
975 controlflow::trans_loop(bcx, expr, &**body)
977 hir::ExprAssign(ref dst, ref src) => {
978 let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
979 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
981 if bcx.fcx.type_needs_drop(dst_datum.ty) {
982 // If there are destructors involved, make sure we
983 // are copying from an rvalue, since that cannot possible
984 // alias an lvalue. We are concerned about code like:
992 // where e.g. a : Option<Foo> and a.b :
993 // Option<Foo>. In that case, freeing `a` before the
994 // assignment may also free `a.b`!
996 // We could avoid this intermediary with some analysis
997 // to determine whether `dst` may possibly own `src`.
998 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
999 let src_datum = unpack_datum!(
1000 bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
1001 let opt_hint_datum = dst_datum.kind.drop_flag_info.hint_datum(bcx);
1002 let opt_hint_val = opt_hint_datum.map(|d|d.to_value());
1004 // 1. Drop the data at the destination, passing the
1005 // drop-hint in case the lvalue has already been
1006 // dropped or moved.
1007 bcx = glue::drop_ty_core(bcx,
1014 // 2. We are overwriting the destination; ensure that
1015 // its drop-hint (if any) says "initialized."
1016 if let Some(hint_val) = opt_hint_val {
1017 let hint_llval = hint_val.value();
1018 let drop_needed = C_u8(bcx.fcx.ccx, adt::DTOR_NEEDED_HINT);
1019 Store(bcx, drop_needed, hint_llval);
1021 src_datum.store_to(bcx, dst_datum.val)
1023 src_datum.store_to(bcx, dst_datum.val)
1026 hir::ExprAssignOp(op, ref dst, ref src) => {
1027 trans_assign_op(bcx, expr, op, &**dst, &**src)
1029 hir::ExprInlineAsm(ref a) => {
1030 asm::trans_inline_asm(bcx, a)
1033 bcx.tcx().sess.span_bug(
1035 &format!("trans_rvalue_stmt_unadjusted reached \
1036 fall-through case: {:?}",
1042 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1045 -> Block<'blk, 'tcx> {
1046 let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
1048 let tcx = bcx.tcx();
1050 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
1053 hir::ExprParen(ref e) => {
1054 trans_into(bcx, &**e, dest)
1056 hir::ExprPath(..) => {
1057 trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
1059 hir::ExprIf(ref cond, ref thn, ref els) => {
1060 controlflow::trans_if(bcx, expr.id, &**cond, &**thn, els.as_ref().map(|e| &**e), dest)
1062 hir::ExprMatch(ref discr, ref arms, _) => {
1063 _match::trans_match(bcx, expr, &**discr, &arms[..], dest)
1065 hir::ExprBlock(ref blk) => {
1066 controlflow::trans_block(bcx, &**blk, dest)
1068 hir::ExprStruct(_, ref fields, ref base) => {
1071 base.as_ref().map(|e| &**e),
1074 node_id_type(bcx, expr.id),
1077 hir::ExprRange(ref start, ref end) => {
1078 // FIXME it is just not right that we are synthesising ast nodes in
1080 fn make_field(field_name: &str, expr: P<hir::Expr>) -> hir::Field {
1082 ident: codemap::dummy_spanned(token::str_to_ident(field_name)),
1084 span: codemap::DUMMY_SP,
1088 // A range just desugars into a struct.
1089 // Note that the type of the start and end may not be the same, but
1090 // they should only differ in their lifetime, which should not matter
1092 let (did, fields, ty_params) = match (start, end) {
1093 (&Some(ref start), &Some(ref end)) => {
1095 let fields = vec![make_field("start", start.clone()),
1096 make_field("end", end.clone())];
1097 (tcx.lang_items.range_struct(), fields, vec![node_id_type(bcx, start.id)])
1099 (&Some(ref start), &None) => {
1100 // Desugar to RangeFrom
1101 let fields = vec![make_field("start", start.clone())];
1102 (tcx.lang_items.range_from_struct(), fields, vec![node_id_type(bcx, start.id)])
1104 (&None, &Some(ref end)) => {
1105 // Desugar to RangeTo
1106 let fields = vec![make_field("end", end.clone())];
1107 (tcx.lang_items.range_to_struct(), fields, vec![node_id_type(bcx, end.id)])
1110 // Desugar to RangeFull
1111 (tcx.lang_items.range_full_struct(), vec![], vec![])
1115 if let Some(did) = did {
1116 let substs = Substs::new_type(ty_params, vec![]);
1122 tcx.mk_struct(tcx.lookup_adt_def(did),
1123 tcx.mk_substs(substs)),
1126 tcx.sess.span_bug(expr.span,
1127 "No lang item for ranges (how did we get this far?)")
1130 hir::ExprTup(ref args) => {
1131 let numbered_fields: Vec<(usize, &hir::Expr)> =
1132 args.iter().enumerate().map(|(i, arg)| (i, &**arg)).collect();
1136 &numbered_fields[..],
1141 hir::ExprLit(ref lit) => {
1143 hir::LitStr(ref s, _) => {
1144 tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1149 .span_bug(expr.span,
1150 "trans_rvalue_dps_unadjusted shouldn't be \
1151 translating this type of literal")
1155 hir::ExprVec(..) | hir::ExprRepeat(..) => {
1156 tvec::trans_fixed_vstore(bcx, expr, dest)
1158 hir::ExprClosure(_, ref decl, ref body) => {
1159 let dest = match dest {
1160 SaveIn(lldest) => closure::Dest::SaveIn(bcx, lldest),
1161 Ignore => closure::Dest::Ignore(bcx.ccx())
1163 let substs = match expr_ty(bcx, expr).sty {
1164 ty::TyClosure(_, ref substs) => substs,
1166 bcx.tcx().sess.span_bug(
1168 &format!("closure expr without closure type: {:?}", t)),
1170 closure::trans_closure_expr(dest, decl, body, expr.id, substs).unwrap_or(bcx)
1172 hir::ExprCall(ref f, ref args) => {
1173 if bcx.tcx().is_method_call(expr.id) {
1174 trans_overloaded_call(bcx,
1180 callee::trans_call(bcx,
1183 callee::ArgExprs(&args[..]),
1187 hir::ExprMethodCall(_, _, ref args) => {
1188 callee::trans_method_call(bcx,
1191 callee::ArgExprs(&args[..]),
1194 hir::ExprBinary(op, ref lhs, ref rhs) => {
1195 // if not overloaded, would be RvalueDatumExpr
1196 let lhs = unpack_datum!(bcx, trans(bcx, &**lhs));
1197 let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs));
1198 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs,
1199 Some((rhs_datum, rhs.id)), Some(dest),
1200 !rustc_front::util::is_by_value_binop(op.node)).bcx
1202 hir::ExprUnary(op, ref subexpr) => {
1203 // if not overloaded, would be RvalueDatumExpr
1204 let arg = unpack_datum!(bcx, trans(bcx, &**subexpr));
1205 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id),
1206 arg, None, Some(dest), !rustc_front::util::is_by_value_unop(op)).bcx
1208 hir::ExprIndex(ref base, ref idx) => {
1209 // if not overloaded, would be RvalueDatumExpr
1210 let base = unpack_datum!(bcx, trans(bcx, &**base));
1211 let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx));
1212 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
1213 Some((idx_datum, idx.id)), Some(dest), true).bcx
1215 hir::ExprCast(..) => {
1216 // Trait casts used to come this way, now they should be coercions.
1217 bcx.tcx().sess.span_bug(expr.span, "DPS expr_cast (residual trait cast?)")
1219 hir::ExprAssignOp(op, ref dst, ref src) => {
1220 trans_assign_op(bcx, expr, op, &**dst, &**src)
1223 bcx.tcx().sess.span_bug(
1225 &format!("trans_rvalue_dps_unadjusted reached fall-through \
1232 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1233 ref_expr: &hir::Expr,
1236 -> Block<'blk, 'tcx> {
1237 let _icx = push_ctxt("trans_def_dps_unadjusted");
1239 let lldest = match dest {
1240 SaveIn(lldest) => lldest,
1241 Ignore => { return bcx; }
1245 def::DefVariant(tid, vid, _) => {
1246 let variant = bcx.tcx().lookup_adt_def(tid).variant_with_id(vid);
1247 if let ty::VariantKind::Tuple = variant.kind() {
1249 let llfn = callee::trans_fn_ref(bcx.ccx(), vid,
1250 ExprId(ref_expr.id),
1251 bcx.fcx.param_substs).val;
1252 Store(bcx, llfn, lldest);
1256 let ty = expr_ty(bcx, ref_expr);
1257 let repr = adt::represent_type(bcx.ccx(), ty);
1258 adt::trans_set_discr(bcx, &*repr, lldest, variant.disr_val);
1262 def::DefStruct(_) => {
1263 let ty = expr_ty(bcx, ref_expr);
1265 ty::TyStruct(def, _) if def.has_dtor() => {
1266 let repr = adt::represent_type(bcx.ccx(), ty);
1267 adt::trans_set_discr(bcx, &*repr, lldest, 0);
1274 bcx.tcx().sess.span_bug(ref_expr.span, &format!(
1275 "Non-DPS def {:?} referened by {}",
1276 def, bcx.node_id_to_string(ref_expr.id)));
1281 pub fn trans_def_fn_unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1282 ref_expr: &hir::Expr,
1284 param_substs: &'tcx Substs<'tcx>)
1285 -> Datum<'tcx, Rvalue> {
1286 let _icx = push_ctxt("trans_def_datum_unadjusted");
1289 def::DefFn(did, _) |
1290 def::DefStruct(did) | def::DefVariant(_, did, _) => {
1291 callee::trans_fn_ref(ccx, did, ExprId(ref_expr.id), param_substs)
1293 def::DefMethod(method_did) => {
1294 match ccx.tcx().impl_or_trait_item(method_did).container() {
1295 ty::ImplContainer(_) => {
1296 callee::trans_fn_ref(ccx, method_did,
1297 ExprId(ref_expr.id),
1300 ty::TraitContainer(trait_did) => {
1301 meth::trans_static_method_callee(ccx, method_did,
1302 trait_did, ref_expr.id,
1308 ccx.tcx().sess.span_bug(ref_expr.span, &format!(
1309 "trans_def_fn_unadjusted invoked on: {:?} for {:?}",
1316 /// Translates a reference to a local variable or argument. This always results in an lvalue datum.
1317 pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1319 -> Datum<'tcx, Lvalue> {
1320 let _icx = push_ctxt("trans_local_var");
1323 def::DefUpvar(nid, _, _) => {
1324 // Can't move upvars, so this is never a ZeroMemLastUse.
1325 let local_ty = node_id_type(bcx, nid);
1326 let lval = Lvalue::new_with_hint("expr::trans_local_var (upvar)",
1327 bcx, nid, HintKind::ZeroAndMaintain);
1328 match bcx.fcx.llupvars.borrow().get(&nid) {
1329 Some(&val) => Datum::new(val, local_ty, lval),
1331 bcx.sess().bug(&format!(
1332 "trans_local_var: no llval for upvar {} found",
1337 def::DefLocal(nid) => {
1338 let datum = match bcx.fcx.lllocals.borrow().get(&nid) {
1341 bcx.sess().bug(&format!(
1342 "trans_local_var: no datum for local/arg {} found",
1346 debug!("take_local(nid={}, v={}, ty={})",
1347 nid, bcx.val_to_string(datum.val), datum.ty);
1351 bcx.sess().unimpl(&format!(
1352 "unsupported def type in trans_local_var: {:?}",
1358 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1359 fields: &[hir::Field],
1360 base: Option<&hir::Expr>,
1361 expr_span: codemap::Span,
1362 expr_id: ast::NodeId,
1364 dest: Dest) -> Block<'blk, 'tcx> {
1365 let _icx = push_ctxt("trans_rec");
1367 let tcx = bcx.tcx();
1368 let vinfo = VariantInfo::of_node(tcx, ty, expr_id);
1370 let mut need_base = vec![true; vinfo.fields.len()];
1372 let numbered_fields = fields.iter().map(|field| {
1373 let pos = vinfo.field_index(field.ident.node.name);
1374 need_base[pos] = false;
1376 }).collect::<Vec<_>>();
1378 let optbase = match base {
1379 Some(base_expr) => {
1380 let mut leftovers = Vec::new();
1381 for (i, b) in need_base.iter().enumerate() {
1383 leftovers.push((i, vinfo.fields[i].1));
1386 Some(StructBaseInfo {expr: base_expr,
1387 fields: leftovers })
1390 if need_base.iter().any(|b| *b) {
1391 tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1403 DebugLoc::At(expr_id, expr_span))
1406 /// Information that `trans_adt` needs in order to fill in the fields
1407 /// of a struct copied from a base struct (e.g., from an expression
1408 /// like `Foo { a: b, ..base }`.
1410 /// Note that `fields` may be empty; the base expression must always be
1411 /// evaluated for side-effects.
1412 pub struct StructBaseInfo<'a, 'tcx> {
1413 /// The base expression; will be evaluated after all explicit fields.
1414 expr: &'a hir::Expr,
1415 /// The indices of fields to copy paired with their types.
1416 fields: Vec<(usize, Ty<'tcx>)>
1419 /// Constructs an ADT instance:
1421 /// - `fields` should be a list of field indices paired with the
1422 /// expression to store into that field. The initializers will be
1423 /// evaluated in the order specified by `fields`.
1425 /// - `optbase` contains information on the base struct (if any) from
1426 /// which remaining fields are copied; see comments on `StructBaseInfo`.
1427 pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1430 fields: &[(usize, &hir::Expr)],
1431 optbase: Option<StructBaseInfo<'a, 'tcx>>,
1433 debug_location: DebugLoc)
1434 -> Block<'blk, 'tcx> {
1435 let _icx = push_ctxt("trans_adt");
1437 let repr = adt::represent_type(bcx.ccx(), ty);
1439 debug_location.apply(bcx.fcx);
1441 // If we don't care about the result, just make a
1442 // temporary stack slot
1443 let addr = match dest {
1446 let llresult = alloc_ty(bcx, ty, "temp");
1447 call_lifetime_start(bcx, llresult);
1452 // This scope holds intermediates that must be cleaned should
1453 // panic occur before the ADT as a whole is ready.
1454 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1457 // Issue 23112: The original logic appeared vulnerable to same
1458 // order-of-eval bug. But, SIMD values are tuple-structs;
1459 // i.e. functional record update (FRU) syntax is unavailable.
1461 // To be safe, double-check that we did not get here via FRU.
1462 assert!(optbase.is_none());
1464 // This is the constructor of a SIMD type, such types are
1465 // always primitive machine types and so do not have a
1466 // destructor or require any clean-up.
1467 let llty = type_of::type_of(bcx.ccx(), ty);
1469 // keep a vector as a register, and running through the field
1470 // `insertelement`ing them directly into that register
1471 // (i.e. avoid GEPi and `store`s to an alloca) .
1472 let mut vec_val = C_undef(llty);
1474 for &(i, ref e) in fields {
1475 let block_datum = trans(bcx, &**e);
1476 bcx = block_datum.bcx;
1477 let position = C_uint(bcx.ccx(), i);
1478 let value = block_datum.datum.to_llscalarish(bcx);
1479 vec_val = InsertElement(bcx, vec_val, value, position);
1481 Store(bcx, vec_val, addr);
1482 } else if let Some(base) = optbase {
1483 // Issue 23112: If there is a base, then order-of-eval
1484 // requires field expressions eval'ed before base expression.
1486 // First, trans field expressions to temporary scratch values.
1487 let scratch_vals: Vec<_> = fields.iter().map(|&(i, ref e)| {
1488 let datum = unpack_datum!(bcx, trans(bcx, &**e));
1492 debug_location.apply(bcx.fcx);
1494 // Second, trans the base to the dest.
1495 assert_eq!(discr, 0);
1497 match expr_kind(bcx.tcx(), &*base.expr) {
1498 ExprKind::RvalueDps | ExprKind::RvalueDatum if !bcx.fcx.type_needs_drop(ty) => {
1499 bcx = trans_into(bcx, &*base.expr, SaveIn(addr));
1501 ExprKind::RvalueStmt => {
1502 bcx.tcx().sess.bug("unexpected expr kind for struct base expr")
1505 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base"));
1506 for &(i, t) in &base.fields {
1507 let datum = base_datum.get_element(
1508 bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i));
1509 assert!(type_is_sized(bcx.tcx(), datum.ty));
1510 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1511 bcx = datum.store_to(bcx, dest);
1516 // Finally, move scratch field values into actual field locations
1517 for (i, datum) in scratch_vals {
1518 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1519 bcx = datum.store_to(bcx, dest);
1522 // No base means we can write all fields directly in place.
1523 for &(i, ref e) in fields {
1524 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1525 let e_ty = expr_ty_adjusted(bcx, &**e);
1526 bcx = trans_into(bcx, &**e, SaveIn(dest));
1527 let scope = cleanup::CustomScope(custom_cleanup_scope);
1528 fcx.schedule_lifetime_end(scope, dest);
1529 // FIXME: nonzeroing move should generalize to fields
1530 fcx.schedule_drop_mem(scope, dest, e_ty, None);
1534 adt::trans_set_discr(bcx, &*repr, addr, discr);
1536 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1538 // If we don't care about the result drop the temporary we made
1542 bcx = glue::drop_ty(bcx, addr, ty, debug_location);
1543 base::call_lifetime_end(bcx, addr);
1550 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1553 -> DatumBlock<'blk, 'tcx, Expr> {
1554 // must not be a string constant, that is a RvalueDpsExpr
1555 let _icx = push_ctxt("trans_immediate_lit");
1556 let ty = expr_ty(bcx, expr);
1557 let v = consts::const_lit(bcx.ccx(), expr, lit);
1558 immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1561 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1564 sub_expr: &hir::Expr)
1565 -> DatumBlock<'blk, 'tcx, Expr> {
1566 let ccx = bcx.ccx();
1568 let _icx = push_ctxt("trans_unary_datum");
1570 let method_call = MethodCall::expr(expr.id);
1572 // The only overloaded operator that is translated to a datum
1573 // is an overloaded deref, since it is always yields a `&T`.
1574 // Otherwise, we should be in the RvalueDpsExpr path.
1575 assert!(op == hir::UnDeref || !ccx.tcx().is_method_call(expr.id));
1577 let un_ty = expr_ty(bcx, expr);
1579 let debug_loc = expr.debug_loc();
1583 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1584 let llresult = Not(bcx, datum.to_llscalarish(bcx), debug_loc);
1585 immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1588 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1589 let val = datum.to_llscalarish(bcx);
1590 let (bcx, llneg) = {
1592 let result = FNeg(bcx, val, debug_loc);
1595 let is_signed = un_ty.is_signed();
1596 let result = Neg(bcx, val, debug_loc);
1597 let bcx = if bcx.ccx().check_overflow() && is_signed {
1598 let (llty, min) = base::llty_and_min_for_signed_ty(bcx, un_ty);
1599 let is_min = ICmp(bcx, llvm::IntEQ, val,
1600 C_integral(llty, min, true), debug_loc);
1601 with_cond(bcx, is_min, |bcx| {
1602 let msg = InternedString::new(
1603 "attempted to negate with overflow");
1604 controlflow::trans_fail(bcx, expr_info(expr), msg)
1612 immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1615 trans_uniq_expr(bcx, expr, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1618 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1619 deref_once(bcx, expr, datum, method_call)
1624 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1625 box_expr: &hir::Expr,
1627 contents: &hir::Expr,
1628 contents_ty: Ty<'tcx>)
1629 -> DatumBlock<'blk, 'tcx, Expr> {
1630 let _icx = push_ctxt("trans_uniq_expr");
1632 assert!(type_is_sized(bcx.tcx(), contents_ty));
1633 let llty = type_of::type_of(bcx.ccx(), contents_ty);
1634 let size = llsize_of(bcx.ccx(), llty);
1635 let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty));
1636 let llty_ptr = llty.ptr_to();
1637 let Result { bcx, val } = malloc_raw_dyn(bcx,
1642 box_expr.debug_loc());
1643 // Unique boxes do not allocate for zero-size types. The standard library
1644 // may assume that `free` is never called on the pointer returned for
1645 // `Box<ZeroSizeType>`.
1646 let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1647 trans_into(bcx, contents, SaveIn(val))
1649 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1650 fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1651 val, cleanup::HeapExchange, contents_ty);
1652 let bcx = trans_into(bcx, contents, SaveIn(val));
1653 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1656 immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1659 fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1660 lval: Datum<'tcx, Lvalue>)
1661 -> DatumBlock<'blk, 'tcx, Expr> {
1662 let dest_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), lval.ty);
1663 let scratch = rvalue_scratch_datum(bcx, dest_ty, "__fat_ptr");
1664 memcpy_ty(bcx, scratch.val, lval.val, scratch.ty);
1666 DatumBlock::new(bcx, scratch.to_expr_datum())
1669 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1671 subexpr: &hir::Expr)
1672 -> DatumBlock<'blk, 'tcx, Expr> {
1673 let _icx = push_ctxt("trans_addr_of");
1675 let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1676 if !type_is_sized(bcx.tcx(), sub_datum.ty) {
1677 // DST lvalue, close to a fat pointer
1678 ref_fat_ptr(bcx, sub_datum)
1680 // Sized value, ref to a thin pointer
1681 let ty = expr_ty(bcx, expr);
1682 immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1686 fn trans_fat_ptr_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1687 binop_expr: &hir::Expr,
1690 lhs: Datum<'tcx, Rvalue>,
1691 rhs: Datum<'tcx, Rvalue>)
1692 -> DatumBlock<'blk, 'tcx, Expr>
1694 let debug_loc = binop_expr.debug_loc();
1696 let lhs_addr = Load(bcx, GEPi(bcx, lhs.val, &[0, abi::FAT_PTR_ADDR]));
1697 let lhs_extra = Load(bcx, GEPi(bcx, lhs.val, &[0, abi::FAT_PTR_EXTRA]));
1699 let rhs_addr = Load(bcx, GEPi(bcx, rhs.val, &[0, abi::FAT_PTR_ADDR]));
1700 let rhs_extra = Load(bcx, GEPi(bcx, rhs.val, &[0, abi::FAT_PTR_EXTRA]));
1702 let val = match op.node {
1704 let addr_eq = ICmp(bcx, llvm::IntEQ, lhs_addr, rhs_addr, debug_loc);
1705 let extra_eq = ICmp(bcx, llvm::IntEQ, lhs_extra, rhs_extra, debug_loc);
1706 And(bcx, addr_eq, extra_eq, debug_loc)
1709 let addr_eq = ICmp(bcx, llvm::IntNE, lhs_addr, rhs_addr, debug_loc);
1710 let extra_eq = ICmp(bcx, llvm::IntNE, lhs_extra, rhs_extra, debug_loc);
1711 Or(bcx, addr_eq, extra_eq, debug_loc)
1713 hir::BiLe | hir::BiLt | hir::BiGe | hir::BiGt => {
1714 // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
1715 let (op, strict_op) = match op.node {
1716 hir::BiLt => (llvm::IntULT, llvm::IntULT),
1717 hir::BiLe => (llvm::IntULE, llvm::IntULT),
1718 hir::BiGt => (llvm::IntUGT, llvm::IntUGT),
1719 hir::BiGe => (llvm::IntUGE, llvm::IntUGT),
1723 let addr_eq = ICmp(bcx, llvm::IntEQ, lhs_addr, rhs_addr, debug_loc);
1724 let extra_op = ICmp(bcx, op, lhs_extra, rhs_extra, debug_loc);
1725 let addr_eq_extra_op = And(bcx, addr_eq, extra_op, debug_loc);
1727 let addr_strict = ICmp(bcx, strict_op, lhs_addr, rhs_addr, debug_loc);
1728 Or(bcx, addr_strict, addr_eq_extra_op, debug_loc)
1731 bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1735 immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1738 fn trans_scalar_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1739 binop_expr: &hir::Expr,
1742 lhs: Datum<'tcx, Rvalue>,
1743 rhs: Datum<'tcx, Rvalue>)
1744 -> DatumBlock<'blk, 'tcx, Expr>
1746 let _icx = push_ctxt("trans_scalar_binop");
1748 let tcx = bcx.tcx();
1750 assert!(!lhs_t.is_simd());
1751 let is_float = lhs_t.is_fp();
1752 let is_signed = lhs_t.is_signed();
1753 let info = expr_info(binop_expr);
1755 let binop_debug_loc = binop_expr.debug_loc();
1758 let lhs = lhs.to_llscalarish(bcx);
1759 let rhs = rhs.to_llscalarish(bcx);
1760 let val = match op.node {
1763 FAdd(bcx, lhs, rhs, binop_debug_loc)
1765 let (newbcx, res) = with_overflow_check(
1766 bcx, OverflowOp::Add, info, lhs_t, lhs, rhs, binop_debug_loc);
1773 FSub(bcx, lhs, rhs, binop_debug_loc)
1775 let (newbcx, res) = with_overflow_check(
1776 bcx, OverflowOp::Sub, info, lhs_t, lhs, rhs, binop_debug_loc);
1783 FMul(bcx, lhs, rhs, binop_debug_loc)
1785 let (newbcx, res) = with_overflow_check(
1786 bcx, OverflowOp::Mul, info, lhs_t, lhs, rhs, binop_debug_loc);
1793 FDiv(bcx, lhs, rhs, binop_debug_loc)
1795 // Only zero-check integers; fp /0 is NaN
1796 bcx = base::fail_if_zero_or_overflows(bcx,
1797 expr_info(binop_expr),
1803 SDiv(bcx, lhs, rhs, binop_debug_loc)
1805 UDiv(bcx, lhs, rhs, binop_debug_loc)
1811 // LLVM currently always lowers the `frem` instructions appropriate
1812 // library calls typically found in libm. Notably f64 gets wired up
1813 // to `fmod` and f32 gets wired up to `fmodf`. Inconveniently for
1814 // us, 32-bit MSVC does not actually have a `fmodf` symbol, it's
1815 // instead just an inline function in a header that goes up to a
1816 // f64, uses `fmod`, and then comes back down to a f32.
1818 // Although LLVM knows that `fmodf` doesn't exist on MSVC, it will
1819 // still unconditionally lower frem instructions over 32-bit floats
1820 // to a call to `fmodf`. To work around this we special case MSVC
1821 // 32-bit float rem instructions and instead do the call out to
1822 // `fmod` ourselves.
1824 // Note that this is currently duplicated with src/libcore/ops.rs
1825 // which does the same thing, and it would be nice to perhaps unify
1826 // these two implementations on day! Also note that we call `fmod`
1827 // for both 32 and 64-bit floats because if we emit any FRem
1828 // instruction at all then LLVM is capable of optimizing it into a
1829 // 32-bit FRem (which we're trying to avoid).
1830 let use_fmod = tcx.sess.target.target.options.is_like_msvc &&
1831 tcx.sess.target.target.arch == "x86";
1833 let f64t = Type::f64(bcx.ccx());
1834 let fty = Type::func(&[f64t, f64t], &f64t);
1835 let llfn = declare::declare_cfn(bcx.ccx(), "fmod", fty,
1837 if lhs_t == tcx.types.f32 {
1838 let lhs = FPExt(bcx, lhs, f64t);
1839 let rhs = FPExt(bcx, rhs, f64t);
1840 let res = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
1841 FPTrunc(bcx, res, Type::f32(bcx.ccx()))
1843 Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc)
1846 FRem(bcx, lhs, rhs, binop_debug_loc)
1849 // Only zero-check integers; fp %0 is NaN
1850 bcx = base::fail_if_zero_or_overflows(bcx,
1851 expr_info(binop_expr),
1852 op, lhs, rhs, lhs_t);
1854 SRem(bcx, lhs, rhs, binop_debug_loc)
1856 URem(bcx, lhs, rhs, binop_debug_loc)
1860 hir::BiBitOr => Or(bcx, lhs, rhs, binop_debug_loc),
1861 hir::BiBitAnd => And(bcx, lhs, rhs, binop_debug_loc),
1862 hir::BiBitXor => Xor(bcx, lhs, rhs, binop_debug_loc),
1864 let (newbcx, res) = with_overflow_check(
1865 bcx, OverflowOp::Shl, info, lhs_t, lhs, rhs, binop_debug_loc);
1870 let (newbcx, res) = with_overflow_check(
1871 bcx, OverflowOp::Shr, info, lhs_t, lhs, rhs, binop_debug_loc);
1875 hir::BiEq | hir::BiNe | hir::BiLt | hir::BiGe | hir::BiLe | hir::BiGt => {
1876 base::compare_scalar_types(bcx, lhs, rhs, lhs_t, op.node, binop_debug_loc)
1879 bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1883 immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1886 // refinement types would obviate the need for this
1887 enum lazy_binop_ty {
1892 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1893 binop_expr: &hir::Expr,
1897 -> DatumBlock<'blk, 'tcx, Expr> {
1898 let _icx = push_ctxt("trans_lazy_binop");
1899 let binop_ty = expr_ty(bcx, binop_expr);
1902 let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1903 let lhs = lhs.to_llscalarish(past_lhs);
1905 if past_lhs.unreachable.get() {
1906 return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1909 let join = fcx.new_id_block("join", binop_expr.id);
1910 let before_rhs = fcx.new_id_block("before_rhs", b.id);
1913 lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb, DebugLoc::None),
1914 lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb, DebugLoc::None)
1917 let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1918 let rhs = rhs.to_llscalarish(past_rhs);
1920 if past_rhs.unreachable.get() {
1921 return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1924 Br(past_rhs, join.llbb, DebugLoc::None);
1925 let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1926 &[past_lhs.llbb, past_rhs.llbb]);
1928 return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1931 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1936 -> DatumBlock<'blk, 'tcx, Expr> {
1937 let _icx = push_ctxt("trans_binary");
1938 let ccx = bcx.ccx();
1940 // if overloaded, would be RvalueDpsExpr
1941 assert!(!ccx.tcx().is_method_call(expr.id));
1945 trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1948 trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1952 let binop_ty = expr_ty(bcx, expr);
1954 let lhs = unpack_datum!(bcx, trans(bcx, lhs));
1955 let lhs = unpack_datum!(bcx, lhs.to_rvalue_datum(bcx, "binop_lhs"));
1956 debug!("trans_binary (expr {}): lhs={}",
1957 expr.id, lhs.to_string(ccx));
1958 let rhs = unpack_datum!(bcx, trans(bcx, rhs));
1959 let rhs = unpack_datum!(bcx, rhs.to_rvalue_datum(bcx, "binop_rhs"));
1960 debug!("trans_binary (expr {}): rhs={}",
1961 expr.id, rhs.to_string(ccx));
1963 if type_is_fat_ptr(ccx.tcx(), lhs.ty) {
1964 assert!(type_is_fat_ptr(ccx.tcx(), rhs.ty),
1965 "built-in binary operators on fat pointers are homogeneous");
1966 trans_fat_ptr_binop(bcx, expr, binop_ty, op, lhs, rhs)
1968 assert!(!type_is_fat_ptr(ccx.tcx(), rhs.ty),
1969 "built-in binary operators on fat pointers are homogeneous");
1970 trans_scalar_binop(bcx, expr, binop_ty, op, lhs, rhs)
1976 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1978 method_call: MethodCall,
1979 lhs: Datum<'tcx, Expr>,
1980 rhs: Option<(Datum<'tcx, Expr>, ast::NodeId)>,
1983 -> Result<'blk, 'tcx> {
1984 callee::trans_call_inner(bcx,
1986 |bcx, arg_cleanup_scope| {
1987 meth::trans_method_callee(bcx,
1992 callee::ArgOverloadedOp(lhs, rhs, autoref),
1996 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1998 callee: &'a hir::Expr,
1999 args: &'a [P<hir::Expr>],
2001 -> Block<'blk, 'tcx> {
2002 debug!("trans_overloaded_call {}", expr.id);
2003 let method_call = MethodCall::expr(expr.id);
2004 let mut all_args = vec!(callee);
2005 all_args.extend(args.iter().map(|e| &**e));
2007 callee::trans_call_inner(bcx,
2009 |bcx, arg_cleanup_scope| {
2010 meth::trans_method_callee(
2016 callee::ArgOverloadedCall(all_args),
2021 pub fn cast_is_noop<'tcx>(tcx: &ty::ctxt<'tcx>,
2026 if let Some(&CastKind::CoercionCast) = tcx.cast_kinds.borrow().get(&expr.id) {
2030 match (t_in.builtin_deref(true, ty::NoPreference),
2031 t_out.builtin_deref(true, ty::NoPreference)) {
2032 (Some(ty::TypeAndMut{ ty: t_in, .. }), Some(ty::TypeAndMut{ ty: t_out, .. })) => {
2036 // This condition isn't redundant with the check for CoercionCast:
2037 // different types can be substituted into the same type, and
2038 // == equality can be overconservative if there are regions.
2044 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2047 -> DatumBlock<'blk, 'tcx, Expr>
2049 use middle::ty::cast::CastTy::*;
2050 use middle::ty::cast::IntTy::*;
2052 fn int_cast(bcx: Block,
2059 let _icx = push_ctxt("int_cast");
2060 let srcsz = llsrctype.int_width();
2061 let dstsz = lldsttype.int_width();
2062 return if dstsz == srcsz {
2063 BitCast(bcx, llsrc, lldsttype)
2064 } else if srcsz > dstsz {
2065 TruncOrBitCast(bcx, llsrc, lldsttype)
2067 SExtOrBitCast(bcx, llsrc, lldsttype)
2069 ZExtOrBitCast(bcx, llsrc, lldsttype)
2073 fn float_cast(bcx: Block,
2079 let _icx = push_ctxt("float_cast");
2080 let srcsz = llsrctype.float_width();
2081 let dstsz = lldsttype.float_width();
2082 return if dstsz > srcsz {
2083 FPExt(bcx, llsrc, lldsttype)
2084 } else if srcsz > dstsz {
2085 FPTrunc(bcx, llsrc, lldsttype)
2089 let _icx = push_ctxt("trans_cast");
2091 let ccx = bcx.ccx();
2093 let t_in = expr_ty_adjusted(bcx, expr);
2094 let t_out = node_id_type(bcx, id);
2096 debug!("trans_cast({:?} as {:?})", t_in, t_out);
2097 let mut ll_t_in = type_of::arg_type_of(ccx, t_in);
2098 let ll_t_out = type_of::arg_type_of(ccx, t_out);
2099 // Convert the value to be cast into a ValueRef, either by-ref or
2100 // by-value as appropriate given its type:
2101 let mut datum = unpack_datum!(bcx, trans(bcx, expr));
2103 let datum_ty = monomorphize_type(bcx, datum.ty);
2105 if cast_is_noop(bcx.tcx(), expr, datum_ty, t_out) {
2107 return DatumBlock::new(bcx, datum);
2110 if type_is_fat_ptr(bcx.tcx(), t_in) {
2111 assert!(datum.kind.is_by_ref());
2112 if type_is_fat_ptr(bcx.tcx(), t_out) {
2113 return DatumBlock::new(bcx, Datum::new(
2114 PointerCast(bcx, datum.val, ll_t_out.ptr_to()),
2117 )).to_expr_datumblock();
2119 // Return the address
2120 return immediate_rvalue_bcx(bcx,
2122 Load(bcx, get_dataptr(bcx, datum.val)),
2124 t_out).to_expr_datumblock();
2128 let r_t_in = CastTy::from_ty(t_in).expect("bad input type for cast");
2129 let r_t_out = CastTy::from_ty(t_out).expect("bad output type for cast");
2131 let (llexpr, signed) = if let Int(CEnum) = r_t_in {
2132 let repr = adt::represent_type(ccx, t_in);
2133 let datum = unpack_datum!(
2134 bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
2135 let llexpr_ptr = datum.to_llref();
2136 let discr = adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
2137 ll_t_in = val_ty(discr);
2138 (discr, adt::is_discr_signed(&*repr))
2140 (datum.to_llscalarish(bcx), t_in.is_signed())
2143 let newval = match (r_t_in, r_t_out) {
2144 (Ptr(_), Ptr(_)) | (FnPtr, Ptr(_)) | (RPtr(_), Ptr(_)) => {
2145 PointerCast(bcx, llexpr, ll_t_out)
2147 (Ptr(_), Int(_)) | (FnPtr, Int(_)) => PtrToInt(bcx, llexpr, ll_t_out),
2148 (Int(_), Ptr(_)) => IntToPtr(bcx, llexpr, ll_t_out),
2150 (Int(_), Int(_)) => int_cast(bcx, ll_t_out, ll_t_in, llexpr, signed),
2151 (Float, Float) => float_cast(bcx, ll_t_out, ll_t_in, llexpr),
2152 (Int(_), Float) if signed => SIToFP(bcx, llexpr, ll_t_out),
2153 (Int(_), Float) => UIToFP(bcx, llexpr, ll_t_out),
2154 (Float, Int(I)) => FPToSI(bcx, llexpr, ll_t_out),
2155 (Float, Int(_)) => FPToUI(bcx, llexpr, ll_t_out),
2157 _ => ccx.sess().span_bug(expr.span,
2158 &format!("translating unsupported cast: \
2164 return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
2167 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2172 -> Block<'blk, 'tcx> {
2173 let _icx = push_ctxt("trans_assign_op");
2176 debug!("trans_assign_op(expr={:?})", expr);
2178 // User-defined operator methods cannot be used with `+=` etc right now
2179 assert!(!bcx.tcx().is_method_call(expr.id));
2181 // Evaluate LHS (destination), which should be an lvalue
2182 let dst = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2183 assert!(!bcx.fcx.type_needs_drop(dst.ty));
2184 let lhs = load_ty(bcx, dst.val, dst.ty);
2185 let lhs = immediate_rvalue(lhs, dst.ty);
2187 // Evaluate RHS - FIXME(#28160) this sucks
2188 let rhs = unpack_datum!(bcx, trans(bcx, &*src));
2189 let rhs = unpack_datum!(bcx, rhs.to_rvalue_datum(bcx, "assign_op_rhs"));
2191 // Perform computation and store the result
2192 let result_datum = unpack_datum!(
2193 bcx, trans_scalar_binop(bcx, expr, dst.ty, op, lhs, rhs));
2194 return result_datum.store_to(bcx, dst.val);
2197 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2198 datum: Datum<'tcx, Expr>,
2200 -> DatumBlock<'blk, 'tcx, Expr> {
2203 // Ensure cleanup of `datum` if not already scheduled and obtain
2204 // a "by ref" pointer.
2205 let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2207 // Compute final type. Note that we are loose with the region and
2208 // mutability, since those things don't matter in trans.
2209 let referent_ty = lv_datum.ty;
2210 let ptr_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), referent_ty);
2213 let llref = lv_datum.to_llref();
2215 // Construct the resulting datum, using what was the "by ref"
2216 // ValueRef of type `referent_ty` to be the "by value" ValueRef
2217 // of type `&referent_ty`.
2218 // Pointers to DST types are non-immediate, and therefore still use ByRef.
2219 let kind = if type_is_sized(bcx.tcx(), referent_ty) { ByValue } else { ByRef };
2220 DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(kind))))
2223 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2225 datum: Datum<'tcx, Expr>,
2227 -> DatumBlock<'blk, 'tcx, Expr> {
2229 let mut datum = datum;
2231 let method_call = MethodCall::autoderef(expr.id, i as u32);
2232 datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2234 DatumBlock { bcx: bcx, datum: datum }
2237 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2239 datum: Datum<'tcx, Expr>,
2240 method_call: MethodCall)
2241 -> DatumBlock<'blk, 'tcx, Expr> {
2242 let ccx = bcx.ccx();
2244 debug!("deref_once(expr={:?}, datum={}, method_call={:?})",
2246 datum.to_string(ccx),
2251 // Check for overloaded deref.
2252 let method_ty = ccx.tcx()
2256 .get(&method_call).map(|method| method.ty);
2258 let datum = match method_ty {
2259 Some(method_ty) => {
2260 let method_ty = monomorphize_type(bcx, method_ty);
2262 // Overloaded. Evaluate `trans_overloaded_op`, which will
2263 // invoke the user's deref() method, which basically
2264 // converts from the `Smaht<T>` pointer that we have into
2265 // a `&T` pointer. We can then proceed down the normal
2266 // path (below) to dereference that `&T`.
2267 let datum = if method_call.autoderef == 0 {
2270 // Always perform an AutoPtr when applying an overloaded auto-deref
2271 unpack_datum!(bcx, auto_ref(bcx, datum, expr))
2274 let ref_ty = // invoked methods have their LB regions instantiated
2275 ccx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
2276 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2278 unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2279 datum, None, Some(SaveIn(scratch.val)),
2281 scratch.to_expr_datum()
2284 // Not overloaded. We already have a pointer we know how to deref.
2289 let r = match datum.ty.sty {
2290 ty::TyBox(content_ty) => {
2291 // Make sure we have an lvalue datum here to get the
2292 // proper cleanups scheduled
2293 let datum = unpack_datum!(
2294 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2296 if type_is_sized(bcx.tcx(), content_ty) {
2297 let ptr = load_ty(bcx, datum.val, datum.ty);
2298 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(datum.kind)))
2300 // A fat pointer and a DST lvalue have the same representation
2301 // just different types. Since there is no temporary for `*e`
2302 // here (because it is unsized), we cannot emulate the sized
2303 // object code path for running drop glue and free. Instead,
2304 // we schedule cleanup for `e`, turning it into an lvalue.
2306 let lval = Lvalue::new("expr::deref_once ty_uniq");
2307 let datum = Datum::new(datum.val, content_ty, LvalueExpr(lval));
2308 DatumBlock::new(bcx, datum)
2312 ty::TyRawPtr(ty::TypeAndMut { ty: content_ty, .. }) |
2313 ty::TyRef(_, ty::TypeAndMut { ty: content_ty, .. }) => {
2314 let lval = Lvalue::new("expr::deref_once ptr");
2315 if type_is_sized(bcx.tcx(), content_ty) {
2316 let ptr = datum.to_llscalarish(bcx);
2318 // Always generate an lvalue datum, even if datum.mode is
2319 // an rvalue. This is because datum.mode is only an
2320 // rvalue for non-owning pointers like &T or *T, in which
2321 // case cleanup *is* scheduled elsewhere, by the true
2322 // owner (or, in the case of *T, by the user).
2323 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(lval)))
2325 // A fat pointer and a DST lvalue have the same representation
2326 // just different types.
2327 DatumBlock::new(bcx, Datum::new(datum.val, content_ty, LvalueExpr(lval)))
2332 bcx.tcx().sess.span_bug(
2334 &format!("deref invoked on expr of invalid type {:?}",
2339 debug!("deref_once(expr={}, method_call={:?}, result={})",
2340 expr.id, method_call, r.datum.to_string(ccx));
2355 fn codegen_strategy(&self) -> OverflowCodegen {
2356 use self::OverflowCodegen::{ViaIntrinsic, ViaInputCheck};
2358 OverflowOp::Add => ViaIntrinsic(OverflowOpViaIntrinsic::Add),
2359 OverflowOp::Sub => ViaIntrinsic(OverflowOpViaIntrinsic::Sub),
2360 OverflowOp::Mul => ViaIntrinsic(OverflowOpViaIntrinsic::Mul),
2362 OverflowOp::Shl => ViaInputCheck(OverflowOpViaInputCheck::Shl),
2363 OverflowOp::Shr => ViaInputCheck(OverflowOpViaInputCheck::Shr),
2368 enum OverflowCodegen {
2369 ViaIntrinsic(OverflowOpViaIntrinsic),
2370 ViaInputCheck(OverflowOpViaInputCheck),
2373 enum OverflowOpViaInputCheck { Shl, Shr, }
2376 enum OverflowOpViaIntrinsic { Add, Sub, Mul, }
2378 impl OverflowOpViaIntrinsic {
2379 fn to_intrinsic<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>, lhs_ty: Ty) -> ValueRef {
2380 let name = self.to_intrinsic_name(bcx.tcx(), lhs_ty);
2381 bcx.ccx().get_intrinsic(&name)
2383 fn to_intrinsic_name(&self, tcx: &ty::ctxt, ty: Ty) -> &'static str {
2384 use rustc_front::hir::IntTy::*;
2385 use rustc_front::hir::UintTy::*;
2386 use middle::ty::{TyInt, TyUint};
2388 let new_sty = match ty.sty {
2389 TyInt(TyIs) => match &tcx.sess.target.target.target_pointer_width[..] {
2390 "32" => TyInt(TyI32),
2391 "64" => TyInt(TyI64),
2392 _ => panic!("unsupported target word size")
2394 TyUint(TyUs) => match &tcx.sess.target.target.target_pointer_width[..] {
2395 "32" => TyUint(TyU32),
2396 "64" => TyUint(TyU64),
2397 _ => panic!("unsupported target word size")
2399 ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
2400 _ => panic!("tried to get overflow intrinsic for {:?} applied to non-int type",
2405 OverflowOpViaIntrinsic::Add => match new_sty {
2406 TyInt(TyI8) => "llvm.sadd.with.overflow.i8",
2407 TyInt(TyI16) => "llvm.sadd.with.overflow.i16",
2408 TyInt(TyI32) => "llvm.sadd.with.overflow.i32",
2409 TyInt(TyI64) => "llvm.sadd.with.overflow.i64",
2411 TyUint(TyU8) => "llvm.uadd.with.overflow.i8",
2412 TyUint(TyU16) => "llvm.uadd.with.overflow.i16",
2413 TyUint(TyU32) => "llvm.uadd.with.overflow.i32",
2414 TyUint(TyU64) => "llvm.uadd.with.overflow.i64",
2416 _ => unreachable!(),
2418 OverflowOpViaIntrinsic::Sub => match new_sty {
2419 TyInt(TyI8) => "llvm.ssub.with.overflow.i8",
2420 TyInt(TyI16) => "llvm.ssub.with.overflow.i16",
2421 TyInt(TyI32) => "llvm.ssub.with.overflow.i32",
2422 TyInt(TyI64) => "llvm.ssub.with.overflow.i64",
2424 TyUint(TyU8) => "llvm.usub.with.overflow.i8",
2425 TyUint(TyU16) => "llvm.usub.with.overflow.i16",
2426 TyUint(TyU32) => "llvm.usub.with.overflow.i32",
2427 TyUint(TyU64) => "llvm.usub.with.overflow.i64",
2429 _ => unreachable!(),
2431 OverflowOpViaIntrinsic::Mul => match new_sty {
2432 TyInt(TyI8) => "llvm.smul.with.overflow.i8",
2433 TyInt(TyI16) => "llvm.smul.with.overflow.i16",
2434 TyInt(TyI32) => "llvm.smul.with.overflow.i32",
2435 TyInt(TyI64) => "llvm.smul.with.overflow.i64",
2437 TyUint(TyU8) => "llvm.umul.with.overflow.i8",
2438 TyUint(TyU16) => "llvm.umul.with.overflow.i16",
2439 TyUint(TyU32) => "llvm.umul.with.overflow.i32",
2440 TyUint(TyU64) => "llvm.umul.with.overflow.i64",
2442 _ => unreachable!(),
2447 fn build_intrinsic_call<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>,
2448 info: NodeIdAndSpan,
2449 lhs_t: Ty<'tcx>, lhs: ValueRef,
2451 binop_debug_loc: DebugLoc)
2452 -> (Block<'blk, 'tcx>, ValueRef) {
2453 let llfn = self.to_intrinsic(bcx, lhs_t);
2455 let val = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
2456 let result = ExtractValue(bcx, val, 0); // iN operation result
2457 let overflow = ExtractValue(bcx, val, 1); // i1 "did it overflow?"
2459 let cond = ICmp(bcx, llvm::IntEQ, overflow, C_integral(Type::i1(bcx.ccx()), 1, false),
2462 let expect = bcx.ccx().get_intrinsic(&"llvm.expect.i1");
2463 Call(bcx, expect, &[cond, C_integral(Type::i1(bcx.ccx()), 0, false)],
2464 None, binop_debug_loc);
2467 base::with_cond(bcx, cond, |bcx|
2468 controlflow::trans_fail(bcx, info,
2469 InternedString::new("arithmetic operation overflowed")));
2475 impl OverflowOpViaInputCheck {
2476 fn build_with_input_check<'blk, 'tcx>(&self,
2477 bcx: Block<'blk, 'tcx>,
2478 info: NodeIdAndSpan,
2482 binop_debug_loc: DebugLoc)
2483 -> (Block<'blk, 'tcx>, ValueRef)
2485 let lhs_llty = val_ty(lhs);
2486 let rhs_llty = val_ty(rhs);
2488 // Panic if any bits are set outside of bits that we always
2491 // Note that the mask's value is derived from the LHS type
2492 // (since that is where the 32/64 distinction is relevant) but
2493 // the mask's type must match the RHS type (since they will
2494 // both be fed into a and-binop)
2495 let invert_mask = shift_mask_val(bcx, lhs_llty, rhs_llty, true);
2497 let outer_bits = And(bcx, rhs, invert_mask, binop_debug_loc);
2498 let cond = build_nonzero_check(bcx, outer_bits, binop_debug_loc);
2499 let result = match *self {
2500 OverflowOpViaInputCheck::Shl =>
2501 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2502 OverflowOpViaInputCheck::Shr =>
2503 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2506 base::with_cond(bcx, cond, |bcx|
2507 controlflow::trans_fail(bcx, info,
2508 InternedString::new("shift operation overflowed")));
2514 fn shift_mask_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2517 invert: bool) -> ValueRef {
2518 let kind = llty.kind();
2520 TypeKind::Integer => {
2521 // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
2522 let val = llty.int_width() - 1;
2524 C_integral(mask_llty, !val, true)
2526 C_integral(mask_llty, val, false)
2529 TypeKind::Vector => {
2530 let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
2531 VectorSplat(bcx, mask_llty.vector_length(), mask)
2533 _ => panic!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
2537 // Check if an integer or vector contains a nonzero element.
2538 fn build_nonzero_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2540 binop_debug_loc: DebugLoc) -> ValueRef {
2541 let llty = val_ty(value);
2542 let kind = llty.kind();
2544 TypeKind::Integer => ICmp(bcx, llvm::IntNE, value, C_null(llty), binop_debug_loc),
2545 TypeKind::Vector => {
2546 // Check if any elements of the vector are nonzero by treating
2547 // it as a wide integer and checking if the integer is nonzero.
2548 let width = llty.vector_length() as u64 * llty.element_type().int_width();
2549 let int_value = BitCast(bcx, value, Type::ix(bcx.ccx(), width));
2550 build_nonzero_check(bcx, int_value, binop_debug_loc)
2552 _ => panic!("build_nonzero_check: expected Integer or Vector, found {:?}", kind),
2556 // To avoid UB from LLVM, these two functions mask RHS with an
2557 // appropriate mask unconditionally (i.e. the fallback behavior for
2558 // all shifts). For 32- and 64-bit types, this matches the semantics
2559 // of Java. (See related discussion on #1877 and #10183.)
2561 fn build_unchecked_lshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2564 binop_debug_loc: DebugLoc) -> ValueRef {
2565 let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShl, lhs, rhs);
2566 // #1877, #10183: Ensure that input is always valid
2567 let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2568 Shl(bcx, lhs, rhs, binop_debug_loc)
2571 fn build_unchecked_rshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2575 binop_debug_loc: DebugLoc) -> ValueRef {
2576 let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShr, lhs, rhs);
2577 // #1877, #10183: Ensure that input is always valid
2578 let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2579 let is_signed = lhs_t.is_signed();
2581 AShr(bcx, lhs, rhs, binop_debug_loc)
2583 LShr(bcx, lhs, rhs, binop_debug_loc)
2587 fn shift_mask_rhs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2589 debug_loc: DebugLoc) -> ValueRef {
2590 let rhs_llty = val_ty(rhs);
2591 And(bcx, rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false), debug_loc)
2594 fn with_overflow_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, oop: OverflowOp, info: NodeIdAndSpan,
2595 lhs_t: Ty<'tcx>, lhs: ValueRef,
2597 binop_debug_loc: DebugLoc)
2598 -> (Block<'blk, 'tcx>, ValueRef) {
2599 if bcx.unreachable.get() { return (bcx, _Undef(lhs)); }
2600 if bcx.ccx().check_overflow() {
2602 match oop.codegen_strategy() {
2603 OverflowCodegen::ViaIntrinsic(oop) =>
2604 oop.build_intrinsic_call(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2605 OverflowCodegen::ViaInputCheck(oop) =>
2606 oop.build_with_input_check(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2609 let res = match oop {
2610 OverflowOp::Add => Add(bcx, lhs, rhs, binop_debug_loc),
2611 OverflowOp::Sub => Sub(bcx, lhs, rhs, binop_debug_loc),
2612 OverflowOp::Mul => Mul(bcx, lhs, rhs, binop_debug_loc),
2615 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2617 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2623 /// We categorize expressions into three kinds. The distinction between
2624 /// lvalue/rvalue is fundamental to the language. The distinction between the
2625 /// two kinds of rvalues is an artifact of trans which reflects how we will
2626 /// generate code for that kind of expression. See trans/expr.rs for more
2628 #[derive(Copy, Clone)]
2636 fn expr_kind(tcx: &ty::ctxt, expr: &hir::Expr) -> ExprKind {
2637 if tcx.is_method_call(expr.id) {
2638 // Overloaded operations are generally calls, and hence they are
2639 // generated via DPS, but there are a few exceptions:
2640 return match expr.node {
2641 // `a += b` has a unit result.
2642 hir::ExprAssignOp(..) => ExprKind::RvalueStmt,
2644 // the deref method invoked for `*a` always yields an `&T`
2645 hir::ExprUnary(hir::UnDeref, _) => ExprKind::Lvalue,
2647 // the index method invoked for `a[i]` always yields an `&T`
2648 hir::ExprIndex(..) => ExprKind::Lvalue,
2650 // in the general case, result could be any type, use DPS
2651 _ => ExprKind::RvalueDps
2656 hir::ExprPath(..) => {
2657 match tcx.resolve_expr(expr) {
2658 def::DefStruct(_) | def::DefVariant(..) => {
2659 if let ty::TyBareFn(..) = tcx.node_id_to_type(expr.id).sty {
2661 ExprKind::RvalueDatum
2667 // Special case: A unit like struct's constructor must be called without () at the
2668 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
2669 // of unit structs this is should not be interpreted as function pointer but as
2670 // call to the constructor.
2671 def::DefFn(_, true) => ExprKind::RvalueDps,
2673 // Fn pointers are just scalar values.
2674 def::DefFn(..) | def::DefMethod(..) => ExprKind::RvalueDatum,
2676 // Note: there is actually a good case to be made that
2677 // DefArg's, particularly those of immediate type, ought to
2678 // considered rvalues.
2679 def::DefStatic(..) |
2681 def::DefLocal(..) => ExprKind::Lvalue,
2684 def::DefAssociatedConst(..) => ExprKind::RvalueDatum,
2689 &format!("uncategorized def for expr {}: {:?}",
2696 hir::ExprUnary(hir::UnDeref, _) |
2697 hir::ExprField(..) |
2698 hir::ExprTupField(..) |
2699 hir::ExprIndex(..) => {
2704 hir::ExprMethodCall(..) |
2705 hir::ExprStruct(..) |
2706 hir::ExprRange(..) |
2709 hir::ExprMatch(..) |
2710 hir::ExprClosure(..) |
2711 hir::ExprBlock(..) |
2712 hir::ExprRepeat(..) |
2713 hir::ExprVec(..) => {
2717 hir::ExprLit(ref lit) if rustc_front::util::lit_is_str(&**lit) => {
2721 hir::ExprBreak(..) |
2722 hir::ExprAgain(..) |
2724 hir::ExprWhile(..) |
2726 hir::ExprAssign(..) |
2727 hir::ExprInlineAsm(..) |
2728 hir::ExprAssignOp(..) => {
2729 ExprKind::RvalueStmt
2732 hir::ExprLit(_) | // Note: LitStr is carved out above
2733 hir::ExprUnary(..) |
2734 hir::ExprBox(None, _) |
2735 hir::ExprAddrOf(..) |
2736 hir::ExprBinary(..) |
2737 hir::ExprCast(..) => {
2738 ExprKind::RvalueDatum
2741 hir::ExprBox(Some(ref place), _) => {
2742 // Special case `Box<T>` for now:
2743 let def_id = match tcx.def_map.borrow().get(&place.id) {
2744 Some(def) => def.def_id(),
2745 None => panic!("no def for place"),
2747 if tcx.lang_items.exchange_heap() == Some(def_id) {
2748 ExprKind::RvalueDatum
2754 hir::ExprParen(ref e) => expr_kind(tcx, &**e),