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::cast::{CastKind, CastTy};
75 use middle::ty::{AdjustDerefRef, AdjustReifyFnPointer, AdjustUnsafeFnPointer};
76 use middle::ty::{self, Ty};
77 use middle::ty::MethodCall;
78 use util::common::indenter;
79 use trans::machine::{llsize_of, llsize_of_alloc};
80 use trans::type_::Type;
82 use syntax::{ast, ast_util, codemap};
83 use syntax::parse::token::InternedString;
85 use syntax::parse::token;
90 // These are passed around by the code generating functions to track the
91 // destination of a computation's value.
93 #[derive(Copy, Clone, PartialEq)]
100 pub fn to_string(&self, ccx: &CrateContext) -> String {
102 SaveIn(v) => format!("SaveIn({})", ccx.tn().val_to_string(v)),
103 Ignore => "Ignore".to_string()
108 /// This function is equivalent to `trans(bcx, expr).store_to_dest(dest)` but it may generate
109 /// better optimized LLVM code.
110 pub fn trans_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
113 -> Block<'blk, 'tcx> {
116 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
118 if bcx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
119 // use trans, which may be less efficient but
120 // which will perform the adjustments:
121 let datum = unpack_datum!(bcx, trans(bcx, expr));
122 return datum.store_to_dest(bcx, dest, expr.id);
125 let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
126 if !qualif.intersects(
127 check_const::ConstQualif::NOT_CONST |
128 check_const::ConstQualif::NEEDS_DROP
130 if !qualif.intersects(check_const::ConstQualif::PREFER_IN_PLACE) {
131 if let SaveIn(lldest) = dest {
132 let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
133 bcx.fcx.param_substs);
134 // Cast pointer to destination, because constants
135 // have different types.
136 let lldest = PointerCast(bcx, lldest, val_ty(global));
137 memcpy_ty(bcx, lldest, global, expr_ty_adjusted(bcx, expr));
140 // Even if we don't have a value to emit, and the expression
141 // doesn't have any side-effects, we still have to translate the
142 // body of any closures.
143 // FIXME: Find a better way of handling this case.
145 // The only way we're going to see a `const` at this point is if
146 // it prefers in-place instantiation, likely because it contains
147 // `[x; N]` somewhere within.
149 ast::ExprPath(..) => {
150 match bcx.def(expr.id) {
151 def::DefConst(did) => {
152 let const_expr = consts::get_const_expr(bcx.ccx(), did, expr);
153 // Temporarily get cleanup scopes out of the way,
154 // as they require sub-expressions to be contained
155 // inside the current AST scope.
156 // These should record no cleanups anyways, `const`
157 // can't have destructors.
158 let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
160 // Lock emitted debug locations to the location of
161 // the constant reference expression.
162 debuginfo::with_source_location_override(bcx.fcx,
165 bcx = trans_into(bcx, const_expr, dest)
167 let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
169 assert!(scopes.is_empty());
180 debug!("trans_into() expr={:?}", expr);
182 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
186 bcx.fcx.push_ast_cleanup_scope(cleanup_debug_loc);
188 let kind = expr_kind(bcx.tcx(), expr);
190 ExprKind::Lvalue | ExprKind::RvalueDatum => {
191 trans_unadjusted(bcx, expr).store_to_dest(dest, expr.id)
193 ExprKind::RvalueDps => {
194 trans_rvalue_dps_unadjusted(bcx, expr, dest)
196 ExprKind::RvalueStmt => {
197 trans_rvalue_stmt_unadjusted(bcx, expr)
201 bcx.fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id)
204 /// Translates an expression, returning a datum (and new block) encapsulating the result. When
205 /// possible, it is preferred to use `trans_into`, as that may avoid creating a temporary on the
207 pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
209 -> DatumBlock<'blk, 'tcx, Expr> {
210 debug!("trans(expr={:?})", expr);
214 let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
215 let adjusted_global = !qualif.intersects(check_const::ConstQualif::NON_STATIC_BORROWS);
216 let global = if !qualif.intersects(
217 check_const::ConstQualif::NOT_CONST |
218 check_const::ConstQualif::NEEDS_DROP
220 let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
221 bcx.fcx.param_substs);
223 if qualif.intersects(check_const::ConstQualif::HAS_STATIC_BORROWS) {
224 // Is borrowed as 'static, must return lvalue.
226 // Cast pointer to global, because constants have different types.
227 let const_ty = expr_ty_adjusted(bcx, expr);
228 let llty = type_of::type_of(bcx.ccx(), const_ty);
229 let global = PointerCast(bcx, global, llty.ptr_to());
230 let datum = Datum::new(global, const_ty, Lvalue::new("expr::trans"));
231 return DatumBlock::new(bcx, datum.to_expr_datum());
234 // Otherwise, keep around and perform adjustments, if needed.
235 let const_ty = if adjusted_global {
236 expr_ty_adjusted(bcx, expr)
241 // This could use a better heuristic.
242 Some(if type_is_immediate(bcx.ccx(), const_ty) {
243 // Cast pointer to global, because constants have different types.
244 let llty = type_of::type_of(bcx.ccx(), const_ty);
245 let global = PointerCast(bcx, global, llty.ptr_to());
246 // Maybe just get the value directly, instead of loading it?
247 immediate_rvalue(load_ty(bcx, global, const_ty), const_ty)
249 let scratch = alloc_ty(bcx, const_ty, "const");
250 call_lifetime_start(bcx, scratch);
251 let lldest = if !const_ty.is_structural() {
252 // Cast pointer to slot, because constants have different types.
253 PointerCast(bcx, scratch, val_ty(global))
255 // In this case, memcpy_ty calls llvm.memcpy after casting both
256 // source and destination to i8*, so we don't need any casts.
259 memcpy_ty(bcx, lldest, global, const_ty);
260 Datum::new(scratch, const_ty, Rvalue::new(ByRef))
266 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
270 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
271 let datum = match global {
272 Some(rvalue) => rvalue.to_expr_datum(),
273 None => unpack_datum!(bcx, trans_unadjusted(bcx, expr))
275 let datum = if adjusted_global {
276 datum // trans::consts already performed adjustments.
278 unpack_datum!(bcx, apply_adjustments(bcx, expr, datum))
280 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id);
281 return DatumBlock::new(bcx, datum);
284 pub fn get_meta(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
285 StructGEP(bcx, fat_ptr, abi::FAT_PTR_EXTRA)
288 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
289 StructGEP(bcx, fat_ptr, abi::FAT_PTR_ADDR)
292 pub fn copy_fat_ptr(bcx: Block, src_ptr: ValueRef, dst_ptr: ValueRef) {
293 Store(bcx, Load(bcx, get_dataptr(bcx, src_ptr)), get_dataptr(bcx, dst_ptr));
294 Store(bcx, Load(bcx, get_meta(bcx, src_ptr)), get_meta(bcx, dst_ptr));
297 /// Retrieve the information we are losing (making dynamic) in an unsizing
300 /// The `old_info` argument is a bit funny. It is intended for use
301 /// in an upcast, where the new vtable for an object will be drived
302 /// from the old one.
303 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
306 old_info: Option<ValueRef>,
307 param_substs: &'tcx Substs<'tcx>)
309 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
310 match (&source.sty, &target.sty) {
311 (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
312 (&ty::TyTrait(_), &ty::TyTrait(_)) => {
313 // For now, upcasts are limited to changes in marker
314 // traits, and hence never actually require an actual
315 // change to the vtable.
316 old_info.expect("unsized_info: missing old info for trait upcast")
318 (_, &ty::TyTrait(box ty::TraitTy { ref principal, .. })) => {
319 // Note that we preserve binding levels here:
320 let substs = principal.0.substs.with_self_ty(source).erase_regions();
321 let substs = ccx.tcx().mk_substs(substs);
322 let trait_ref = ty::Binder(ty::TraitRef { def_id: principal.def_id(),
324 consts::ptrcast(meth::get_vtable(ccx, trait_ref, param_substs),
325 Type::vtable_ptr(ccx))
327 _ => ccx.sess().bug(&format!("unsized_info: invalid unsizing {:?} -> {:?}",
333 /// Helper for trans that apply adjustments from `expr` to `datum`, which should be the unadjusted
334 /// translation of `expr`.
335 fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
337 datum: Datum<'tcx, Expr>)
338 -> DatumBlock<'blk, 'tcx, Expr>
341 let mut datum = datum;
342 let adjustment = match bcx.tcx().tables.borrow().adjustments.get(&expr.id).cloned() {
344 return DatumBlock::new(bcx, datum);
348 debug!("unadjusted datum for expr {:?}: {} adjustment={:?}",
350 datum.to_string(bcx.ccx()),
353 AdjustReifyFnPointer => {
354 // FIXME(#19925) once fn item types are
355 // zero-sized, we'll need to do something here
357 AdjustUnsafeFnPointer => {
358 // purely a type-level thing
360 AdjustDerefRef(ref adj) => {
361 let skip_reborrows = if adj.autoderefs == 1 && adj.autoref.is_some() {
362 // We are a bit paranoid about adjustments and thus might have a re-
363 // borrow here which merely derefs and then refs again (it might have
364 // a different region or mutability, but we don't care here).
366 // Don't skip a conversion from Box<T> to &T, etc.
368 if bcx.tcx().is_overloaded_autoderef(expr.id, 0) {
369 // Don't skip an overloaded deref.
381 if adj.autoderefs > skip_reborrows {
383 let lval = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "auto_deref", expr.id));
384 datum = unpack_datum!(bcx, deref_multiple(bcx, expr,
385 lval.to_expr_datum(),
386 adj.autoderefs - skip_reborrows));
389 // (You might think there is a more elegant way to do this than a
390 // skip_reborrows bool, but then you remember that the borrow checker exists).
391 if skip_reborrows == 0 && adj.autoref.is_some() {
392 datum = unpack_datum!(bcx, auto_ref(bcx, datum, expr));
395 if let Some(target) = adj.unsize {
396 // We do not arrange cleanup ourselves; if we already are an
397 // L-value, then cleanup will have already been scheduled (and
398 // the `datum.to_rvalue_datum` call below will emit code to zero
399 // the drop flag when moving out of the L-value). If we are an
400 // R-value, then we do not need to schedule cleanup.
401 let source_datum = unpack_datum!(bcx,
402 datum.to_rvalue_datum(bcx, "__coerce_source"));
404 let target = bcx.monomorphize(&target);
406 let scratch = alloc_ty(bcx, target, "__coerce_target");
407 call_lifetime_start(bcx, scratch);
408 let target_datum = Datum::new(scratch, target,
410 bcx = coerce_unsized(bcx, expr.span, source_datum, target_datum);
411 datum = Datum::new(scratch, target,
412 RvalueExpr(Rvalue::new(ByRef)));
416 debug!("after adjustments, datum={}", datum.to_string(bcx.ccx()));
417 DatumBlock::new(bcx, datum)
420 fn coerce_unsized<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
422 source: Datum<'tcx, Rvalue>,
423 target: Datum<'tcx, Rvalue>)
424 -> Block<'blk, 'tcx> {
426 debug!("coerce_unsized({} -> {})",
427 source.to_string(bcx.ccx()),
428 target.to_string(bcx.ccx()));
430 match (&source.ty.sty, &target.ty.sty) {
431 (&ty::TyBox(a), &ty::TyBox(b)) |
432 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
433 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
434 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
435 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
436 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
437 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
438 let (inner_source, inner_target) = (a, b);
440 let (base, old_info) = if !type_is_sized(bcx.tcx(), inner_source) {
441 // Normally, the source is a thin pointer and we are
442 // adding extra info to make a fat pointer. The exception
443 // is when we are upcasting an existing object fat pointer
444 // to use a different vtable. In that case, we want to
445 // load out the original data pointer so we can repackage
447 (Load(bcx, get_dataptr(bcx, source.val)),
448 Some(Load(bcx, get_meta(bcx, source.val))))
450 let val = if source.kind.is_by_ref() {
451 load_ty(bcx, source.val, source.ty)
458 let info = unsized_info(bcx.ccx(), inner_source, inner_target,
459 old_info, bcx.fcx.param_substs);
461 // Compute the base pointer. This doesn't change the pointer value,
462 // but merely its type.
463 let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), inner_target).ptr_to();
464 let base = PointerCast(bcx, base, ptr_ty);
466 Store(bcx, base, get_dataptr(bcx, target.val));
467 Store(bcx, info, get_meta(bcx, target.val));
470 // This can be extended to enums and tuples in the future.
471 // (&ty::TyEnum(def_id_a, _), &ty::TyEnum(def_id_b, _)) |
472 (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
473 assert_eq!(def_id_a, def_id_b);
475 // The target is already by-ref because it's to be written to.
476 let source = unpack_datum!(bcx, source.to_ref_datum(bcx));
477 assert!(target.kind.is_by_ref());
479 let trait_substs = Substs::erased(VecPerParamSpace::new(vec![target.ty],
482 let trait_ref = ty::Binder(ty::TraitRef {
483 def_id: langcall(bcx, Some(span), "coercion",
484 CoerceUnsizedTraitLangItem),
485 substs: bcx.tcx().mk_substs(trait_substs)
488 let kind = match fulfill_obligation(bcx.ccx(), span, trait_ref) {
489 traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
490 bcx.tcx().custom_coerce_unsized_kind(impl_def_id)
493 bcx.sess().span_bug(span, &format!("invalid CoerceUnsized vtable: {:?}",
498 let repr_source = adt::represent_type(bcx.ccx(), source.ty);
499 let src_fields = match &*repr_source {
500 &adt::Repr::Univariant(ref s, _) => &s.fields,
501 _ => bcx.sess().span_bug(span,
502 &format!("Non univariant struct? (repr_source: {:?})",
505 let repr_target = adt::represent_type(bcx.ccx(), target.ty);
506 let target_fields = match &*repr_target {
507 &adt::Repr::Univariant(ref s, _) => &s.fields,
508 _ => bcx.sess().span_bug(span,
509 &format!("Non univariant struct? (repr_target: {:?})",
513 let coerce_index = match kind {
514 ty::CustomCoerceUnsized::Struct(i) => i
516 assert!(coerce_index < src_fields.len() && src_fields.len() == target_fields.len());
518 let iter = src_fields.iter().zip(target_fields).enumerate();
519 for (i, (src_ty, target_ty)) in iter {
520 let ll_source = adt::trans_field_ptr(bcx, &repr_source, source.val, 0, i);
521 let ll_target = adt::trans_field_ptr(bcx, &repr_target, target.val, 0, i);
523 // If this is the field we need to coerce, recurse on it.
524 if i == coerce_index {
525 coerce_unsized(bcx, span,
526 Datum::new(ll_source, src_ty,
528 Datum::new(ll_target, target_ty,
529 Rvalue::new(ByRef)));
531 // Otherwise, simply copy the data from the source.
532 assert_eq!(src_ty, target_ty);
533 memcpy_ty(bcx, ll_target, ll_source, src_ty);
537 _ => bcx.sess().bug(&format!("coerce_unsized: invalid coercion {:?} -> {:?}",
544 /// Translates an expression in "lvalue" mode -- meaning that it returns a reference to the memory
545 /// that the expr represents.
547 /// If this expression is an rvalue, this implies introducing a temporary. In other words,
548 /// something like `x().f` is translated into roughly the equivalent of
550 /// { tmp = x(); tmp.f }
551 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
554 -> DatumBlock<'blk, 'tcx, Lvalue> {
556 let datum = unpack_datum!(bcx, trans(bcx, expr));
557 return datum.to_lvalue_datum(bcx, name, expr.id);
560 /// A version of `trans` that ignores adjustments. You almost certainly do not want to call this
562 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
564 -> DatumBlock<'blk, 'tcx, Expr> {
567 debug!("trans_unadjusted(expr={:?})", expr);
568 let _indenter = indenter();
570 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
572 return match expr_kind(bcx.tcx(), expr) {
573 ExprKind::Lvalue | ExprKind::RvalueDatum => {
574 let datum = unpack_datum!(bcx, {
575 trans_datum_unadjusted(bcx, expr)
578 DatumBlock {bcx: bcx, datum: datum}
581 ExprKind::RvalueStmt => {
582 bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
583 nil(bcx, expr_ty(bcx, expr))
586 ExprKind::RvalueDps => {
587 let ty = expr_ty(bcx, expr);
588 if type_is_zero_size(bcx.ccx(), ty) {
589 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
592 let scratch = rvalue_scratch_datum(bcx, ty, "");
593 bcx = trans_rvalue_dps_unadjusted(
594 bcx, expr, SaveIn(scratch.val));
596 // Note: this is not obviously a good idea. It causes
597 // immediate values to be loaded immediately after a
598 // return from a call or other similar expression,
599 // which in turn leads to alloca's having shorter
600 // lifetimes and hence larger stack frames. However,
601 // in turn it can lead to more register pressure.
602 // Still, in practice it seems to increase
603 // performance, since we have fewer problems with
605 let scratch = unpack_datum!(
606 bcx, scratch.to_appropriate_datum(bcx));
608 DatumBlock::new(bcx, scratch.to_expr_datum())
613 fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: Ty<'tcx>)
614 -> DatumBlock<'blk, 'tcx, Expr> {
615 let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
616 let datum = immediate_rvalue(llval, ty);
617 DatumBlock::new(bcx, datum.to_expr_datum())
621 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
623 -> DatumBlock<'blk, 'tcx, Expr> {
626 let _icx = push_ctxt("trans_datum_unadjusted");
629 ast::ExprParen(ref e) => {
632 ast::ExprPath(..) => {
633 trans_def(bcx, expr, bcx.def(expr.id))
635 ast::ExprField(ref base, ident) => {
636 trans_rec_field(bcx, &**base, ident.node.name)
638 ast::ExprTupField(ref base, idx) => {
639 trans_rec_tup_field(bcx, &**base, idx.node)
641 ast::ExprIndex(ref base, ref idx) => {
642 trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id))
644 ast::ExprBox(_, ref contents) => {
645 // Special case for `Box<T>`
646 let box_ty = expr_ty(bcx, expr);
647 let contents_ty = expr_ty(bcx, &**contents);
650 trans_uniq_expr(bcx, expr, box_ty, &**contents, contents_ty)
652 _ => bcx.sess().span_bug(expr.span,
653 "expected unique box")
657 ast::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, &**lit),
658 ast::ExprBinary(op, ref lhs, ref rhs) => {
659 trans_binary(bcx, expr, op, &**lhs, &**rhs)
661 ast::ExprUnary(op, ref x) => {
662 trans_unary(bcx, expr, op, &**x)
664 ast::ExprAddrOf(_, ref x) => {
666 ast::ExprRepeat(..) | ast::ExprVec(..) => {
667 // Special case for slices.
668 let cleanup_debug_loc =
669 debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
673 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
674 let datum = unpack_datum!(
675 bcx, tvec::trans_slice_vec(bcx, expr, &**x));
676 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
677 DatumBlock::new(bcx, datum)
680 trans_addr_of(bcx, expr, &**x)
684 ast::ExprCast(ref val, _) => {
685 // Datum output mode means this is a scalar cast:
686 trans_imm_cast(bcx, &**val, expr.id)
689 bcx.tcx().sess.span_bug(
691 &format!("trans_rvalue_datum_unadjusted reached \
692 fall-through case: {:?}",
698 fn trans_field<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
701 -> DatumBlock<'blk, 'tcx, Expr> where
702 F: FnOnce(&'blk ty::ctxt<'tcx>, &VariantInfo<'tcx>) -> usize,
705 let _icx = push_ctxt("trans_rec_field");
707 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
708 let bare_ty = base_datum.ty;
709 let repr = adt::represent_type(bcx.ccx(), bare_ty);
710 let vinfo = VariantInfo::from_ty(bcx.tcx(), bare_ty, None);
712 let ix = get_idx(bcx.tcx(), &vinfo);
713 let d = base_datum.get_element(
716 |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, vinfo.discr, ix));
718 if type_is_sized(bcx.tcx(), d.ty) {
719 DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
721 let scratch = rvalue_scratch_datum(bcx, d.ty, "");
722 Store(bcx, d.val, get_dataptr(bcx, scratch.val));
723 let info = Load(bcx, get_meta(bcx, base_datum.val));
724 Store(bcx, info, get_meta(bcx, scratch.val));
726 // Always generate an lvalue datum, because this pointer doesn't own
727 // the data and cleanup is scheduled elsewhere.
728 DatumBlock::new(bcx, Datum::new(scratch.val, scratch.ty, LvalueExpr(d.kind)))
732 /// Translates `base.field`.
733 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
736 -> DatumBlock<'blk, 'tcx, Expr> {
737 trans_field(bcx, base, |_, vinfo| vinfo.field_index(field))
740 /// Translates `base.<idx>`.
741 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
744 -> DatumBlock<'blk, 'tcx, Expr> {
745 trans_field(bcx, base, |_, _| idx)
748 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
749 index_expr: &ast::Expr,
752 method_call: MethodCall)
753 -> DatumBlock<'blk, 'tcx, Expr> {
754 //! Translates `base[idx]`.
756 let _icx = push_ctxt("trans_index");
760 let index_expr_debug_loc = index_expr.debug_loc();
762 // Check for overloaded index.
763 let method_ty = ccx.tcx()
768 .map(|method| method.ty);
769 let elt_datum = match method_ty {
771 let method_ty = monomorphize_type(bcx, method_ty);
773 let base_datum = unpack_datum!(bcx, trans(bcx, base));
775 // Translate index expression.
776 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
778 let ref_ty = // invoked methods have LB regions instantiated:
779 bcx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
780 let elt_ty = match ref_ty.builtin_deref(true) {
782 bcx.tcx().sess.span_bug(index_expr.span,
783 "index method didn't return a \
784 dereferenceable type?!")
786 Some(elt_tm) => elt_tm.ty,
789 // Overloaded. Evaluate `trans_overloaded_op`, which will
790 // invoke the user's index() method, which basically yields
791 // a `&T` pointer. We can then proceed down the normal
792 // path (below) to dereference that `&T`.
793 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_index_elt");
795 trans_overloaded_op(bcx,
799 Some((ix_datum, idx.id)),
800 Some(SaveIn(scratch.val)),
802 let datum = scratch.to_expr_datum();
803 let lval = Lvalue::new("expr::trans_index overload");
804 if type_is_sized(bcx.tcx(), elt_ty) {
805 Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr(lval))
807 Datum::new(datum.val, elt_ty, LvalueExpr(lval))
811 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
815 // Translate index expression and cast to a suitable LLVM integer.
816 // Rust is less strict than LLVM in this regard.
817 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
818 let ix_val = ix_datum.to_llscalarish(bcx);
819 let ix_size = machine::llbitsize_of_real(bcx.ccx(),
821 let int_size = machine::llbitsize_of_real(bcx.ccx(),
824 if ix_size < int_size {
825 if expr_ty(bcx, idx).is_signed() {
826 SExt(bcx, ix_val, ccx.int_type())
827 } else { ZExt(bcx, ix_val, ccx.int_type()) }
828 } else if ix_size > int_size {
829 Trunc(bcx, ix_val, ccx.int_type())
835 let unit_ty = base_datum.ty.sequence_element_type(bcx.tcx());
837 let (base, len) = base_datum.get_vec_base_and_len(bcx);
839 debug!("trans_index: base {}", bcx.val_to_string(base));
840 debug!("trans_index: len {}", bcx.val_to_string(len));
842 let bounds_check = ICmp(bcx,
846 index_expr_debug_loc);
847 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
848 let expected = Call(bcx,
850 &[bounds_check, C_bool(ccx, false)],
852 index_expr_debug_loc);
853 bcx = with_cond(bcx, expected, |bcx| {
854 controlflow::trans_fail_bounds_check(bcx,
855 expr_info(index_expr),
859 let elt = InBoundsGEP(bcx, base, &[ix_val]);
860 let elt = PointerCast(bcx, elt, type_of::type_of(ccx, unit_ty).ptr_to());
861 let lval = Lvalue::new("expr::trans_index fallback");
862 Datum::new(elt, unit_ty, LvalueExpr(lval))
866 DatumBlock::new(bcx, elt_datum)
869 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
870 ref_expr: &ast::Expr,
872 -> DatumBlock<'blk, 'tcx, Expr> {
873 //! Translates a reference to a path.
875 let _icx = push_ctxt("trans_def_lvalue");
877 def::DefFn(..) | def::DefMethod(..) |
878 def::DefStruct(_) | def::DefVariant(..) => {
879 let datum = trans_def_fn_unadjusted(bcx.ccx(), ref_expr, def,
880 bcx.fcx.param_substs);
881 DatumBlock::new(bcx, datum.to_expr_datum())
883 def::DefStatic(did, _) => {
884 // There are two things that may happen here:
885 // 1) If the static item is defined in this crate, it will be
886 // translated using `get_item_val`, and we return a pointer to
888 // 2) If the static item is defined in another crate then we add
889 // (or reuse) a declaration of an external global, and return a
891 let const_ty = expr_ty(bcx, ref_expr);
893 // For external constants, we don't inline.
894 let val = if did.is_local() {
897 // The LLVM global has the type of its initializer,
898 // which may not be equal to the enum's type for
900 let val = base::get_item_val(bcx.ccx(), did.node);
901 let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to();
902 PointerCast(bcx, val, pty)
905 base::get_extern_const(bcx.ccx(), did, const_ty)
907 let lval = Lvalue::new("expr::trans_def");
908 DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr(lval)))
910 def::DefConst(_) => {
911 bcx.sess().span_bug(ref_expr.span,
912 "constant expression should not reach expr::trans_def")
915 DatumBlock::new(bcx, trans_local_var(bcx, def).to_expr_datum())
920 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
922 -> Block<'blk, 'tcx> {
924 let _icx = push_ctxt("trans_rvalue_stmt");
926 if bcx.unreachable.get() {
930 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
933 ast::ExprParen(ref e) => {
934 trans_into(bcx, &**e, Ignore)
936 ast::ExprBreak(label_opt) => {
937 controlflow::trans_break(bcx, expr, label_opt)
939 ast::ExprAgain(label_opt) => {
940 controlflow::trans_cont(bcx, expr, label_opt)
942 ast::ExprRet(ref ex) => {
943 // Check to see if the return expression itself is reachable.
944 // This can occur when the inner expression contains a return
945 let reachable = if let Some(ref cfg) = bcx.fcx.cfg {
946 cfg.node_is_reachable(expr.id)
952 controlflow::trans_ret(bcx, expr, ex.as_ref().map(|e| &**e))
954 // If it's not reachable, just translate the inner expression
955 // directly. This avoids having to manage a return slot when
956 // it won't actually be used anyway.
957 if let &Some(ref x) = ex {
958 bcx = trans_into(bcx, &**x, Ignore);
960 // Mark the end of the block as unreachable. Once we get to
961 // a return expression, there's no more we should be doing
967 ast::ExprWhile(ref cond, ref body, _) => {
968 controlflow::trans_while(bcx, expr, &**cond, &**body)
970 ast::ExprLoop(ref body, _) => {
971 controlflow::trans_loop(bcx, expr, &**body)
973 ast::ExprAssign(ref dst, ref src) => {
974 let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
975 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
977 if bcx.fcx.type_needs_drop(dst_datum.ty) {
978 // If there are destructors involved, make sure we
979 // are copying from an rvalue, since that cannot possible
980 // alias an lvalue. We are concerned about code like:
988 // where e.g. a : Option<Foo> and a.b :
989 // Option<Foo>. In that case, freeing `a` before the
990 // assignment may also free `a.b`!
992 // We could avoid this intermediary with some analysis
993 // to determine whether `dst` may possibly own `src`.
994 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
995 let src_datum = unpack_datum!(
996 bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
997 let opt_hint_datum = dst_datum.kind.drop_flag_info.hint_datum(bcx);
998 let opt_hint_val = opt_hint_datum.map(|d|d.to_value());
1000 // 1. Drop the data at the destination, passing the
1001 // drop-hint in case the lvalue has already been
1002 // dropped or moved.
1003 bcx = glue::drop_ty_core(bcx,
1010 // 2. We are overwriting the destination; ensure that
1011 // its drop-hint (if any) says "initialized."
1012 if let Some(hint_val) = opt_hint_val {
1013 let hint_llval = hint_val.value();
1014 let drop_needed = C_u8(bcx.fcx.ccx, adt::DTOR_NEEDED_HINT);
1015 Store(bcx, drop_needed, hint_llval);
1017 src_datum.store_to(bcx, dst_datum.val)
1019 src_datum.store_to(bcx, dst_datum.val)
1022 ast::ExprAssignOp(op, ref dst, ref src) => {
1023 trans_assign_op(bcx, expr, op, &**dst, &**src)
1025 ast::ExprInlineAsm(ref a) => {
1026 asm::trans_inline_asm(bcx, a)
1029 bcx.tcx().sess.span_bug(
1031 &format!("trans_rvalue_stmt_unadjusted reached \
1032 fall-through case: {:?}",
1038 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1041 -> Block<'blk, 'tcx> {
1042 let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
1044 let tcx = bcx.tcx();
1046 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
1049 ast::ExprParen(ref e) => {
1050 trans_into(bcx, &**e, dest)
1052 ast::ExprPath(..) => {
1053 trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
1055 ast::ExprIf(ref cond, ref thn, ref els) => {
1056 controlflow::trans_if(bcx, expr.id, &**cond, &**thn, els.as_ref().map(|e| &**e), dest)
1058 ast::ExprMatch(ref discr, ref arms, _) => {
1059 _match::trans_match(bcx, expr, &**discr, &arms[..], dest)
1061 ast::ExprBlock(ref blk) => {
1062 controlflow::trans_block(bcx, &**blk, dest)
1064 ast::ExprStruct(_, ref fields, ref base) => {
1067 base.as_ref().map(|e| &**e),
1070 node_id_type(bcx, expr.id),
1073 ast::ExprRange(ref start, ref end) => {
1074 // FIXME it is just not right that we are synthesising ast nodes in
1076 fn make_field(field_name: &str, expr: P<ast::Expr>) -> ast::Field {
1078 ident: codemap::dummy_spanned(token::str_to_ident(field_name)),
1080 span: codemap::DUMMY_SP,
1084 // A range just desugars into a struct.
1085 // Note that the type of the start and end may not be the same, but
1086 // they should only differ in their lifetime, which should not matter
1088 let (did, fields, ty_params) = match (start, end) {
1089 (&Some(ref start), &Some(ref end)) => {
1091 let fields = vec![make_field("start", start.clone()),
1092 make_field("end", end.clone())];
1093 (tcx.lang_items.range_struct(), fields, vec![node_id_type(bcx, start.id)])
1095 (&Some(ref start), &None) => {
1096 // Desugar to RangeFrom
1097 let fields = vec![make_field("start", start.clone())];
1098 (tcx.lang_items.range_from_struct(), fields, vec![node_id_type(bcx, start.id)])
1100 (&None, &Some(ref end)) => {
1101 // Desugar to RangeTo
1102 let fields = vec![make_field("end", end.clone())];
1103 (tcx.lang_items.range_to_struct(), fields, vec![node_id_type(bcx, end.id)])
1106 // Desugar to RangeFull
1107 (tcx.lang_items.range_full_struct(), vec![], vec![])
1111 if let Some(did) = did {
1112 let substs = Substs::new_type(ty_params, vec![]);
1118 tcx.mk_struct(tcx.lookup_adt_def(did),
1119 tcx.mk_substs(substs)),
1122 tcx.sess.span_bug(expr.span,
1123 "No lang item for ranges (how did we get this far?)")
1126 ast::ExprTup(ref args) => {
1127 let numbered_fields: Vec<(usize, &ast::Expr)> =
1128 args.iter().enumerate().map(|(i, arg)| (i, &**arg)).collect();
1132 &numbered_fields[..],
1137 ast::ExprLit(ref lit) => {
1139 ast::LitStr(ref s, _) => {
1140 tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1145 .span_bug(expr.span,
1146 "trans_rvalue_dps_unadjusted shouldn't be \
1147 translating this type of literal")
1151 ast::ExprVec(..) | ast::ExprRepeat(..) => {
1152 tvec::trans_fixed_vstore(bcx, expr, dest)
1154 ast::ExprClosure(_, ref decl, ref body) => {
1155 let dest = match dest {
1156 SaveIn(lldest) => closure::Dest::SaveIn(bcx, lldest),
1157 Ignore => closure::Dest::Ignore(bcx.ccx())
1159 let substs = match expr_ty(bcx, expr).sty {
1160 ty::TyClosure(_, ref substs) => substs,
1162 bcx.tcx().sess.span_bug(
1164 &format!("closure expr without closure type: {:?}", t)),
1166 closure::trans_closure_expr(dest, decl, body, expr.id, substs).unwrap_or(bcx)
1168 ast::ExprCall(ref f, ref args) => {
1169 if bcx.tcx().is_method_call(expr.id) {
1170 trans_overloaded_call(bcx,
1176 callee::trans_call(bcx,
1179 callee::ArgExprs(&args[..]),
1183 ast::ExprMethodCall(_, _, ref args) => {
1184 callee::trans_method_call(bcx,
1187 callee::ArgExprs(&args[..]),
1190 ast::ExprBinary(op, ref lhs, ref rhs) => {
1191 // if not overloaded, would be RvalueDatumExpr
1192 let lhs = unpack_datum!(bcx, trans(bcx, &**lhs));
1193 let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs));
1194 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs,
1195 Some((rhs_datum, rhs.id)), Some(dest),
1196 !ast_util::is_by_value_binop(op.node)).bcx
1198 ast::ExprUnary(op, ref subexpr) => {
1199 // if not overloaded, would be RvalueDatumExpr
1200 let arg = unpack_datum!(bcx, trans(bcx, &**subexpr));
1201 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id),
1202 arg, None, Some(dest), !ast_util::is_by_value_unop(op)).bcx
1204 ast::ExprIndex(ref base, ref idx) => {
1205 // if not overloaded, would be RvalueDatumExpr
1206 let base = unpack_datum!(bcx, trans(bcx, &**base));
1207 let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx));
1208 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
1209 Some((idx_datum, idx.id)), Some(dest), true).bcx
1211 ast::ExprCast(..) => {
1212 // Trait casts used to come this way, now they should be coercions.
1213 bcx.tcx().sess.span_bug(expr.span, "DPS expr_cast (residual trait cast?)")
1215 ast::ExprAssignOp(op, ref dst, ref src) => {
1216 trans_assign_op(bcx, expr, op, &**dst, &**src)
1219 bcx.tcx().sess.span_bug(
1221 &format!("trans_rvalue_dps_unadjusted reached fall-through \
1228 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1229 ref_expr: &ast::Expr,
1232 -> Block<'blk, 'tcx> {
1233 let _icx = push_ctxt("trans_def_dps_unadjusted");
1235 let lldest = match dest {
1236 SaveIn(lldest) => lldest,
1237 Ignore => { return bcx; }
1241 def::DefVariant(tid, vid, _) => {
1242 let variant = bcx.tcx().lookup_adt_def(tid).variant_with_id(vid);
1243 if let ty::VariantKind::Tuple = variant.kind() {
1245 let llfn = callee::trans_fn_ref(bcx.ccx(), vid,
1246 ExprId(ref_expr.id),
1247 bcx.fcx.param_substs).val;
1248 Store(bcx, llfn, lldest);
1252 let ty = expr_ty(bcx, ref_expr);
1253 let repr = adt::represent_type(bcx.ccx(), ty);
1254 adt::trans_set_discr(bcx, &*repr, lldest, variant.disr_val);
1258 def::DefStruct(_) => {
1259 let ty = expr_ty(bcx, ref_expr);
1261 ty::TyStruct(def, _) if def.has_dtor() => {
1262 let repr = adt::represent_type(bcx.ccx(), ty);
1263 adt::trans_set_discr(bcx, &*repr, lldest, 0);
1270 bcx.tcx().sess.span_bug(ref_expr.span, &format!(
1271 "Non-DPS def {:?} referened by {}",
1272 def, bcx.node_id_to_string(ref_expr.id)));
1277 pub fn trans_def_fn_unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1278 ref_expr: &ast::Expr,
1280 param_substs: &'tcx Substs<'tcx>)
1281 -> Datum<'tcx, Rvalue> {
1282 let _icx = push_ctxt("trans_def_datum_unadjusted");
1285 def::DefFn(did, _) |
1286 def::DefStruct(did) | def::DefVariant(_, did, _) => {
1287 callee::trans_fn_ref(ccx, did, ExprId(ref_expr.id), param_substs)
1289 def::DefMethod(method_did) => {
1290 match ccx.tcx().impl_or_trait_item(method_did).container() {
1291 ty::ImplContainer(_) => {
1292 callee::trans_fn_ref(ccx, method_did,
1293 ExprId(ref_expr.id),
1296 ty::TraitContainer(trait_did) => {
1297 meth::trans_static_method_callee(ccx, method_did,
1298 trait_did, ref_expr.id,
1304 ccx.tcx().sess.span_bug(ref_expr.span, &format!(
1305 "trans_def_fn_unadjusted invoked on: {:?} for {:?}",
1312 /// Translates a reference to a local variable or argument. This always results in an lvalue datum.
1313 pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1315 -> Datum<'tcx, Lvalue> {
1316 let _icx = push_ctxt("trans_local_var");
1319 def::DefUpvar(nid, _) => {
1320 // Can't move upvars, so this is never a ZeroMemLastUse.
1321 let local_ty = node_id_type(bcx, nid);
1322 let lval = Lvalue::new_with_hint("expr::trans_local_var (upvar)",
1323 bcx, nid, HintKind::ZeroAndMaintain);
1324 match bcx.fcx.llupvars.borrow().get(&nid) {
1325 Some(&val) => Datum::new(val, local_ty, lval),
1327 bcx.sess().bug(&format!(
1328 "trans_local_var: no llval for upvar {} found",
1333 def::DefLocal(nid) => {
1334 let datum = match bcx.fcx.lllocals.borrow().get(&nid) {
1337 bcx.sess().bug(&format!(
1338 "trans_local_var: no datum for local/arg {} found",
1342 debug!("take_local(nid={}, v={}, ty={})",
1343 nid, bcx.val_to_string(datum.val), datum.ty);
1347 bcx.sess().unimpl(&format!(
1348 "unsupported def type in trans_local_var: {:?}",
1354 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1355 fields: &[ast::Field],
1356 base: Option<&ast::Expr>,
1357 expr_span: codemap::Span,
1358 expr_id: ast::NodeId,
1360 dest: Dest) -> Block<'blk, 'tcx> {
1361 let _icx = push_ctxt("trans_rec");
1363 let tcx = bcx.tcx();
1364 let vinfo = VariantInfo::of_node(tcx, ty, expr_id);
1366 let mut need_base = vec![true; vinfo.fields.len()];
1368 let numbered_fields = fields.iter().map(|field| {
1369 let pos = vinfo.field_index(field.ident.node.name);
1370 need_base[pos] = false;
1372 }).collect::<Vec<_>>();
1374 let optbase = match base {
1375 Some(base_expr) => {
1376 let mut leftovers = Vec::new();
1377 for (i, b) in need_base.iter().enumerate() {
1379 leftovers.push((i, vinfo.fields[i].1));
1382 Some(StructBaseInfo {expr: base_expr,
1383 fields: leftovers })
1386 if need_base.iter().any(|b| *b) {
1387 tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1399 DebugLoc::At(expr_id, expr_span))
1402 /// Information that `trans_adt` needs in order to fill in the fields
1403 /// of a struct copied from a base struct (e.g., from an expression
1404 /// like `Foo { a: b, ..base }`.
1406 /// Note that `fields` may be empty; the base expression must always be
1407 /// evaluated for side-effects.
1408 pub struct StructBaseInfo<'a, 'tcx> {
1409 /// The base expression; will be evaluated after all explicit fields.
1410 expr: &'a ast::Expr,
1411 /// The indices of fields to copy paired with their types.
1412 fields: Vec<(usize, Ty<'tcx>)>
1415 /// Constructs an ADT instance:
1417 /// - `fields` should be a list of field indices paired with the
1418 /// expression to store into that field. The initializers will be
1419 /// evaluated in the order specified by `fields`.
1421 /// - `optbase` contains information on the base struct (if any) from
1422 /// which remaining fields are copied; see comments on `StructBaseInfo`.
1423 pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1426 fields: &[(usize, &ast::Expr)],
1427 optbase: Option<StructBaseInfo<'a, 'tcx>>,
1429 debug_location: DebugLoc)
1430 -> Block<'blk, 'tcx> {
1431 let _icx = push_ctxt("trans_adt");
1433 let repr = adt::represent_type(bcx.ccx(), ty);
1435 debug_location.apply(bcx.fcx);
1437 // If we don't care about the result, just make a
1438 // temporary stack slot
1439 let addr = match dest {
1442 let llresult = alloc_ty(bcx, ty, "temp");
1443 call_lifetime_start(bcx, llresult);
1448 // This scope holds intermediates that must be cleaned should
1449 // panic occur before the ADT as a whole is ready.
1450 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1453 // Issue 23112: The original logic appeared vulnerable to same
1454 // order-of-eval bug. But, SIMD values are tuple-structs;
1455 // i.e. functional record update (FRU) syntax is unavailable.
1457 // To be safe, double-check that we did not get here via FRU.
1458 assert!(optbase.is_none());
1460 // This is the constructor of a SIMD type, such types are
1461 // always primitive machine types and so do not have a
1462 // destructor or require any clean-up.
1463 let llty = type_of::type_of(bcx.ccx(), ty);
1465 // keep a vector as a register, and running through the field
1466 // `insertelement`ing them directly into that register
1467 // (i.e. avoid GEPi and `store`s to an alloca) .
1468 let mut vec_val = C_undef(llty);
1470 for &(i, ref e) in fields {
1471 let block_datum = trans(bcx, &**e);
1472 bcx = block_datum.bcx;
1473 let position = C_uint(bcx.ccx(), i);
1474 let value = block_datum.datum.to_llscalarish(bcx);
1475 vec_val = InsertElement(bcx, vec_val, value, position);
1477 Store(bcx, vec_val, addr);
1478 } else if let Some(base) = optbase {
1479 // Issue 23112: If there is a base, then order-of-eval
1480 // requires field expressions eval'ed before base expression.
1482 // First, trans field expressions to temporary scratch values.
1483 let scratch_vals: Vec<_> = fields.iter().map(|&(i, ref e)| {
1484 let datum = unpack_datum!(bcx, trans(bcx, &**e));
1488 debug_location.apply(bcx.fcx);
1490 // Second, trans the base to the dest.
1491 assert_eq!(discr, 0);
1493 match expr_kind(bcx.tcx(), &*base.expr) {
1494 ExprKind::RvalueDps | ExprKind::RvalueDatum if !bcx.fcx.type_needs_drop(ty) => {
1495 bcx = trans_into(bcx, &*base.expr, SaveIn(addr));
1497 ExprKind::RvalueStmt => {
1498 bcx.tcx().sess.bug("unexpected expr kind for struct base expr")
1501 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base"));
1502 for &(i, t) in &base.fields {
1503 let datum = base_datum.get_element(
1504 bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i));
1505 assert!(type_is_sized(bcx.tcx(), datum.ty));
1506 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1507 bcx = datum.store_to(bcx, dest);
1512 // Finally, move scratch field values into actual field locations
1513 for (i, datum) in scratch_vals {
1514 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1515 bcx = datum.store_to(bcx, dest);
1518 // No base means we can write all fields directly in place.
1519 for &(i, ref e) in fields {
1520 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1521 let e_ty = expr_ty_adjusted(bcx, &**e);
1522 bcx = trans_into(bcx, &**e, SaveIn(dest));
1523 let scope = cleanup::CustomScope(custom_cleanup_scope);
1524 fcx.schedule_lifetime_end(scope, dest);
1525 // FIXME: nonzeroing move should generalize to fields
1526 fcx.schedule_drop_mem(scope, dest, e_ty, None);
1530 adt::trans_set_discr(bcx, &*repr, addr, discr);
1532 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1534 // If we don't care about the result drop the temporary we made
1538 bcx = glue::drop_ty(bcx, addr, ty, debug_location);
1539 base::call_lifetime_end(bcx, addr);
1546 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1549 -> DatumBlock<'blk, 'tcx, Expr> {
1550 // must not be a string constant, that is a RvalueDpsExpr
1551 let _icx = push_ctxt("trans_immediate_lit");
1552 let ty = expr_ty(bcx, expr);
1553 let v = consts::const_lit(bcx.ccx(), expr, lit);
1554 immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1557 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1560 sub_expr: &ast::Expr)
1561 -> DatumBlock<'blk, 'tcx, Expr> {
1562 let ccx = bcx.ccx();
1564 let _icx = push_ctxt("trans_unary_datum");
1566 let method_call = MethodCall::expr(expr.id);
1568 // The only overloaded operator that is translated to a datum
1569 // is an overloaded deref, since it is always yields a `&T`.
1570 // Otherwise, we should be in the RvalueDpsExpr path.
1571 assert!(op == ast::UnDeref || !ccx.tcx().is_method_call(expr.id));
1573 let un_ty = expr_ty(bcx, expr);
1575 let debug_loc = expr.debug_loc();
1579 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1580 let llresult = Not(bcx, datum.to_llscalarish(bcx), debug_loc);
1581 immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1584 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1585 let val = datum.to_llscalarish(bcx);
1586 let (bcx, llneg) = {
1588 let result = FNeg(bcx, val, debug_loc);
1591 let is_signed = un_ty.is_signed();
1592 let result = Neg(bcx, val, debug_loc);
1593 let bcx = if bcx.ccx().check_overflow() && is_signed {
1594 let (llty, min) = base::llty_and_min_for_signed_ty(bcx, un_ty);
1595 let is_min = ICmp(bcx, llvm::IntEQ, val,
1596 C_integral(llty, min, true), debug_loc);
1597 with_cond(bcx, is_min, |bcx| {
1598 let msg = InternedString::new(
1599 "attempted to negate with overflow");
1600 controlflow::trans_fail(bcx, expr_info(expr), msg)
1608 immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1611 trans_uniq_expr(bcx, expr, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1614 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1615 deref_once(bcx, expr, datum, method_call)
1620 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1621 box_expr: &ast::Expr,
1623 contents: &ast::Expr,
1624 contents_ty: Ty<'tcx>)
1625 -> DatumBlock<'blk, 'tcx, Expr> {
1626 let _icx = push_ctxt("trans_uniq_expr");
1628 assert!(type_is_sized(bcx.tcx(), contents_ty));
1629 let llty = type_of::type_of(bcx.ccx(), contents_ty);
1630 let size = llsize_of(bcx.ccx(), llty);
1631 let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty));
1632 let llty_ptr = llty.ptr_to();
1633 let Result { bcx, val } = malloc_raw_dyn(bcx,
1638 box_expr.debug_loc());
1639 // Unique boxes do not allocate for zero-size types. The standard library
1640 // may assume that `free` is never called on the pointer returned for
1641 // `Box<ZeroSizeType>`.
1642 let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1643 trans_into(bcx, contents, SaveIn(val))
1645 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1646 fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1647 val, cleanup::HeapExchange, contents_ty);
1648 let bcx = trans_into(bcx, contents, SaveIn(val));
1649 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1652 immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1655 fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1656 lval: Datum<'tcx, Lvalue>)
1657 -> DatumBlock<'blk, 'tcx, Expr> {
1658 let dest_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), lval.ty);
1659 let scratch = rvalue_scratch_datum(bcx, dest_ty, "__fat_ptr");
1660 memcpy_ty(bcx, scratch.val, lval.val, scratch.ty);
1662 DatumBlock::new(bcx, scratch.to_expr_datum())
1665 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1667 subexpr: &ast::Expr)
1668 -> DatumBlock<'blk, 'tcx, Expr> {
1669 let _icx = push_ctxt("trans_addr_of");
1671 let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1672 if !type_is_sized(bcx.tcx(), sub_datum.ty) {
1673 // DST lvalue, close to a fat pointer
1674 ref_fat_ptr(bcx, sub_datum)
1676 // Sized value, ref to a thin pointer
1677 let ty = expr_ty(bcx, expr);
1678 immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1682 // Important to get types for both lhs and rhs, because one might be _|_
1683 // and the other not.
1684 fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1685 binop_expr: &ast::Expr,
1692 -> DatumBlock<'blk, 'tcx, Expr> {
1693 let _icx = push_ctxt("trans_eager_binop");
1695 let tcx = bcx.tcx();
1696 assert!(!lhs_t.is_simd());
1697 let is_float = lhs_t.is_fp();
1698 let is_signed = lhs_t.is_signed();
1699 let info = expr_info(binop_expr);
1701 let binop_debug_loc = binop_expr.debug_loc();
1704 let val = match op.node {
1707 FAdd(bcx, lhs, rhs, binop_debug_loc)
1709 let (newbcx, res) = with_overflow_check(
1710 bcx, OverflowOp::Add, info, lhs_t, lhs, rhs, binop_debug_loc);
1717 FSub(bcx, lhs, rhs, binop_debug_loc)
1719 let (newbcx, res) = with_overflow_check(
1720 bcx, OverflowOp::Sub, info, lhs_t, lhs, rhs, binop_debug_loc);
1727 FMul(bcx, lhs, rhs, binop_debug_loc)
1729 let (newbcx, res) = with_overflow_check(
1730 bcx, OverflowOp::Mul, info, lhs_t, lhs, rhs, binop_debug_loc);
1737 FDiv(bcx, lhs, rhs, binop_debug_loc)
1739 // Only zero-check integers; fp /0 is NaN
1740 bcx = base::fail_if_zero_or_overflows(bcx,
1741 expr_info(binop_expr),
1747 SDiv(bcx, lhs, rhs, binop_debug_loc)
1749 UDiv(bcx, lhs, rhs, binop_debug_loc)
1755 // LLVM currently always lowers the `frem` instructions appropriate
1756 // library calls typically found in libm. Notably f64 gets wired up
1757 // to `fmod` and f32 gets wired up to `fmodf`. Inconveniently for
1758 // us, 32-bit MSVC does not actually have a `fmodf` symbol, it's
1759 // instead just an inline function in a header that goes up to a
1760 // f64, uses `fmod`, and then comes back down to a f32.
1762 // Although LLVM knows that `fmodf` doesn't exist on MSVC, it will
1763 // still unconditionally lower frem instructions over 32-bit floats
1764 // to a call to `fmodf`. To work around this we special case MSVC
1765 // 32-bit float rem instructions and instead do the call out to
1766 // `fmod` ourselves.
1768 // Note that this is currently duplicated with src/libcore/ops.rs
1769 // which does the same thing, and it would be nice to perhaps unify
1770 // these two implementations on day! Also note that we call `fmod`
1771 // for both 32 and 64-bit floats because if we emit any FRem
1772 // instruction at all then LLVM is capable of optimizing it into a
1773 // 32-bit FRem (which we're trying to avoid).
1774 let use_fmod = tcx.sess.target.target.options.is_like_msvc &&
1775 tcx.sess.target.target.arch == "x86";
1777 let f64t = Type::f64(bcx.ccx());
1778 let fty = Type::func(&[f64t, f64t], &f64t);
1779 let llfn = declare::declare_cfn(bcx.ccx(), "fmod", fty,
1781 if lhs_t == tcx.types.f32 {
1782 let lhs = FPExt(bcx, lhs, f64t);
1783 let rhs = FPExt(bcx, rhs, f64t);
1784 let res = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
1785 FPTrunc(bcx, res, Type::f32(bcx.ccx()))
1787 Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc)
1790 FRem(bcx, lhs, rhs, binop_debug_loc)
1793 // Only zero-check integers; fp %0 is NaN
1794 bcx = base::fail_if_zero_or_overflows(bcx,
1795 expr_info(binop_expr),
1796 op, lhs, rhs, rhs_t);
1798 SRem(bcx, lhs, rhs, binop_debug_loc)
1800 URem(bcx, lhs, rhs, binop_debug_loc)
1804 ast::BiBitOr => Or(bcx, lhs, rhs, binop_debug_loc),
1805 ast::BiBitAnd => And(bcx, lhs, rhs, binop_debug_loc),
1806 ast::BiBitXor => Xor(bcx, lhs, rhs, binop_debug_loc),
1808 let (newbcx, res) = with_overflow_check(
1809 bcx, OverflowOp::Shl, info, lhs_t, lhs, rhs, binop_debug_loc);
1814 let (newbcx, res) = with_overflow_check(
1815 bcx, OverflowOp::Shr, info, lhs_t, lhs, rhs, binop_debug_loc);
1819 ast::BiEq | ast::BiNe | ast::BiLt | ast::BiGe | ast::BiLe | ast::BiGt => {
1820 base::compare_scalar_types(bcx, lhs, rhs, lhs_t, op.node, binop_debug_loc)
1823 bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1827 immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1830 // refinement types would obviate the need for this
1831 enum lazy_binop_ty {
1836 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1837 binop_expr: &ast::Expr,
1841 -> DatumBlock<'blk, 'tcx, Expr> {
1842 let _icx = push_ctxt("trans_lazy_binop");
1843 let binop_ty = expr_ty(bcx, binop_expr);
1846 let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1847 let lhs = lhs.to_llscalarish(past_lhs);
1849 if past_lhs.unreachable.get() {
1850 return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1853 let join = fcx.new_id_block("join", binop_expr.id);
1854 let before_rhs = fcx.new_id_block("before_rhs", b.id);
1857 lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb, DebugLoc::None),
1858 lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb, DebugLoc::None)
1861 let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1862 let rhs = rhs.to_llscalarish(past_rhs);
1864 if past_rhs.unreachable.get() {
1865 return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1868 Br(past_rhs, join.llbb, DebugLoc::None);
1869 let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1870 &[past_lhs.llbb, past_rhs.llbb]);
1872 return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1875 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1880 -> DatumBlock<'blk, 'tcx, Expr> {
1881 let _icx = push_ctxt("trans_binary");
1882 let ccx = bcx.ccx();
1884 // if overloaded, would be RvalueDpsExpr
1885 assert!(!ccx.tcx().is_method_call(expr.id));
1889 trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1892 trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1896 let lhs_datum = unpack_datum!(bcx, trans(bcx, lhs));
1897 let rhs_datum = unpack_datum!(bcx, trans(bcx, rhs));
1898 let binop_ty = expr_ty(bcx, expr);
1900 debug!("trans_binary (expr {}): lhs_datum={}",
1902 lhs_datum.to_string(ccx));
1903 let lhs_ty = lhs_datum.ty;
1904 let lhs = lhs_datum.to_llscalarish(bcx);
1906 debug!("trans_binary (expr {}): rhs_datum={}",
1908 rhs_datum.to_string(ccx));
1909 let rhs_ty = rhs_datum.ty;
1910 let rhs = rhs_datum.to_llscalarish(bcx);
1911 trans_eager_binop(bcx, expr, binop_ty, op,
1912 lhs_ty, lhs, rhs_ty, rhs)
1917 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1919 method_call: MethodCall,
1920 lhs: Datum<'tcx, Expr>,
1921 rhs: Option<(Datum<'tcx, Expr>, ast::NodeId)>,
1924 -> Result<'blk, 'tcx> {
1925 callee::trans_call_inner(bcx,
1927 |bcx, arg_cleanup_scope| {
1928 meth::trans_method_callee(bcx,
1933 callee::ArgOverloadedOp(lhs, rhs, autoref),
1937 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1939 callee: &'a ast::Expr,
1940 args: &'a [P<ast::Expr>],
1942 -> Block<'blk, 'tcx> {
1943 debug!("trans_overloaded_call {}", expr.id);
1944 let method_call = MethodCall::expr(expr.id);
1945 let mut all_args = vec!(callee);
1946 all_args.extend(args.iter().map(|e| &**e));
1948 callee::trans_call_inner(bcx,
1950 |bcx, arg_cleanup_scope| {
1951 meth::trans_method_callee(
1957 callee::ArgOverloadedCall(all_args),
1962 pub fn cast_is_noop<'tcx>(tcx: &ty::ctxt<'tcx>,
1967 if let Some(&CastKind::CoercionCast) = tcx.cast_kinds.borrow().get(&expr.id) {
1971 match (t_in.builtin_deref(true), t_out.builtin_deref(true)) {
1972 (Some(ty::TypeAndMut{ ty: t_in, .. }), Some(ty::TypeAndMut{ ty: t_out, .. })) => {
1976 // This condition isn't redundant with the check for CoercionCast:
1977 // different types can be substituted into the same type, and
1978 // == equality can be overconservative if there are regions.
1984 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1987 -> DatumBlock<'blk, 'tcx, Expr>
1989 use middle::cast::CastTy::*;
1990 use middle::cast::IntTy::*;
1992 fn int_cast(bcx: Block,
1999 let _icx = push_ctxt("int_cast");
2000 let srcsz = llsrctype.int_width();
2001 let dstsz = lldsttype.int_width();
2002 return if dstsz == srcsz {
2003 BitCast(bcx, llsrc, lldsttype)
2004 } else if srcsz > dstsz {
2005 TruncOrBitCast(bcx, llsrc, lldsttype)
2007 SExtOrBitCast(bcx, llsrc, lldsttype)
2009 ZExtOrBitCast(bcx, llsrc, lldsttype)
2013 fn float_cast(bcx: Block,
2019 let _icx = push_ctxt("float_cast");
2020 let srcsz = llsrctype.float_width();
2021 let dstsz = lldsttype.float_width();
2022 return if dstsz > srcsz {
2023 FPExt(bcx, llsrc, lldsttype)
2024 } else if srcsz > dstsz {
2025 FPTrunc(bcx, llsrc, lldsttype)
2029 let _icx = push_ctxt("trans_cast");
2031 let ccx = bcx.ccx();
2033 let t_in = expr_ty_adjusted(bcx, expr);
2034 let t_out = node_id_type(bcx, id);
2036 debug!("trans_cast({:?} as {:?})", t_in, t_out);
2037 let mut ll_t_in = type_of::arg_type_of(ccx, t_in);
2038 let ll_t_out = type_of::arg_type_of(ccx, t_out);
2039 // Convert the value to be cast into a ValueRef, either by-ref or
2040 // by-value as appropriate given its type:
2041 let mut datum = unpack_datum!(bcx, trans(bcx, expr));
2043 let datum_ty = monomorphize_type(bcx, datum.ty);
2045 if cast_is_noop(bcx.tcx(), expr, datum_ty, t_out) {
2047 return DatumBlock::new(bcx, datum);
2050 if type_is_fat_ptr(bcx.tcx(), t_in) {
2051 assert!(datum.kind.is_by_ref());
2052 if type_is_fat_ptr(bcx.tcx(), t_out) {
2053 return DatumBlock::new(bcx, Datum::new(
2054 PointerCast(bcx, datum.val, ll_t_out.ptr_to()),
2057 )).to_expr_datumblock();
2059 // Return the address
2060 return immediate_rvalue_bcx(bcx,
2062 Load(bcx, get_dataptr(bcx, datum.val)),
2064 t_out).to_expr_datumblock();
2068 let r_t_in = CastTy::from_ty(t_in).expect("bad input type for cast");
2069 let r_t_out = CastTy::from_ty(t_out).expect("bad output type for cast");
2071 let (llexpr, signed) = if let Int(CEnum) = r_t_in {
2072 let repr = adt::represent_type(ccx, t_in);
2073 let datum = unpack_datum!(
2074 bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
2075 let llexpr_ptr = datum.to_llref();
2076 let discr = adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
2077 ll_t_in = val_ty(discr);
2078 (discr, adt::is_discr_signed(&*repr))
2080 (datum.to_llscalarish(bcx), t_in.is_signed())
2083 let newval = match (r_t_in, r_t_out) {
2084 (Ptr(_), Ptr(_)) | (FnPtr, Ptr(_)) | (RPtr(_), Ptr(_)) => {
2085 PointerCast(bcx, llexpr, ll_t_out)
2087 (Ptr(_), Int(_)) | (FnPtr, Int(_)) => PtrToInt(bcx, llexpr, ll_t_out),
2088 (Int(_), Ptr(_)) => IntToPtr(bcx, llexpr, ll_t_out),
2090 (Int(_), Int(_)) => int_cast(bcx, ll_t_out, ll_t_in, llexpr, signed),
2091 (Float, Float) => float_cast(bcx, ll_t_out, ll_t_in, llexpr),
2092 (Int(_), Float) if signed => SIToFP(bcx, llexpr, ll_t_out),
2093 (Int(_), Float) => UIToFP(bcx, llexpr, ll_t_out),
2094 (Float, Int(I)) => FPToSI(bcx, llexpr, ll_t_out),
2095 (Float, Int(_)) => FPToUI(bcx, llexpr, ll_t_out),
2097 _ => ccx.sess().span_bug(expr.span,
2098 &format!("translating unsupported cast: \
2104 return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
2107 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2112 -> Block<'blk, 'tcx> {
2113 let _icx = push_ctxt("trans_assign_op");
2116 debug!("trans_assign_op(expr={:?})", expr);
2118 // User-defined operator methods cannot be used with `+=` etc right now
2119 assert!(!bcx.tcx().is_method_call(expr.id));
2121 // Evaluate LHS (destination), which should be an lvalue
2122 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2123 assert!(!bcx.fcx.type_needs_drop(dst_datum.ty));
2124 let dst_ty = dst_datum.ty;
2125 let dst = load_ty(bcx, dst_datum.val, dst_datum.ty);
2128 let rhs_datum = unpack_datum!(bcx, trans(bcx, &*src));
2129 let rhs_ty = rhs_datum.ty;
2130 let rhs = rhs_datum.to_llscalarish(bcx);
2132 // Perform computation and store the result
2133 let result_datum = unpack_datum!(
2134 bcx, trans_eager_binop(bcx, expr, dst_datum.ty, op,
2135 dst_ty, dst, rhs_ty, rhs));
2136 return result_datum.store_to(bcx, dst_datum.val);
2139 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2140 datum: Datum<'tcx, Expr>,
2142 -> DatumBlock<'blk, 'tcx, Expr> {
2145 // Ensure cleanup of `datum` if not already scheduled and obtain
2146 // a "by ref" pointer.
2147 let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2149 // Compute final type. Note that we are loose with the region and
2150 // mutability, since those things don't matter in trans.
2151 let referent_ty = lv_datum.ty;
2152 let ptr_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), referent_ty);
2155 let llref = lv_datum.to_llref();
2157 // Construct the resulting datum, using what was the "by ref"
2158 // ValueRef of type `referent_ty` to be the "by value" ValueRef
2159 // of type `&referent_ty`.
2160 // Pointers to DST types are non-immediate, and therefore still use ByRef.
2161 let kind = if type_is_sized(bcx.tcx(), referent_ty) { ByValue } else { ByRef };
2162 DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(kind))))
2165 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2167 datum: Datum<'tcx, Expr>,
2169 -> DatumBlock<'blk, 'tcx, Expr> {
2171 let mut datum = datum;
2173 let method_call = MethodCall::autoderef(expr.id, i as u32);
2174 datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2176 DatumBlock { bcx: bcx, datum: datum }
2179 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2181 datum: Datum<'tcx, Expr>,
2182 method_call: MethodCall)
2183 -> DatumBlock<'blk, 'tcx, Expr> {
2184 let ccx = bcx.ccx();
2186 debug!("deref_once(expr={:?}, datum={}, method_call={:?})",
2188 datum.to_string(ccx),
2193 // Check for overloaded deref.
2194 let method_ty = ccx.tcx()
2198 .get(&method_call).map(|method| method.ty);
2200 let datum = match method_ty {
2201 Some(method_ty) => {
2202 let method_ty = monomorphize_type(bcx, method_ty);
2204 // Overloaded. Evaluate `trans_overloaded_op`, which will
2205 // invoke the user's deref() method, which basically
2206 // converts from the `Smaht<T>` pointer that we have into
2207 // a `&T` pointer. We can then proceed down the normal
2208 // path (below) to dereference that `&T`.
2209 let datum = if method_call.autoderef == 0 {
2212 // Always perform an AutoPtr when applying an overloaded auto-deref
2213 unpack_datum!(bcx, auto_ref(bcx, datum, expr))
2216 let ref_ty = // invoked methods have their LB regions instantiated
2217 ccx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
2218 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2220 unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2221 datum, None, Some(SaveIn(scratch.val)),
2223 scratch.to_expr_datum()
2226 // Not overloaded. We already have a pointer we know how to deref.
2231 let r = match datum.ty.sty {
2232 ty::TyBox(content_ty) => {
2233 // Make sure we have an lvalue datum here to get the
2234 // proper cleanups scheduled
2235 let datum = unpack_datum!(
2236 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2238 if type_is_sized(bcx.tcx(), content_ty) {
2239 let ptr = load_ty(bcx, datum.val, datum.ty);
2240 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(datum.kind)))
2242 // A fat pointer and a DST lvalue have the same representation
2243 // just different types. Since there is no temporary for `*e`
2244 // here (because it is unsized), we cannot emulate the sized
2245 // object code path for running drop glue and free. Instead,
2246 // we schedule cleanup for `e`, turning it into an lvalue.
2248 let lval = Lvalue::new("expr::deref_once ty_uniq");
2249 let datum = Datum::new(datum.val, content_ty, LvalueExpr(lval));
2250 DatumBlock::new(bcx, datum)
2254 ty::TyRawPtr(ty::TypeAndMut { ty: content_ty, .. }) |
2255 ty::TyRef(_, ty::TypeAndMut { ty: content_ty, .. }) => {
2256 let lval = Lvalue::new("expr::deref_once ptr");
2257 if type_is_sized(bcx.tcx(), content_ty) {
2258 let ptr = datum.to_llscalarish(bcx);
2260 // Always generate an lvalue datum, even if datum.mode is
2261 // an rvalue. This is because datum.mode is only an
2262 // rvalue for non-owning pointers like &T or *T, in which
2263 // case cleanup *is* scheduled elsewhere, by the true
2264 // owner (or, in the case of *T, by the user).
2265 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr(lval)))
2267 // A fat pointer and a DST lvalue have the same representation
2268 // just different types.
2269 DatumBlock::new(bcx, Datum::new(datum.val, content_ty, LvalueExpr(lval)))
2274 bcx.tcx().sess.span_bug(
2276 &format!("deref invoked on expr of invalid type {:?}",
2281 debug!("deref_once(expr={}, method_call={:?}, result={})",
2282 expr.id, method_call, r.datum.to_string(ccx));
2297 fn codegen_strategy(&self) -> OverflowCodegen {
2298 use self::OverflowCodegen::{ViaIntrinsic, ViaInputCheck};
2300 OverflowOp::Add => ViaIntrinsic(OverflowOpViaIntrinsic::Add),
2301 OverflowOp::Sub => ViaIntrinsic(OverflowOpViaIntrinsic::Sub),
2302 OverflowOp::Mul => ViaIntrinsic(OverflowOpViaIntrinsic::Mul),
2304 OverflowOp::Shl => ViaInputCheck(OverflowOpViaInputCheck::Shl),
2305 OverflowOp::Shr => ViaInputCheck(OverflowOpViaInputCheck::Shr),
2310 enum OverflowCodegen {
2311 ViaIntrinsic(OverflowOpViaIntrinsic),
2312 ViaInputCheck(OverflowOpViaInputCheck),
2315 enum OverflowOpViaInputCheck { Shl, Shr, }
2318 enum OverflowOpViaIntrinsic { Add, Sub, Mul, }
2320 impl OverflowOpViaIntrinsic {
2321 fn to_intrinsic<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>, lhs_ty: Ty) -> ValueRef {
2322 let name = self.to_intrinsic_name(bcx.tcx(), lhs_ty);
2323 bcx.ccx().get_intrinsic(&name)
2325 fn to_intrinsic_name(&self, tcx: &ty::ctxt, ty: Ty) -> &'static str {
2326 use syntax::ast::IntTy::*;
2327 use syntax::ast::UintTy::*;
2328 use middle::ty::{TyInt, TyUint};
2330 let new_sty = match ty.sty {
2331 TyInt(TyIs) => match &tcx.sess.target.target.target_pointer_width[..] {
2332 "32" => TyInt(TyI32),
2333 "64" => TyInt(TyI64),
2334 _ => panic!("unsupported target word size")
2336 TyUint(TyUs) => match &tcx.sess.target.target.target_pointer_width[..] {
2337 "32" => TyUint(TyU32),
2338 "64" => TyUint(TyU64),
2339 _ => panic!("unsupported target word size")
2341 ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
2342 _ => panic!("tried to get overflow intrinsic for {:?} applied to non-int type",
2347 OverflowOpViaIntrinsic::Add => match new_sty {
2348 TyInt(TyI8) => "llvm.sadd.with.overflow.i8",
2349 TyInt(TyI16) => "llvm.sadd.with.overflow.i16",
2350 TyInt(TyI32) => "llvm.sadd.with.overflow.i32",
2351 TyInt(TyI64) => "llvm.sadd.with.overflow.i64",
2353 TyUint(TyU8) => "llvm.uadd.with.overflow.i8",
2354 TyUint(TyU16) => "llvm.uadd.with.overflow.i16",
2355 TyUint(TyU32) => "llvm.uadd.with.overflow.i32",
2356 TyUint(TyU64) => "llvm.uadd.with.overflow.i64",
2358 _ => unreachable!(),
2360 OverflowOpViaIntrinsic::Sub => match new_sty {
2361 TyInt(TyI8) => "llvm.ssub.with.overflow.i8",
2362 TyInt(TyI16) => "llvm.ssub.with.overflow.i16",
2363 TyInt(TyI32) => "llvm.ssub.with.overflow.i32",
2364 TyInt(TyI64) => "llvm.ssub.with.overflow.i64",
2366 TyUint(TyU8) => "llvm.usub.with.overflow.i8",
2367 TyUint(TyU16) => "llvm.usub.with.overflow.i16",
2368 TyUint(TyU32) => "llvm.usub.with.overflow.i32",
2369 TyUint(TyU64) => "llvm.usub.with.overflow.i64",
2371 _ => unreachable!(),
2373 OverflowOpViaIntrinsic::Mul => match new_sty {
2374 TyInt(TyI8) => "llvm.smul.with.overflow.i8",
2375 TyInt(TyI16) => "llvm.smul.with.overflow.i16",
2376 TyInt(TyI32) => "llvm.smul.with.overflow.i32",
2377 TyInt(TyI64) => "llvm.smul.with.overflow.i64",
2379 TyUint(TyU8) => "llvm.umul.with.overflow.i8",
2380 TyUint(TyU16) => "llvm.umul.with.overflow.i16",
2381 TyUint(TyU32) => "llvm.umul.with.overflow.i32",
2382 TyUint(TyU64) => "llvm.umul.with.overflow.i64",
2384 _ => unreachable!(),
2389 fn build_intrinsic_call<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>,
2390 info: NodeIdAndSpan,
2391 lhs_t: Ty<'tcx>, lhs: ValueRef,
2393 binop_debug_loc: DebugLoc)
2394 -> (Block<'blk, 'tcx>, ValueRef) {
2395 let llfn = self.to_intrinsic(bcx, lhs_t);
2397 let val = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
2398 let result = ExtractValue(bcx, val, 0); // iN operation result
2399 let overflow = ExtractValue(bcx, val, 1); // i1 "did it overflow?"
2401 let cond = ICmp(bcx, llvm::IntEQ, overflow, C_integral(Type::i1(bcx.ccx()), 1, false),
2404 let expect = bcx.ccx().get_intrinsic(&"llvm.expect.i1");
2405 Call(bcx, expect, &[cond, C_integral(Type::i1(bcx.ccx()), 0, false)],
2406 None, binop_debug_loc);
2409 base::with_cond(bcx, cond, |bcx|
2410 controlflow::trans_fail(bcx, info,
2411 InternedString::new("arithmetic operation overflowed")));
2417 impl OverflowOpViaInputCheck {
2418 fn build_with_input_check<'blk, 'tcx>(&self,
2419 bcx: Block<'blk, 'tcx>,
2420 info: NodeIdAndSpan,
2424 binop_debug_loc: DebugLoc)
2425 -> (Block<'blk, 'tcx>, ValueRef)
2427 let lhs_llty = val_ty(lhs);
2428 let rhs_llty = val_ty(rhs);
2430 // Panic if any bits are set outside of bits that we always
2433 // Note that the mask's value is derived from the LHS type
2434 // (since that is where the 32/64 distinction is relevant) but
2435 // the mask's type must match the RHS type (since they will
2436 // both be fed into a and-binop)
2437 let invert_mask = shift_mask_val(bcx, lhs_llty, rhs_llty, true);
2439 let outer_bits = And(bcx, rhs, invert_mask, binop_debug_loc);
2440 let cond = build_nonzero_check(bcx, outer_bits, binop_debug_loc);
2441 let result = match *self {
2442 OverflowOpViaInputCheck::Shl =>
2443 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2444 OverflowOpViaInputCheck::Shr =>
2445 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2448 base::with_cond(bcx, cond, |bcx|
2449 controlflow::trans_fail(bcx, info,
2450 InternedString::new("shift operation overflowed")));
2456 fn shift_mask_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2459 invert: bool) -> ValueRef {
2460 let kind = llty.kind();
2462 TypeKind::Integer => {
2463 // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
2464 let val = llty.int_width() - 1;
2466 C_integral(mask_llty, !val, true)
2468 C_integral(mask_llty, val, false)
2471 TypeKind::Vector => {
2472 let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
2473 VectorSplat(bcx, mask_llty.vector_length(), mask)
2475 _ => panic!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
2479 // Check if an integer or vector contains a nonzero element.
2480 fn build_nonzero_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2482 binop_debug_loc: DebugLoc) -> ValueRef {
2483 let llty = val_ty(value);
2484 let kind = llty.kind();
2486 TypeKind::Integer => ICmp(bcx, llvm::IntNE, value, C_null(llty), binop_debug_loc),
2487 TypeKind::Vector => {
2488 // Check if any elements of the vector are nonzero by treating
2489 // it as a wide integer and checking if the integer is nonzero.
2490 let width = llty.vector_length() as u64 * llty.element_type().int_width();
2491 let int_value = BitCast(bcx, value, Type::ix(bcx.ccx(), width));
2492 build_nonzero_check(bcx, int_value, binop_debug_loc)
2494 _ => panic!("build_nonzero_check: expected Integer or Vector, found {:?}", kind),
2498 // To avoid UB from LLVM, these two functions mask RHS with an
2499 // appropriate mask unconditionally (i.e. the fallback behavior for
2500 // all shifts). For 32- and 64-bit types, this matches the semantics
2501 // of Java. (See related discussion on #1877 and #10183.)
2503 fn build_unchecked_lshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2506 binop_debug_loc: DebugLoc) -> ValueRef {
2507 let rhs = base::cast_shift_expr_rhs(bcx, ast::BinOp_::BiShl, lhs, rhs);
2508 // #1877, #10183: Ensure that input is always valid
2509 let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2510 Shl(bcx, lhs, rhs, binop_debug_loc)
2513 fn build_unchecked_rshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2517 binop_debug_loc: DebugLoc) -> ValueRef {
2518 let rhs = base::cast_shift_expr_rhs(bcx, ast::BinOp_::BiShr, lhs, rhs);
2519 // #1877, #10183: Ensure that input is always valid
2520 let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2521 let is_signed = lhs_t.is_signed();
2523 AShr(bcx, lhs, rhs, binop_debug_loc)
2525 LShr(bcx, lhs, rhs, binop_debug_loc)
2529 fn shift_mask_rhs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2531 debug_loc: DebugLoc) -> ValueRef {
2532 let rhs_llty = val_ty(rhs);
2533 And(bcx, rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false), debug_loc)
2536 fn with_overflow_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, oop: OverflowOp, info: NodeIdAndSpan,
2537 lhs_t: Ty<'tcx>, lhs: ValueRef,
2539 binop_debug_loc: DebugLoc)
2540 -> (Block<'blk, 'tcx>, ValueRef) {
2541 if bcx.unreachable.get() { return (bcx, _Undef(lhs)); }
2542 if bcx.ccx().check_overflow() {
2544 match oop.codegen_strategy() {
2545 OverflowCodegen::ViaIntrinsic(oop) =>
2546 oop.build_intrinsic_call(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2547 OverflowCodegen::ViaInputCheck(oop) =>
2548 oop.build_with_input_check(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2551 let res = match oop {
2552 OverflowOp::Add => Add(bcx, lhs, rhs, binop_debug_loc),
2553 OverflowOp::Sub => Sub(bcx, lhs, rhs, binop_debug_loc),
2554 OverflowOp::Mul => Mul(bcx, lhs, rhs, binop_debug_loc),
2557 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2559 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2565 /// We categorize expressions into three kinds. The distinction between
2566 /// lvalue/rvalue is fundamental to the language. The distinction between the
2567 /// two kinds of rvalues is an artifact of trans which reflects how we will
2568 /// generate code for that kind of expression. See trans/expr.rs for more
2570 #[derive(Copy, Clone)]
2578 fn expr_kind(tcx: &ty::ctxt, expr: &ast::Expr) -> ExprKind {
2579 if tcx.is_method_call(expr.id) {
2580 // Overloaded operations are generally calls, and hence they are
2581 // generated via DPS, but there are a few exceptions:
2582 return match expr.node {
2583 // `a += b` has a unit result.
2584 ast::ExprAssignOp(..) => ExprKind::RvalueStmt,
2586 // the deref method invoked for `*a` always yields an `&T`
2587 ast::ExprUnary(ast::UnDeref, _) => ExprKind::Lvalue,
2589 // the index method invoked for `a[i]` always yields an `&T`
2590 ast::ExprIndex(..) => ExprKind::Lvalue,
2592 // in the general case, result could be any type, use DPS
2593 _ => ExprKind::RvalueDps
2598 ast::ExprPath(..) => {
2599 match tcx.resolve_expr(expr) {
2600 def::DefStruct(_) | def::DefVariant(..) => {
2601 if let ty::TyBareFn(..) = tcx.node_id_to_type(expr.id).sty {
2603 ExprKind::RvalueDatum
2609 // Special case: A unit like struct's constructor must be called without () at the
2610 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
2611 // of unit structs this is should not be interpreted as function pointer but as
2612 // call to the constructor.
2613 def::DefFn(_, true) => ExprKind::RvalueDps,
2615 // Fn pointers are just scalar values.
2616 def::DefFn(..) | def::DefMethod(..) => ExprKind::RvalueDatum,
2618 // Note: there is actually a good case to be made that
2619 // DefArg's, particularly those of immediate type, ought to
2620 // considered rvalues.
2621 def::DefStatic(..) |
2623 def::DefLocal(..) => ExprKind::Lvalue,
2626 def::DefAssociatedConst(..) => ExprKind::RvalueDatum,
2631 &format!("uncategorized def for expr {}: {:?}",
2638 ast::ExprUnary(ast::UnDeref, _) |
2639 ast::ExprField(..) |
2640 ast::ExprTupField(..) |
2641 ast::ExprIndex(..) => {
2646 ast::ExprMethodCall(..) |
2647 ast::ExprStruct(..) |
2648 ast::ExprRange(..) |
2651 ast::ExprMatch(..) |
2652 ast::ExprClosure(..) |
2653 ast::ExprBlock(..) |
2654 ast::ExprRepeat(..) |
2655 ast::ExprVec(..) => {
2659 ast::ExprIfLet(..) => {
2660 tcx.sess.span_bug(expr.span, "non-desugared ExprIfLet");
2662 ast::ExprWhileLet(..) => {
2663 tcx.sess.span_bug(expr.span, "non-desugared ExprWhileLet");
2666 ast::ExprForLoop(..) => {
2667 tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
2670 ast::ExprLit(ref lit) if ast_util::lit_is_str(&**lit) => {
2674 ast::ExprBreak(..) |
2675 ast::ExprAgain(..) |
2677 ast::ExprWhile(..) |
2679 ast::ExprAssign(..) |
2680 ast::ExprInlineAsm(..) |
2681 ast::ExprAssignOp(..) => {
2682 ExprKind::RvalueStmt
2685 ast::ExprLit(_) | // Note: LitStr is carved out above
2686 ast::ExprUnary(..) |
2687 ast::ExprBox(None, _) |
2688 ast::ExprAddrOf(..) |
2689 ast::ExprBinary(..) |
2690 ast::ExprCast(..) => {
2691 ExprKind::RvalueDatum
2694 ast::ExprBox(Some(ref place), _) => {
2695 // Special case `Box<T>` for now:
2696 let def_id = match tcx.def_map.borrow().get(&place.id) {
2697 Some(def) => def.def_id(),
2698 None => panic!("no def for place"),
2700 if tcx.lang_items.exchange_heap() == Some(def_id) {
2701 ExprKind::RvalueDatum
2707 ast::ExprParen(ref e) => expr_kind(tcx, &**e),
2709 ast::ExprMac(..) => {
2712 "macro expression remains after expansion");