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};
67 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
71 use trans::monomorphize;
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;
86 use std::iter::repeat;
91 // These are passed around by the code generating functions to track the
92 // destination of a computation's value.
94 #[derive(Copy, Clone, PartialEq)]
101 pub fn to_string(&self, ccx: &CrateContext) -> String {
103 SaveIn(v) => format!("SaveIn({})", ccx.tn().val_to_string(v)),
104 Ignore => "Ignore".to_string()
109 /// This function is equivalent to `trans(bcx, expr).store_to_dest(dest)` but it may generate
110 /// better optimized LLVM code.
111 pub fn trans_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
114 -> Block<'blk, 'tcx> {
117 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
119 if bcx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
120 // use trans, which may be less efficient but
121 // which will perform the adjustments:
122 let datum = unpack_datum!(bcx, trans(bcx, expr));
123 return datum.store_to_dest(bcx, dest, expr.id);
126 let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
127 if !qualif.intersects(
128 check_const::ConstQualif::NOT_CONST |
129 check_const::ConstQualif::NEEDS_DROP
131 if !qualif.intersects(check_const::ConstQualif::PREFER_IN_PLACE) {
132 if let SaveIn(lldest) = dest {
133 let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
134 bcx.fcx.param_substs);
135 // Cast pointer to destination, because constants
136 // have different types.
137 let lldest = PointerCast(bcx, lldest, val_ty(global));
138 memcpy_ty(bcx, lldest, global, expr_ty_adjusted(bcx, expr));
141 // Even if we don't have a value to emit, and the expression
142 // doesn't have any side-effects, we still have to translate the
143 // body of any closures.
144 // FIXME: Find a better way of handling this case.
146 // The only way we're going to see a `const` at this point is if
147 // it prefers in-place instantiation, likely because it contains
148 // `[x; N]` somewhere within.
150 ast::ExprPath(..) => {
151 match bcx.def(expr.id) {
152 def::DefConst(did) => {
153 let const_expr = consts::get_const_expr(bcx.ccx(), did, expr);
154 // Temporarily get cleanup scopes out of the way,
155 // as they require sub-expressions to be contained
156 // inside the current AST scope.
157 // These should record no cleanups anyways, `const`
158 // can't have destructors.
159 let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
161 // Lock emitted debug locations to the location of
162 // the constant reference expression.
163 debuginfo::with_source_location_override(bcx.fcx,
166 bcx = trans_into(bcx, const_expr, dest)
168 let scopes = mem::replace(&mut *bcx.fcx.scopes.borrow_mut(),
170 assert!(scopes.is_empty());
181 debug!("trans_into() expr={:?}", expr);
183 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
187 bcx.fcx.push_ast_cleanup_scope(cleanup_debug_loc);
189 let kind = expr_kind(bcx.tcx(), expr);
191 ExprKind::Lvalue | ExprKind::RvalueDatum => {
192 trans_unadjusted(bcx, expr).store_to_dest(dest, expr.id)
194 ExprKind::RvalueDps => {
195 trans_rvalue_dps_unadjusted(bcx, expr, dest)
197 ExprKind::RvalueStmt => {
198 trans_rvalue_stmt_unadjusted(bcx, expr)
202 bcx.fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id)
205 /// Translates an expression, returning a datum (and new block) encapsulating the result. When
206 /// possible, it is preferred to use `trans_into`, as that may avoid creating a temporary on the
208 pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
210 -> DatumBlock<'blk, 'tcx, Expr> {
211 debug!("trans(expr={:?})", expr);
215 let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap();
216 let adjusted_global = !qualif.intersects(check_const::ConstQualif::NON_STATIC_BORROWS);
217 let global = if !qualif.intersects(
218 check_const::ConstQualif::NOT_CONST |
219 check_const::ConstQualif::NEEDS_DROP
221 let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif,
222 bcx.fcx.param_substs);
224 if qualif.intersects(check_const::ConstQualif::HAS_STATIC_BORROWS) {
225 // Is borrowed as 'static, must return lvalue.
227 // Cast pointer to global, because constants have different types.
228 let const_ty = expr_ty_adjusted(bcx, expr);
229 let llty = type_of::type_of(bcx.ccx(), const_ty);
230 let global = PointerCast(bcx, global, llty.ptr_to());
231 let datum = Datum::new(global, const_ty, Lvalue);
232 return DatumBlock::new(bcx, datum.to_expr_datum());
235 // Otherwise, keep around and perform adjustments, if needed.
236 let const_ty = if adjusted_global {
237 expr_ty_adjusted(bcx, expr)
242 // This could use a better heuristic.
243 Some(if type_is_immediate(bcx.ccx(), const_ty) {
244 // Cast pointer to global, because constants have different types.
245 let llty = type_of::type_of(bcx.ccx(), const_ty);
246 let global = PointerCast(bcx, global, llty.ptr_to());
247 // Maybe just get the value directly, instead of loading it?
248 immediate_rvalue(load_ty(bcx, global, const_ty), const_ty)
250 let llty = type_of::type_of(bcx.ccx(), const_ty);
251 // HACK(eddyb) get around issues with lifetime intrinsics.
252 let scratch = alloca_no_lifetime(bcx, llty, "const");
253 let lldest = if !const_ty.is_structural() {
254 // Cast pointer to slot, because constants have different types.
255 PointerCast(bcx, scratch, val_ty(global))
257 // In this case, memcpy_ty calls llvm.memcpy after casting both
258 // source and destination to i8*, so we don't need any casts.
261 memcpy_ty(bcx, lldest, global, const_ty);
262 Datum::new(scratch, const_ty, Rvalue::new(ByRef))
268 let cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
272 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
273 let datum = match global {
274 Some(rvalue) => rvalue.to_expr_datum(),
275 None => unpack_datum!(bcx, trans_unadjusted(bcx, expr))
277 let datum = if adjusted_global {
278 datum // trans::consts already performed adjustments.
280 unpack_datum!(bcx, apply_adjustments(bcx, expr, datum))
282 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, expr.id);
283 return DatumBlock::new(bcx, datum);
286 pub fn get_len(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
287 GEPi(bcx, fat_ptr, &[0, abi::FAT_PTR_EXTRA])
290 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
291 GEPi(bcx, fat_ptr, &[0, abi::FAT_PTR_ADDR])
294 pub fn copy_fat_ptr(bcx: Block, src_ptr: ValueRef, dst_ptr: ValueRef) {
295 Store(bcx, Load(bcx, get_dataptr(bcx, src_ptr)), get_dataptr(bcx, dst_ptr));
296 Store(bcx, Load(bcx, get_len(bcx, src_ptr)), get_len(bcx, dst_ptr));
299 /// Retrieve the information we are losing (making dynamic) in an unsizing
302 /// The `old_info` argument is a bit funny. It is intended for use
303 /// in an upcast, where the new vtable for an object will be drived
304 /// from the old one.
305 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
308 old_info: Option<ValueRef>,
309 param_substs: &'tcx Substs<'tcx>)
311 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
312 match (&source.sty, &target.sty) {
313 (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
314 (&ty::TyTrait(_), &ty::TyTrait(_)) => {
315 // For now, upcasts are limited to changes in marker
316 // traits, and hence never actually require an actual
317 // change to the vtable.
318 old_info.expect("unsized_info: missing old info for trait upcast")
320 (_, &ty::TyTrait(box ty::TraitTy { ref principal, .. })) => {
321 // Note that we preserve binding levels here:
322 let substs = principal.0.substs.with_self_ty(source).erase_regions();
323 let substs = ccx.tcx().mk_substs(substs);
324 let trait_ref = ty::Binder(ty::TraitRef { def_id: principal.def_id(),
326 consts::ptrcast(meth::get_vtable(ccx, trait_ref, param_substs),
327 Type::vtable_ptr(ccx))
329 _ => ccx.sess().bug(&format!("unsized_info: invalid unsizing {:?} -> {:?}",
335 /// Helper for trans that apply adjustments from `expr` to `datum`, which should be the unadjusted
336 /// translation of `expr`.
337 fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
339 datum: Datum<'tcx, Expr>)
340 -> DatumBlock<'blk, 'tcx, Expr>
343 let mut datum = datum;
344 let adjustment = match bcx.tcx().tables.borrow().adjustments.get(&expr.id).cloned() {
346 return DatumBlock::new(bcx, datum);
350 debug!("unadjusted datum for expr {:?}: {} adjustment={:?}",
352 datum.to_string(bcx.ccx()),
355 AdjustReifyFnPointer => {
356 // FIXME(#19925) once fn item types are
357 // zero-sized, we'll need to do something here
359 AdjustUnsafeFnPointer => {
360 // purely a type-level thing
362 AdjustDerefRef(ref adj) => {
363 let skip_reborrows = if adj.autoderefs == 1 && adj.autoref.is_some() {
364 // We are a bit paranoid about adjustments and thus might have a re-
365 // borrow here which merely derefs and then refs again (it might have
366 // a different region or mutability, but we don't care here).
368 // Don't skip a conversion from Box<T> to &T, etc.
370 let method_call = MethodCall::autoderef(expr.id, 0);
371 if bcx.tcx().tables.borrow().method_map.contains_key(&method_call) {
372 // Don't skip an overloaded deref.
384 if adj.autoderefs > skip_reborrows {
386 let lval = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "auto_deref", expr.id));
387 datum = unpack_datum!(bcx, deref_multiple(bcx, expr,
388 lval.to_expr_datum(),
389 adj.autoderefs - skip_reborrows));
392 // (You might think there is a more elegant way to do this than a
393 // skip_reborrows bool, but then you remember that the borrow checker exists).
394 if skip_reborrows == 0 && adj.autoref.is_some() {
395 if !type_is_sized(bcx.tcx(), datum.ty) {
397 let lval = unpack_datum!(bcx,
398 datum.to_lvalue_datum(bcx, "ref_fat_ptr", expr.id));
399 datum = unpack_datum!(bcx, ref_fat_ptr(bcx, lval));
401 datum = unpack_datum!(bcx, auto_ref(bcx, datum, expr));
405 if let Some(target) = adj.unsize {
406 // We do not arrange cleanup ourselves; if we already are an
407 // L-value, then cleanup will have already been scheduled (and
408 // the `datum.to_rvalue_datum` call below will emit code to zero
409 // the drop flag when moving out of the L-value). If we are an
410 // R-value, then we do not need to schedule cleanup.
411 let source_datum = unpack_datum!(bcx,
412 datum.to_rvalue_datum(bcx, "__coerce_source"));
414 let target = bcx.monomorphize(&target);
415 let llty = type_of::type_of(bcx.ccx(), target);
417 // HACK(eddyb) get around issues with lifetime intrinsics.
418 let scratch = alloca_no_lifetime(bcx, llty, "__coerce_target");
419 let target_datum = Datum::new(scratch, target,
421 bcx = coerce_unsized(bcx, expr.span, source_datum, target_datum);
422 datum = Datum::new(scratch, target,
423 RvalueExpr(Rvalue::new(ByRef)));
427 debug!("after adjustments, datum={}", datum.to_string(bcx.ccx()));
428 DatumBlock::new(bcx, datum)
431 fn coerce_unsized<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
433 source: Datum<'tcx, Rvalue>,
434 target: Datum<'tcx, Rvalue>)
435 -> Block<'blk, 'tcx> {
437 debug!("coerce_unsized({} -> {})",
438 source.to_string(bcx.ccx()),
439 target.to_string(bcx.ccx()));
441 match (&source.ty.sty, &target.ty.sty) {
442 (&ty::TyBox(a), &ty::TyBox(b)) |
443 (&ty::TyRef(_, ty::mt { ty: a, .. }), &ty::TyRef(_, ty::mt { ty: b, .. })) |
444 (&ty::TyRef(_, ty::mt { ty: a, .. }), &ty::TyRawPtr(ty::mt { ty: b, .. })) |
445 (&ty::TyRawPtr(ty::mt { ty: a, .. }), &ty::TyRawPtr(ty::mt { ty: b, .. })) => {
446 let (inner_source, inner_target) = (a, b);
448 let (base, old_info) = if !type_is_sized(bcx.tcx(), inner_source) {
449 // Normally, the source is a thin pointer and we are
450 // adding extra info to make a fat pointer. The exception
451 // is when we are upcasting an existing object fat pointer
452 // to use a different vtable. In that case, we want to
453 // load out the original data pointer so we can repackage
455 (Load(bcx, get_dataptr(bcx, source.val)),
456 Some(Load(bcx, get_len(bcx, source.val))))
458 let val = if source.kind.is_by_ref() {
459 load_ty(bcx, source.val, source.ty)
466 let info = unsized_info(bcx.ccx(), inner_source, inner_target,
467 old_info, bcx.fcx.param_substs);
469 // Compute the base pointer. This doesn't change the pointer value,
470 // but merely its type.
471 let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), inner_target).ptr_to();
472 let base = PointerCast(bcx, base, ptr_ty);
474 Store(bcx, base, get_dataptr(bcx, target.val));
475 Store(bcx, info, get_len(bcx, target.val));
478 // This can be extended to enums and tuples in the future.
479 // (&ty::TyEnum(def_id_a, _), &ty::TyEnum(def_id_b, _)) |
480 (&ty::TyStruct(def_id_a, _), &ty::TyStruct(def_id_b, _)) => {
481 assert_eq!(def_id_a, def_id_b);
483 // The target is already by-ref because it's to be written to.
484 let source = unpack_datum!(bcx, source.to_ref_datum(bcx));
485 assert!(target.kind.is_by_ref());
487 let trait_substs = Substs::erased(VecPerParamSpace::new(vec![target.ty],
490 let trait_ref = ty::Binder(ty::TraitRef {
491 def_id: langcall(bcx, Some(span), "coercion",
492 CoerceUnsizedTraitLangItem),
493 substs: bcx.tcx().mk_substs(trait_substs)
496 let kind = match fulfill_obligation(bcx.ccx(), span, trait_ref) {
497 traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
498 bcx.tcx().custom_coerce_unsized_kind(impl_def_id)
501 bcx.sess().span_bug(span, &format!("invalid CoerceUnsized vtable: {:?}",
506 let repr_source = adt::represent_type(bcx.ccx(), source.ty);
507 let src_fields = match &*repr_source {
508 &adt::Repr::Univariant(ref s, _) => &s.fields,
509 _ => bcx.sess().span_bug(span,
510 &format!("Non univariant struct? (repr_source: {:?})",
513 let repr_target = adt::represent_type(bcx.ccx(), target.ty);
514 let target_fields = match &*repr_target {
515 &adt::Repr::Univariant(ref s, _) => &s.fields,
516 _ => bcx.sess().span_bug(span,
517 &format!("Non univariant struct? (repr_target: {:?})",
521 let coerce_index = match kind {
522 ty::CustomCoerceUnsized::Struct(i) => i
524 assert!(coerce_index < src_fields.len() && src_fields.len() == target_fields.len());
526 let iter = src_fields.iter().zip(target_fields).enumerate();
527 for (i, (src_ty, target_ty)) in iter {
528 let ll_source = adt::trans_field_ptr(bcx, &repr_source, source.val, 0, i);
529 let ll_target = adt::trans_field_ptr(bcx, &repr_target, target.val, 0, i);
531 // If this is the field we need to coerce, recurse on it.
532 if i == coerce_index {
533 coerce_unsized(bcx, span,
534 Datum::new(ll_source, src_ty,
536 Datum::new(ll_target, target_ty,
537 Rvalue::new(ByRef)));
539 // Otherwise, simply copy the data from the source.
540 assert_eq!(src_ty, target_ty);
541 memcpy_ty(bcx, ll_target, ll_source, src_ty);
545 _ => bcx.sess().bug(&format!("coerce_unsized: invalid coercion {:?} -> {:?}",
552 /// Translates an expression in "lvalue" mode -- meaning that it returns a reference to the memory
553 /// that the expr represents.
555 /// If this expression is an rvalue, this implies introducing a temporary. In other words,
556 /// something like `x().f` is translated into roughly the equivalent of
558 /// { tmp = x(); tmp.f }
559 pub fn trans_to_lvalue<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
562 -> DatumBlock<'blk, 'tcx, Lvalue> {
564 let datum = unpack_datum!(bcx, trans(bcx, expr));
565 return datum.to_lvalue_datum(bcx, name, expr.id);
568 /// A version of `trans` that ignores adjustments. You almost certainly do not want to call this
570 fn trans_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
572 -> DatumBlock<'blk, 'tcx, Expr> {
575 debug!("trans_unadjusted(expr={:?})", expr);
576 let _indenter = indenter();
578 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
580 return match expr_kind(bcx.tcx(), expr) {
581 ExprKind::Lvalue | ExprKind::RvalueDatum => {
582 let datum = unpack_datum!(bcx, {
583 trans_datum_unadjusted(bcx, expr)
586 DatumBlock {bcx: bcx, datum: datum}
589 ExprKind::RvalueStmt => {
590 bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
591 nil(bcx, expr_ty(bcx, expr))
594 ExprKind::RvalueDps => {
595 let ty = expr_ty(bcx, expr);
596 if type_is_zero_size(bcx.ccx(), ty) {
597 bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
600 let scratch = rvalue_scratch_datum(bcx, ty, "");
601 bcx = trans_rvalue_dps_unadjusted(
602 bcx, expr, SaveIn(scratch.val));
604 // Note: this is not obviously a good idea. It causes
605 // immediate values to be loaded immediately after a
606 // return from a call or other similar expression,
607 // which in turn leads to alloca's having shorter
608 // lifetimes and hence larger stack frames. However,
609 // in turn it can lead to more register pressure.
610 // Still, in practice it seems to increase
611 // performance, since we have fewer problems with
613 let scratch = unpack_datum!(
614 bcx, scratch.to_appropriate_datum(bcx));
616 DatumBlock::new(bcx, scratch.to_expr_datum())
621 fn nil<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ty: Ty<'tcx>)
622 -> DatumBlock<'blk, 'tcx, Expr> {
623 let llval = C_undef(type_of::type_of(bcx.ccx(), ty));
624 let datum = immediate_rvalue(llval, ty);
625 DatumBlock::new(bcx, datum.to_expr_datum())
629 fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
631 -> DatumBlock<'blk, 'tcx, Expr> {
634 let _icx = push_ctxt("trans_datum_unadjusted");
637 ast::ExprParen(ref e) => {
640 ast::ExprPath(..) => {
641 trans_def(bcx, expr, bcx.def(expr.id))
643 ast::ExprField(ref base, ident) => {
644 trans_rec_field(bcx, &**base, ident.node.name)
646 ast::ExprTupField(ref base, idx) => {
647 trans_rec_tup_field(bcx, &**base, idx.node)
649 ast::ExprIndex(ref base, ref idx) => {
650 trans_index(bcx, expr, &**base, &**idx, MethodCall::expr(expr.id))
652 ast::ExprBox(_, ref contents) => {
653 // Special case for `Box<T>`
654 let box_ty = expr_ty(bcx, expr);
655 let contents_ty = expr_ty(bcx, &**contents);
658 trans_uniq_expr(bcx, expr, box_ty, &**contents, contents_ty)
660 _ => bcx.sess().span_bug(expr.span,
661 "expected unique box")
665 ast::ExprLit(ref lit) => trans_immediate_lit(bcx, expr, &**lit),
666 ast::ExprBinary(op, ref lhs, ref rhs) => {
667 trans_binary(bcx, expr, op, &**lhs, &**rhs)
669 ast::ExprUnary(op, ref x) => {
670 trans_unary(bcx, expr, op, &**x)
672 ast::ExprAddrOf(_, ref x) => {
674 ast::ExprRepeat(..) | ast::ExprVec(..) => {
675 // Special case for slices.
676 let cleanup_debug_loc =
677 debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(),
681 fcx.push_ast_cleanup_scope(cleanup_debug_loc);
682 let datum = unpack_datum!(
683 bcx, tvec::trans_slice_vec(bcx, expr, &**x));
684 bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, x.id);
685 DatumBlock::new(bcx, datum)
688 trans_addr_of(bcx, expr, &**x)
692 ast::ExprCast(ref val, _) => {
693 // Datum output mode means this is a scalar cast:
694 trans_imm_cast(bcx, &**val, expr.id)
697 bcx.tcx().sess.span_bug(
699 &format!("trans_rvalue_datum_unadjusted reached \
700 fall-through case: {:?}",
706 fn trans_field<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
709 -> DatumBlock<'blk, 'tcx, Expr> where
710 F: FnOnce(&'blk ty::ctxt<'tcx>, &[ty::field<'tcx>]) -> usize,
713 let _icx = push_ctxt("trans_rec_field");
715 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, base, "field"));
716 let bare_ty = base_datum.ty;
717 let repr = adt::represent_type(bcx.ccx(), bare_ty);
718 with_field_tys(bcx.tcx(), bare_ty, None, move |discr, field_tys| {
719 let ix = get_idx(bcx.tcx(), field_tys);
720 let d = base_datum.get_element(
723 |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, ix));
725 if type_is_sized(bcx.tcx(), d.ty) {
726 DatumBlock { datum: d.to_expr_datum(), bcx: bcx }
728 let scratch = rvalue_scratch_datum(bcx, d.ty, "");
729 Store(bcx, d.val, get_dataptr(bcx, scratch.val));
730 let info = Load(bcx, get_len(bcx, base_datum.val));
731 Store(bcx, info, get_len(bcx, scratch.val));
733 // Always generate an lvalue datum, because this pointer doesn't own
734 // the data and cleanup is scheduled elsewhere.
735 DatumBlock::new(bcx, Datum::new(scratch.val, scratch.ty, LvalueExpr))
741 /// Translates `base.field`.
742 fn trans_rec_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
745 -> DatumBlock<'blk, 'tcx, Expr> {
746 trans_field(bcx, base, |tcx, field_tys| tcx.field_idx_strict(field, field_tys))
749 /// Translates `base.<idx>`.
750 fn trans_rec_tup_field<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
753 -> DatumBlock<'blk, 'tcx, Expr> {
754 trans_field(bcx, base, |_, _| idx)
757 fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
758 index_expr: &ast::Expr,
761 method_call: MethodCall)
762 -> DatumBlock<'blk, 'tcx, Expr> {
763 //! Translates `base[idx]`.
765 let _icx = push_ctxt("trans_index");
769 let index_expr_debug_loc = index_expr.debug_loc();
771 // Check for overloaded index.
772 let method_ty = ccx.tcx()
777 .map(|method| method.ty);
778 let elt_datum = match method_ty {
780 let method_ty = monomorphize_type(bcx, method_ty);
782 let base_datum = unpack_datum!(bcx, trans(bcx, base));
784 // Translate index expression.
785 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
787 let ref_ty = // invoked methods have LB regions instantiated:
788 bcx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
789 let elt_ty = match ref_ty.builtin_deref(true) {
791 bcx.tcx().sess.span_bug(index_expr.span,
792 "index method didn't return a \
793 dereferenceable type?!")
795 Some(elt_tm) => elt_tm.ty,
798 // Overloaded. Evaluate `trans_overloaded_op`, which will
799 // invoke the user's index() method, which basically yields
800 // a `&T` pointer. We can then proceed down the normal
801 // path (below) to dereference that `&T`.
802 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_index_elt");
804 trans_overloaded_op(bcx,
808 Some((ix_datum, idx.id)),
809 Some(SaveIn(scratch.val)),
811 let datum = scratch.to_expr_datum();
812 if type_is_sized(bcx.tcx(), elt_ty) {
813 Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr)
815 Datum::new(datum.val, elt_ty, LvalueExpr)
819 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx,
823 // Translate index expression and cast to a suitable LLVM integer.
824 // Rust is less strict than LLVM in this regard.
825 let ix_datum = unpack_datum!(bcx, trans(bcx, idx));
826 let ix_val = ix_datum.to_llscalarish(bcx);
827 let ix_size = machine::llbitsize_of_real(bcx.ccx(),
829 let int_size = machine::llbitsize_of_real(bcx.ccx(),
832 if ix_size < int_size {
833 if expr_ty(bcx, idx).is_signed() {
834 SExt(bcx, ix_val, ccx.int_type())
835 } else { ZExt(bcx, ix_val, ccx.int_type()) }
836 } else if ix_size > int_size {
837 Trunc(bcx, ix_val, ccx.int_type())
843 let unit_ty = base_datum.ty.sequence_element_type(bcx.tcx());
845 let (base, len) = base_datum.get_vec_base_and_len(bcx);
847 debug!("trans_index: base {}", bcx.val_to_string(base));
848 debug!("trans_index: len {}", bcx.val_to_string(len));
850 let bounds_check = ICmp(bcx,
854 index_expr_debug_loc);
855 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
856 let expected = Call(bcx,
858 &[bounds_check, C_bool(ccx, false)],
860 index_expr_debug_loc);
861 bcx = with_cond(bcx, expected, |bcx| {
862 controlflow::trans_fail_bounds_check(bcx,
863 expr_info(index_expr),
867 let elt = InBoundsGEP(bcx, base, &[ix_val]);
868 let elt = PointerCast(bcx, elt, type_of::type_of(ccx, unit_ty).ptr_to());
869 Datum::new(elt, unit_ty, LvalueExpr)
873 DatumBlock::new(bcx, elt_datum)
876 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
877 ref_expr: &ast::Expr,
879 -> DatumBlock<'blk, 'tcx, Expr> {
880 //! Translates a reference to a path.
882 let _icx = push_ctxt("trans_def_lvalue");
884 def::DefFn(..) | def::DefMethod(..) |
885 def::DefStruct(_) | def::DefVariant(..) => {
886 let datum = trans_def_fn_unadjusted(bcx.ccx(), ref_expr, def,
887 bcx.fcx.param_substs);
888 DatumBlock::new(bcx, datum.to_expr_datum())
890 def::DefStatic(did, _) => {
891 // There are two things that may happen here:
892 // 1) If the static item is defined in this crate, it will be
893 // translated using `get_item_val`, and we return a pointer to
895 // 2) If the static item is defined in another crate then we add
896 // (or reuse) a declaration of an external global, and return a
898 let const_ty = expr_ty(bcx, ref_expr);
900 // For external constants, we don't inline.
901 let val = if did.krate == ast::LOCAL_CRATE {
904 // The LLVM global has the type of its initializer,
905 // which may not be equal to the enum's type for
907 let val = base::get_item_val(bcx.ccx(), did.node);
908 let pty = type_of::type_of(bcx.ccx(), const_ty).ptr_to();
909 PointerCast(bcx, val, pty)
912 base::get_extern_const(bcx.ccx(), did, const_ty)
914 DatumBlock::new(bcx, Datum::new(val, const_ty, LvalueExpr))
916 def::DefConst(_) => {
917 bcx.sess().span_bug(ref_expr.span,
918 "constant expression should not reach expr::trans_def")
921 DatumBlock::new(bcx, trans_local_var(bcx, def).to_expr_datum())
926 fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
928 -> Block<'blk, 'tcx> {
930 let _icx = push_ctxt("trans_rvalue_stmt");
932 if bcx.unreachable.get() {
936 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
939 ast::ExprParen(ref e) => {
940 trans_into(bcx, &**e, Ignore)
942 ast::ExprBreak(label_opt) => {
943 controlflow::trans_break(bcx, expr, label_opt)
945 ast::ExprAgain(label_opt) => {
946 controlflow::trans_cont(bcx, expr, label_opt)
948 ast::ExprRet(ref ex) => {
949 // Check to see if the return expression itself is reachable.
950 // This can occur when the inner expression contains a return
951 let reachable = if let Some(ref cfg) = bcx.fcx.cfg {
952 cfg.node_is_reachable(expr.id)
958 controlflow::trans_ret(bcx, expr, ex.as_ref().map(|e| &**e))
960 // If it's not reachable, just translate the inner expression
961 // directly. This avoids having to manage a return slot when
962 // it won't actually be used anyway.
963 if let &Some(ref x) = ex {
964 bcx = trans_into(bcx, &**x, Ignore);
966 // Mark the end of the block as unreachable. Once we get to
967 // a return expression, there's no more we should be doing
973 ast::ExprWhile(ref cond, ref body, _) => {
974 controlflow::trans_while(bcx, expr, &**cond, &**body)
976 ast::ExprLoop(ref body, _) => {
977 controlflow::trans_loop(bcx, expr, &**body)
979 ast::ExprAssign(ref dst, ref src) => {
980 let src_datum = unpack_datum!(bcx, trans(bcx, &**src));
981 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &**dst, "assign"));
983 if bcx.fcx.type_needs_drop(dst_datum.ty) {
984 // If there are destructors involved, make sure we
985 // are copying from an rvalue, since that cannot possible
986 // alias an lvalue. We are concerned about code like:
994 // where e.g. a : Option<Foo> and a.b :
995 // Option<Foo>. In that case, freeing `a` before the
996 // assignment may also free `a.b`!
998 // We could avoid this intermediary with some analysis
999 // to determine whether `dst` may possibly own `src`.
1000 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
1001 let src_datum = unpack_datum!(
1002 bcx, src_datum.to_rvalue_datum(bcx, "ExprAssign"));
1003 bcx = glue::drop_ty(bcx,
1007 src_datum.store_to(bcx, dst_datum.val)
1009 src_datum.store_to(bcx, dst_datum.val)
1012 ast::ExprAssignOp(op, ref dst, ref src) => {
1013 trans_assign_op(bcx, expr, op, &**dst, &**src)
1015 ast::ExprInlineAsm(ref a) => {
1016 asm::trans_inline_asm(bcx, a)
1019 bcx.tcx().sess.span_bug(
1021 &format!("trans_rvalue_stmt_unadjusted reached \
1022 fall-through case: {:?}",
1028 fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1031 -> Block<'blk, 'tcx> {
1032 let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
1034 let tcx = bcx.tcx();
1036 debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
1039 ast::ExprParen(ref e) => {
1040 trans_into(bcx, &**e, dest)
1042 ast::ExprPath(..) => {
1043 trans_def_dps_unadjusted(bcx, expr, bcx.def(expr.id), dest)
1045 ast::ExprIf(ref cond, ref thn, ref els) => {
1046 controlflow::trans_if(bcx, expr.id, &**cond, &**thn, els.as_ref().map(|e| &**e), dest)
1048 ast::ExprMatch(ref discr, ref arms, _) => {
1049 _match::trans_match(bcx, expr, &**discr, &arms[..], dest)
1051 ast::ExprBlock(ref blk) => {
1052 controlflow::trans_block(bcx, &**blk, dest)
1054 ast::ExprStruct(_, ref fields, ref base) => {
1057 base.as_ref().map(|e| &**e),
1060 node_id_type(bcx, expr.id),
1063 ast::ExprRange(ref start, ref end) => {
1064 // FIXME it is just not right that we are synthesising ast nodes in
1066 fn make_field(field_name: &str, expr: P<ast::Expr>) -> ast::Field {
1068 ident: codemap::dummy_spanned(token::str_to_ident(field_name)),
1070 span: codemap::DUMMY_SP,
1074 // A range just desugars into a struct.
1075 // Note that the type of the start and end may not be the same, but
1076 // they should only differ in their lifetime, which should not matter
1078 let (did, fields, ty_params) = match (start, end) {
1079 (&Some(ref start), &Some(ref end)) => {
1081 let fields = vec![make_field("start", start.clone()),
1082 make_field("end", end.clone())];
1083 (tcx.lang_items.range_struct(), fields, vec![node_id_type(bcx, start.id)])
1085 (&Some(ref start), &None) => {
1086 // Desugar to RangeFrom
1087 let fields = vec![make_field("start", start.clone())];
1088 (tcx.lang_items.range_from_struct(), fields, vec![node_id_type(bcx, start.id)])
1090 (&None, &Some(ref end)) => {
1091 // Desugar to RangeTo
1092 let fields = vec![make_field("end", end.clone())];
1093 (tcx.lang_items.range_to_struct(), fields, vec![node_id_type(bcx, end.id)])
1096 // Desugar to RangeFull
1097 (tcx.lang_items.range_full_struct(), vec![], vec![])
1101 if let Some(did) = did {
1102 let substs = Substs::new_type(ty_params, vec![]);
1108 tcx.mk_struct(did, tcx.mk_substs(substs)),
1111 tcx.sess.span_bug(expr.span,
1112 "No lang item for ranges (how did we get this far?)")
1115 ast::ExprTup(ref args) => {
1116 let numbered_fields: Vec<(usize, &ast::Expr)> =
1117 args.iter().enumerate().map(|(i, arg)| (i, &**arg)).collect();
1121 &numbered_fields[..],
1126 ast::ExprLit(ref lit) => {
1128 ast::LitStr(ref s, _) => {
1129 tvec::trans_lit_str(bcx, expr, (*s).clone(), dest)
1134 .span_bug(expr.span,
1135 "trans_rvalue_dps_unadjusted shouldn't be \
1136 translating this type of literal")
1140 ast::ExprVec(..) | ast::ExprRepeat(..) => {
1141 tvec::trans_fixed_vstore(bcx, expr, dest)
1143 ast::ExprClosure(_, ref decl, ref body) => {
1144 let dest = match dest {
1145 SaveIn(lldest) => closure::Dest::SaveIn(bcx, lldest),
1146 Ignore => closure::Dest::Ignore(bcx.ccx())
1148 closure::trans_closure_expr(dest, decl, body, expr.id, bcx.fcx.param_substs)
1151 ast::ExprCall(ref f, ref args) => {
1152 if bcx.tcx().is_method_call(expr.id) {
1153 trans_overloaded_call(bcx,
1159 callee::trans_call(bcx,
1162 callee::ArgExprs(&args[..]),
1166 ast::ExprMethodCall(_, _, ref args) => {
1167 callee::trans_method_call(bcx,
1170 callee::ArgExprs(&args[..]),
1173 ast::ExprBinary(op, ref lhs, ref rhs) => {
1174 // if not overloaded, would be RvalueDatumExpr
1175 let lhs = unpack_datum!(bcx, trans(bcx, &**lhs));
1176 let rhs_datum = unpack_datum!(bcx, trans(bcx, &**rhs));
1177 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), lhs,
1178 Some((rhs_datum, rhs.id)), Some(dest),
1179 !ast_util::is_by_value_binop(op.node)).bcx
1181 ast::ExprUnary(op, ref subexpr) => {
1182 // if not overloaded, would be RvalueDatumExpr
1183 let arg = unpack_datum!(bcx, trans(bcx, &**subexpr));
1184 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id),
1185 arg, None, Some(dest), !ast_util::is_by_value_unop(op)).bcx
1187 ast::ExprIndex(ref base, ref idx) => {
1188 // if not overloaded, would be RvalueDatumExpr
1189 let base = unpack_datum!(bcx, trans(bcx, &**base));
1190 let idx_datum = unpack_datum!(bcx, trans(bcx, &**idx));
1191 trans_overloaded_op(bcx, expr, MethodCall::expr(expr.id), base,
1192 Some((idx_datum, idx.id)), Some(dest), true).bcx
1194 ast::ExprCast(..) => {
1195 // Trait casts used to come this way, now they should be coercions.
1196 bcx.tcx().sess.span_bug(expr.span, "DPS expr_cast (residual trait cast?)")
1198 ast::ExprAssignOp(op, ref dst, ref src) => {
1199 trans_assign_op(bcx, expr, op, &**dst, &**src)
1202 bcx.tcx().sess.span_bug(
1204 &format!("trans_rvalue_dps_unadjusted reached fall-through \
1211 fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1212 ref_expr: &ast::Expr,
1215 -> Block<'blk, 'tcx> {
1216 let _icx = push_ctxt("trans_def_dps_unadjusted");
1218 let lldest = match dest {
1219 SaveIn(lldest) => lldest,
1220 Ignore => { return bcx; }
1224 def::DefVariant(tid, vid, _) => {
1225 let variant_info = bcx.tcx().enum_variant_with_id(tid, vid);
1226 if !variant_info.args.is_empty() {
1228 let llfn = callee::trans_fn_ref(bcx.ccx(), vid,
1229 ExprId(ref_expr.id),
1230 bcx.fcx.param_substs).val;
1231 Store(bcx, llfn, lldest);
1235 let ty = expr_ty(bcx, ref_expr);
1236 let repr = adt::represent_type(bcx.ccx(), ty);
1237 adt::trans_set_discr(bcx, &*repr, lldest,
1238 variant_info.disr_val);
1242 def::DefStruct(_) => {
1243 let ty = expr_ty(bcx, ref_expr);
1245 ty::TyStruct(did, _) if bcx.tcx().has_dtor(did) => {
1246 let repr = adt::represent_type(bcx.ccx(), ty);
1247 adt::trans_set_discr(bcx, &*repr, lldest, 0);
1254 bcx.tcx().sess.span_bug(ref_expr.span, &format!(
1255 "Non-DPS def {:?} referened by {}",
1256 def, bcx.node_id_to_string(ref_expr.id)));
1261 pub fn trans_def_fn_unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1262 ref_expr: &ast::Expr,
1264 param_substs: &'tcx Substs<'tcx>)
1265 -> Datum<'tcx, Rvalue> {
1266 let _icx = push_ctxt("trans_def_datum_unadjusted");
1269 def::DefFn(did, _) |
1270 def::DefStruct(did) | def::DefVariant(_, did, _) |
1271 def::DefMethod(did, def::FromImpl(_)) => {
1272 callee::trans_fn_ref(ccx, did, ExprId(ref_expr.id), param_substs)
1274 def::DefMethod(impl_did, def::FromTrait(trait_did)) => {
1275 meth::trans_static_method_callee(ccx, impl_did,
1276 trait_did, ref_expr.id,
1280 ccx.tcx().sess.span_bug(ref_expr.span, &format!(
1281 "trans_def_fn_unadjusted invoked on: {:?} for {:?}",
1288 /// Translates a reference to a local variable or argument. This always results in an lvalue datum.
1289 pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1291 -> Datum<'tcx, Lvalue> {
1292 let _icx = push_ctxt("trans_local_var");
1295 def::DefUpvar(nid, _) => {
1296 // Can't move upvars, so this is never a ZeroMemLastUse.
1297 let local_ty = node_id_type(bcx, nid);
1298 match bcx.fcx.llupvars.borrow().get(&nid) {
1299 Some(&val) => Datum::new(val, local_ty, Lvalue),
1301 bcx.sess().bug(&format!(
1302 "trans_local_var: no llval for upvar {} found",
1307 def::DefLocal(nid) => {
1308 let datum = match bcx.fcx.lllocals.borrow().get(&nid) {
1311 bcx.sess().bug(&format!(
1312 "trans_local_var: no datum for local/arg {} found",
1316 debug!("take_local(nid={}, v={}, ty={})",
1317 nid, bcx.val_to_string(datum.val), datum.ty);
1321 bcx.sess().unimpl(&format!(
1322 "unsupported def type in trans_local_var: {:?}",
1328 /// Helper for enumerating the field types of structs, enums, or records. The optional node ID here
1329 /// is the node ID of the path identifying the enum variant in use. If none, this cannot possibly
1330 /// an enum variant (so, if it is and `node_id_opt` is none, this function panics).
1331 pub fn with_field_tys<'tcx, R, F>(tcx: &ty::ctxt<'tcx>,
1333 node_id_opt: Option<ast::NodeId>,
1336 F: FnOnce(ty::Disr, &[ty::field<'tcx>]) -> R,
1339 ty::TyStruct(did, substs) => {
1340 let fields = tcx.struct_fields(did, substs);
1341 let fields = monomorphize::normalize_associated_type(tcx, &fields);
1345 ty::TyTuple(ref v) => {
1346 let fields: Vec<_> = v.iter().enumerate().map(|(i, &f)| {
1348 name: token::intern(&i.to_string()),
1351 mutbl: ast::MutImmutable
1358 ty::TyEnum(_, substs) => {
1359 // We want the *variant* ID here, not the enum ID.
1362 tcx.sess.bug(&format!(
1363 "cannot get field types from the enum type {:?} \
1368 let def = tcx.def_map.borrow().get(&node_id).unwrap().full_def();
1370 def::DefVariant(enum_id, variant_id, _) => {
1371 let variant_info = tcx.enum_variant_with_id(enum_id, variant_id);
1372 let fields = tcx.struct_fields(variant_id, substs);
1373 let fields = monomorphize::normalize_associated_type(tcx, &fields);
1374 op(variant_info.disr_val, &fields[..])
1377 tcx.sess.bug("resolve didn't map this expr to a \
1386 tcx.sess.bug(&format!(
1387 "cannot get field types from the type {:?}",
1393 fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1394 fields: &[ast::Field],
1395 base: Option<&ast::Expr>,
1396 expr_span: codemap::Span,
1397 expr_id: ast::NodeId,
1399 dest: Dest) -> Block<'blk, 'tcx> {
1400 let _icx = push_ctxt("trans_rec");
1402 let tcx = bcx.tcx();
1403 with_field_tys(tcx, ty, Some(expr_id), |discr, field_tys| {
1404 let mut need_base: Vec<bool> = repeat(true).take(field_tys.len()).collect();
1406 let numbered_fields = fields.iter().map(|field| {
1408 field_tys.iter().position(|field_ty|
1409 field_ty.name == field.ident.node.name);
1410 let result = match opt_pos {
1412 need_base[i] = false;
1416 tcx.sess.span_bug(field.span,
1417 "Couldn't find field in struct type")
1421 }).collect::<Vec<_>>();
1422 let optbase = match base {
1423 Some(base_expr) => {
1424 let mut leftovers = Vec::new();
1425 for (i, b) in need_base.iter().enumerate() {
1427 leftovers.push((i, field_tys[i].mt.ty));
1430 Some(StructBaseInfo {expr: base_expr,
1431 fields: leftovers })
1434 if need_base.iter().any(|b| *b) {
1435 tcx.sess.span_bug(expr_span, "missing fields and no base expr")
1447 DebugLoc::At(expr_id, expr_span))
1451 /// Information that `trans_adt` needs in order to fill in the fields
1452 /// of a struct copied from a base struct (e.g., from an expression
1453 /// like `Foo { a: b, ..base }`.
1455 /// Note that `fields` may be empty; the base expression must always be
1456 /// evaluated for side-effects.
1457 pub struct StructBaseInfo<'a, 'tcx> {
1458 /// The base expression; will be evaluated after all explicit fields.
1459 expr: &'a ast::Expr,
1460 /// The indices of fields to copy paired with their types.
1461 fields: Vec<(usize, Ty<'tcx>)>
1464 /// Constructs an ADT instance:
1466 /// - `fields` should be a list of field indices paired with the
1467 /// expression to store into that field. The initializers will be
1468 /// evaluated in the order specified by `fields`.
1470 /// - `optbase` contains information on the base struct (if any) from
1471 /// which remaining fields are copied; see comments on `StructBaseInfo`.
1472 pub fn trans_adt<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1475 fields: &[(usize, &ast::Expr)],
1476 optbase: Option<StructBaseInfo<'a, 'tcx>>,
1478 debug_location: DebugLoc)
1479 -> Block<'blk, 'tcx> {
1480 let _icx = push_ctxt("trans_adt");
1482 let repr = adt::represent_type(bcx.ccx(), ty);
1484 debug_location.apply(bcx.fcx);
1486 // If we don't care about the result, just make a
1487 // temporary stack slot
1488 let addr = match dest {
1490 Ignore => alloc_ty(bcx, ty, "temp"),
1493 // This scope holds intermediates that must be cleaned should
1494 // panic occur before the ADT as a whole is ready.
1495 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1497 if ty.is_simd(bcx.tcx()) {
1498 // Issue 23112: The original logic appeared vulnerable to same
1499 // order-of-eval bug. But, SIMD values are tuple-structs;
1500 // i.e. functional record update (FRU) syntax is unavailable.
1502 // To be safe, double-check that we did not get here via FRU.
1503 assert!(optbase.is_none());
1505 // This is the constructor of a SIMD type, such types are
1506 // always primitive machine types and so do not have a
1507 // destructor or require any clean-up.
1508 let llty = type_of::type_of(bcx.ccx(), ty);
1510 // keep a vector as a register, and running through the field
1511 // `insertelement`ing them directly into that register
1512 // (i.e. avoid GEPi and `store`s to an alloca) .
1513 let mut vec_val = C_undef(llty);
1515 for &(i, ref e) in fields {
1516 let block_datum = trans(bcx, &**e);
1517 bcx = block_datum.bcx;
1518 let position = C_uint(bcx.ccx(), i);
1519 let value = block_datum.datum.to_llscalarish(bcx);
1520 vec_val = InsertElement(bcx, vec_val, value, position);
1522 Store(bcx, vec_val, addr);
1523 } else if let Some(base) = optbase {
1524 // Issue 23112: If there is a base, then order-of-eval
1525 // requires field expressions eval'ed before base expression.
1527 // First, trans field expressions to temporary scratch values.
1528 let scratch_vals: Vec<_> = fields.iter().map(|&(i, ref e)| {
1529 let datum = unpack_datum!(bcx, trans(bcx, &**e));
1533 debug_location.apply(bcx.fcx);
1535 // Second, trans the base to the dest.
1536 assert_eq!(discr, 0);
1538 match expr_kind(bcx.tcx(), &*base.expr) {
1539 ExprKind::RvalueDps | ExprKind::RvalueDatum if !bcx.fcx.type_needs_drop(ty) => {
1540 bcx = trans_into(bcx, &*base.expr, SaveIn(addr));
1542 ExprKind::RvalueStmt => {
1543 bcx.tcx().sess.bug("unexpected expr kind for struct base expr")
1546 let base_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, &*base.expr, "base"));
1547 for &(i, t) in &base.fields {
1548 let datum = base_datum.get_element(
1549 bcx, t, |srcval| adt::trans_field_ptr(bcx, &*repr, srcval, discr, i));
1550 assert!(type_is_sized(bcx.tcx(), datum.ty));
1551 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1552 bcx = datum.store_to(bcx, dest);
1557 // Finally, move scratch field values into actual field locations
1558 for (i, datum) in scratch_vals {
1559 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1560 bcx = datum.store_to(bcx, dest);
1563 // No base means we can write all fields directly in place.
1564 for &(i, ref e) in fields {
1565 let dest = adt::trans_field_ptr(bcx, &*repr, addr, discr, i);
1566 let e_ty = expr_ty_adjusted(bcx, &**e);
1567 bcx = trans_into(bcx, &**e, SaveIn(dest));
1568 let scope = cleanup::CustomScope(custom_cleanup_scope);
1569 fcx.schedule_lifetime_end(scope, dest);
1570 fcx.schedule_drop_mem(scope, dest, e_ty);
1574 adt::trans_set_discr(bcx, &*repr, addr, discr);
1576 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1578 // If we don't care about the result drop the temporary we made
1582 bcx = glue::drop_ty(bcx, addr, ty, debug_location);
1583 base::call_lifetime_end(bcx, addr);
1590 fn trans_immediate_lit<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1593 -> DatumBlock<'blk, 'tcx, Expr> {
1594 // must not be a string constant, that is a RvalueDpsExpr
1595 let _icx = push_ctxt("trans_immediate_lit");
1596 let ty = expr_ty(bcx, expr);
1597 let v = consts::const_lit(bcx.ccx(), expr, lit);
1598 immediate_rvalue_bcx(bcx, v, ty).to_expr_datumblock()
1601 fn trans_unary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1604 sub_expr: &ast::Expr)
1605 -> DatumBlock<'blk, 'tcx, Expr> {
1606 let ccx = bcx.ccx();
1608 let _icx = push_ctxt("trans_unary_datum");
1610 let method_call = MethodCall::expr(expr.id);
1612 // The only overloaded operator that is translated to a datum
1613 // is an overloaded deref, since it is always yields a `&T`.
1614 // Otherwise, we should be in the RvalueDpsExpr path.
1616 op == ast::UnDeref ||
1617 !ccx.tcx().tables.borrow().method_map.contains_key(&method_call));
1619 let un_ty = expr_ty(bcx, expr);
1621 let debug_loc = expr.debug_loc();
1625 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1626 let llresult = Not(bcx, datum.to_llscalarish(bcx), debug_loc);
1627 immediate_rvalue_bcx(bcx, llresult, un_ty).to_expr_datumblock()
1630 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1631 let val = datum.to_llscalarish(bcx);
1632 let (bcx, llneg) = {
1634 let result = FNeg(bcx, val, debug_loc);
1637 let is_signed = un_ty.is_signed();
1638 let result = Neg(bcx, val, debug_loc);
1639 let bcx = if bcx.ccx().check_overflow() && is_signed {
1640 let (llty, min) = base::llty_and_min_for_signed_ty(bcx, un_ty);
1641 let is_min = ICmp(bcx, llvm::IntEQ, val,
1642 C_integral(llty, min, true), debug_loc);
1643 with_cond(bcx, is_min, |bcx| {
1644 let msg = InternedString::new(
1645 "attempted to negate with overflow");
1646 controlflow::trans_fail(bcx, expr_info(expr), msg)
1654 immediate_rvalue_bcx(bcx, llneg, un_ty).to_expr_datumblock()
1657 trans_uniq_expr(bcx, expr, un_ty, sub_expr, expr_ty(bcx, sub_expr))
1660 let datum = unpack_datum!(bcx, trans(bcx, sub_expr));
1661 deref_once(bcx, expr, datum, method_call)
1666 fn trans_uniq_expr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1667 box_expr: &ast::Expr,
1669 contents: &ast::Expr,
1670 contents_ty: Ty<'tcx>)
1671 -> DatumBlock<'blk, 'tcx, Expr> {
1672 let _icx = push_ctxt("trans_uniq_expr");
1674 assert!(type_is_sized(bcx.tcx(), contents_ty));
1675 let llty = type_of::type_of(bcx.ccx(), contents_ty);
1676 let size = llsize_of(bcx.ccx(), llty);
1677 let align = C_uint(bcx.ccx(), type_of::align_of(bcx.ccx(), contents_ty));
1678 let llty_ptr = llty.ptr_to();
1679 let Result { bcx, val } = malloc_raw_dyn(bcx,
1684 box_expr.debug_loc());
1685 // Unique boxes do not allocate for zero-size types. The standard library
1686 // may assume that `free` is never called on the pointer returned for
1687 // `Box<ZeroSizeType>`.
1688 let bcx = if llsize_of_alloc(bcx.ccx(), llty) == 0 {
1689 trans_into(bcx, contents, SaveIn(val))
1691 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1692 fcx.schedule_free_value(cleanup::CustomScope(custom_cleanup_scope),
1693 val, cleanup::HeapExchange, contents_ty);
1694 let bcx = trans_into(bcx, contents, SaveIn(val));
1695 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1698 immediate_rvalue_bcx(bcx, val, box_ty).to_expr_datumblock()
1701 fn ref_fat_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1702 lval: Datum<'tcx, Lvalue>)
1703 -> DatumBlock<'blk, 'tcx, Expr> {
1704 let dest_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), lval.ty);
1705 let scratch = rvalue_scratch_datum(bcx, dest_ty, "__fat_ptr");
1706 memcpy_ty(bcx, scratch.val, lval.val, scratch.ty);
1708 DatumBlock::new(bcx, scratch.to_expr_datum())
1711 fn trans_addr_of<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1713 subexpr: &ast::Expr)
1714 -> DatumBlock<'blk, 'tcx, Expr> {
1715 let _icx = push_ctxt("trans_addr_of");
1717 let sub_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, subexpr, "addr_of"));
1718 if !type_is_sized(bcx.tcx(), sub_datum.ty) {
1719 // DST lvalue, close to a fat pointer
1720 ref_fat_ptr(bcx, sub_datum)
1722 // Sized value, ref to a thin pointer
1723 let ty = expr_ty(bcx, expr);
1724 immediate_rvalue_bcx(bcx, sub_datum.val, ty).to_expr_datumblock()
1728 // Important to get types for both lhs and rhs, because one might be _|_
1729 // and the other not.
1730 fn trans_eager_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1731 binop_expr: &ast::Expr,
1738 -> DatumBlock<'blk, 'tcx, Expr> {
1739 let _icx = push_ctxt("trans_eager_binop");
1741 let tcx = bcx.tcx();
1742 let is_simd = lhs_t.is_simd(tcx);
1743 let intype = if is_simd {
1744 lhs_t.simd_type(tcx)
1748 let is_float = intype.is_fp();
1749 let is_signed = intype.is_signed();
1750 let info = expr_info(binop_expr);
1752 let binop_debug_loc = binop_expr.debug_loc();
1755 let val = match op.node {
1758 FAdd(bcx, lhs, rhs, binop_debug_loc)
1760 Add(bcx, lhs, rhs, binop_debug_loc)
1762 let (newbcx, res) = with_overflow_check(
1763 bcx, OverflowOp::Add, info, lhs_t, lhs, rhs, binop_debug_loc);
1770 FSub(bcx, lhs, rhs, binop_debug_loc)
1772 Sub(bcx, lhs, rhs, binop_debug_loc)
1774 let (newbcx, res) = with_overflow_check(
1775 bcx, OverflowOp::Sub, info, lhs_t, lhs, rhs, binop_debug_loc);
1782 FMul(bcx, lhs, rhs, binop_debug_loc)
1784 Mul(bcx, lhs, rhs, binop_debug_loc)
1786 let (newbcx, res) = with_overflow_check(
1787 bcx, OverflowOp::Mul, info, lhs_t, lhs, rhs, binop_debug_loc);
1794 FDiv(bcx, lhs, rhs, binop_debug_loc)
1796 // Only zero-check integers; fp /0 is NaN
1797 bcx = base::fail_if_zero_or_overflows(bcx,
1798 expr_info(binop_expr),
1804 SDiv(bcx, lhs, rhs, binop_debug_loc)
1806 UDiv(bcx, lhs, rhs, binop_debug_loc)
1812 FRem(bcx, lhs, rhs, binop_debug_loc)
1814 // Only zero-check integers; fp %0 is NaN
1815 bcx = base::fail_if_zero_or_overflows(bcx,
1816 expr_info(binop_expr),
1817 op, lhs, rhs, rhs_t);
1819 SRem(bcx, lhs, rhs, binop_debug_loc)
1821 URem(bcx, lhs, rhs, binop_debug_loc)
1825 ast::BiBitOr => Or(bcx, lhs, rhs, binop_debug_loc),
1826 ast::BiBitAnd => And(bcx, lhs, rhs, binop_debug_loc),
1827 ast::BiBitXor => Xor(bcx, lhs, rhs, binop_debug_loc),
1829 let (newbcx, res) = with_overflow_check(
1830 bcx, OverflowOp::Shl, info, lhs_t, lhs, rhs, binop_debug_loc);
1835 let (newbcx, res) = with_overflow_check(
1836 bcx, OverflowOp::Shr, info, lhs_t, lhs, rhs, binop_debug_loc);
1840 ast::BiEq | ast::BiNe | ast::BiLt | ast::BiGe | ast::BiLe | ast::BiGt => {
1842 base::compare_simd_types(bcx, lhs, rhs, intype, op.node, binop_debug_loc)
1844 base::compare_scalar_types(bcx, lhs, rhs, intype, op.node, binop_debug_loc)
1848 bcx.tcx().sess.span_bug(binop_expr.span, "unexpected binop");
1852 immediate_rvalue_bcx(bcx, val, binop_ty).to_expr_datumblock()
1855 // refinement types would obviate the need for this
1856 enum lazy_binop_ty {
1861 fn trans_lazy_binop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1862 binop_expr: &ast::Expr,
1866 -> DatumBlock<'blk, 'tcx, Expr> {
1867 let _icx = push_ctxt("trans_lazy_binop");
1868 let binop_ty = expr_ty(bcx, binop_expr);
1871 let DatumBlock {bcx: past_lhs, datum: lhs} = trans(bcx, a);
1872 let lhs = lhs.to_llscalarish(past_lhs);
1874 if past_lhs.unreachable.get() {
1875 return immediate_rvalue_bcx(past_lhs, lhs, binop_ty).to_expr_datumblock();
1878 let join = fcx.new_id_block("join", binop_expr.id);
1879 let before_rhs = fcx.new_id_block("before_rhs", b.id);
1882 lazy_and => CondBr(past_lhs, lhs, before_rhs.llbb, join.llbb, DebugLoc::None),
1883 lazy_or => CondBr(past_lhs, lhs, join.llbb, before_rhs.llbb, DebugLoc::None)
1886 let DatumBlock {bcx: past_rhs, datum: rhs} = trans(before_rhs, b);
1887 let rhs = rhs.to_llscalarish(past_rhs);
1889 if past_rhs.unreachable.get() {
1890 return immediate_rvalue_bcx(join, lhs, binop_ty).to_expr_datumblock();
1893 Br(past_rhs, join.llbb, DebugLoc::None);
1894 let phi = Phi(join, Type::i1(bcx.ccx()), &[lhs, rhs],
1895 &[past_lhs.llbb, past_rhs.llbb]);
1897 return immediate_rvalue_bcx(join, phi, binop_ty).to_expr_datumblock();
1900 fn trans_binary<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1905 -> DatumBlock<'blk, 'tcx, Expr> {
1906 let _icx = push_ctxt("trans_binary");
1907 let ccx = bcx.ccx();
1909 // if overloaded, would be RvalueDpsExpr
1910 assert!(!ccx.tcx().tables.borrow().method_map.contains_key(&MethodCall::expr(expr.id)));
1914 trans_lazy_binop(bcx, expr, lazy_and, lhs, rhs)
1917 trans_lazy_binop(bcx, expr, lazy_or, lhs, rhs)
1921 let lhs_datum = unpack_datum!(bcx, trans(bcx, lhs));
1922 let rhs_datum = unpack_datum!(bcx, trans(bcx, rhs));
1923 let binop_ty = expr_ty(bcx, expr);
1925 debug!("trans_binary (expr {}): lhs_datum={}",
1927 lhs_datum.to_string(ccx));
1928 let lhs_ty = lhs_datum.ty;
1929 let lhs = lhs_datum.to_llscalarish(bcx);
1931 debug!("trans_binary (expr {}): rhs_datum={}",
1933 rhs_datum.to_string(ccx));
1934 let rhs_ty = rhs_datum.ty;
1935 let rhs = rhs_datum.to_llscalarish(bcx);
1936 trans_eager_binop(bcx, expr, binop_ty, op,
1937 lhs_ty, lhs, rhs_ty, rhs)
1942 fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1944 method_call: MethodCall,
1945 lhs: Datum<'tcx, Expr>,
1946 rhs: Option<(Datum<'tcx, Expr>, ast::NodeId)>,
1949 -> Result<'blk, 'tcx> {
1950 let method_ty = bcx.tcx()
1954 .get(&method_call).unwrap().ty;
1956 callee::trans_call_inner(bcx,
1958 monomorphize_type(bcx, method_ty),
1959 |bcx, arg_cleanup_scope| {
1960 meth::trans_method_callee(bcx,
1965 callee::ArgOverloadedOp(lhs, rhs, autoref),
1969 fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1971 callee: &'a ast::Expr,
1972 args: &'a [P<ast::Expr>],
1974 -> Block<'blk, 'tcx> {
1975 debug!("trans_overloaded_call {}", expr.id);
1976 let method_call = MethodCall::expr(expr.id);
1977 let method_type = bcx.tcx()
1984 let mut all_args = vec!(callee);
1985 all_args.extend(args.iter().map(|e| &**e));
1987 callee::trans_call_inner(bcx,
1989 monomorphize_type(bcx,
1991 |bcx, arg_cleanup_scope| {
1992 meth::trans_method_callee(
1998 callee::ArgOverloadedCall(all_args),
2003 pub fn cast_is_noop<'tcx>(tcx: &ty::ctxt<'tcx>,
2008 if let Some(&CastKind::CoercionCast) = tcx.cast_kinds.borrow().get(&expr.id) {
2012 match (t_in.builtin_deref(true), t_out.builtin_deref(true)) {
2013 (Some(ty::mt{ ty: t_in, .. }), Some(ty::mt{ ty: t_out, .. })) => {
2017 // This condition isn't redundant with the check for CoercionCast:
2018 // different types can be substituted into the same type, and
2019 // == equality can be overconservative if there are regions.
2025 fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2028 -> DatumBlock<'blk, 'tcx, Expr>
2030 use middle::cast::CastTy::*;
2031 use middle::cast::IntTy::*;
2033 fn int_cast(bcx: Block,
2040 let _icx = push_ctxt("int_cast");
2041 let srcsz = llsrctype.int_width();
2042 let dstsz = lldsttype.int_width();
2043 return if dstsz == srcsz {
2044 BitCast(bcx, llsrc, lldsttype)
2045 } else if srcsz > dstsz {
2046 TruncOrBitCast(bcx, llsrc, lldsttype)
2048 SExtOrBitCast(bcx, llsrc, lldsttype)
2050 ZExtOrBitCast(bcx, llsrc, lldsttype)
2054 fn float_cast(bcx: Block,
2060 let _icx = push_ctxt("float_cast");
2061 let srcsz = llsrctype.float_width();
2062 let dstsz = lldsttype.float_width();
2063 return if dstsz > srcsz {
2064 FPExt(bcx, llsrc, lldsttype)
2065 } else if srcsz > dstsz {
2066 FPTrunc(bcx, llsrc, lldsttype)
2070 let _icx = push_ctxt("trans_cast");
2072 let ccx = bcx.ccx();
2074 let t_in = expr_ty_adjusted(bcx, expr);
2075 let t_out = node_id_type(bcx, id);
2077 debug!("trans_cast({:?} as {:?})", t_in, t_out);
2078 let mut ll_t_in = type_of::arg_type_of(ccx, t_in);
2079 let ll_t_out = type_of::arg_type_of(ccx, t_out);
2080 // Convert the value to be cast into a ValueRef, either by-ref or
2081 // by-value as appropriate given its type:
2082 let mut datum = unpack_datum!(bcx, trans(bcx, expr));
2084 let datum_ty = monomorphize_type(bcx, datum.ty);
2086 if cast_is_noop(bcx.tcx(), expr, datum_ty, t_out) {
2088 return DatumBlock::new(bcx, datum);
2091 if type_is_fat_ptr(bcx.tcx(), t_in) {
2092 assert!(datum.kind.is_by_ref());
2093 if type_is_fat_ptr(bcx.tcx(), t_out) {
2094 return DatumBlock::new(bcx, Datum::new(
2095 PointerCast(bcx, datum.val, ll_t_out.ptr_to()),
2098 )).to_expr_datumblock();
2100 // Return the address
2101 return immediate_rvalue_bcx(bcx,
2103 Load(bcx, get_dataptr(bcx, datum.val)),
2105 t_out).to_expr_datumblock();
2109 let r_t_in = CastTy::from_ty(bcx.tcx(), t_in).expect("bad input type for cast");
2110 let r_t_out = CastTy::from_ty(bcx.tcx(), t_out).expect("bad output type for cast");
2112 let (llexpr, signed) = if let Int(CEnum) = r_t_in {
2113 let repr = adt::represent_type(ccx, t_in);
2114 let datum = unpack_datum!(
2115 bcx, datum.to_lvalue_datum(bcx, "trans_imm_cast", expr.id));
2116 let llexpr_ptr = datum.to_llref();
2117 let discr = adt::trans_get_discr(bcx, &*repr, llexpr_ptr, Some(Type::i64(ccx)));
2118 ll_t_in = val_ty(discr);
2119 (discr, adt::is_discr_signed(&*repr))
2121 (datum.to_llscalarish(bcx), t_in.is_signed())
2124 let newval = match (r_t_in, r_t_out) {
2125 (Ptr(_), Ptr(_)) | (FnPtr, Ptr(_)) | (RPtr(_), Ptr(_)) => {
2126 PointerCast(bcx, llexpr, ll_t_out)
2128 (Ptr(_), Int(_)) | (FnPtr, Int(_)) => PtrToInt(bcx, llexpr, ll_t_out),
2129 (Int(_), Ptr(_)) => IntToPtr(bcx, llexpr, ll_t_out),
2131 (Int(_), Int(_)) => int_cast(bcx, ll_t_out, ll_t_in, llexpr, signed),
2132 (Float, Float) => float_cast(bcx, ll_t_out, ll_t_in, llexpr),
2133 (Int(_), Float) if signed => SIToFP(bcx, llexpr, ll_t_out),
2134 (Int(_), Float) => UIToFP(bcx, llexpr, ll_t_out),
2135 (Float, Int(I)) => FPToSI(bcx, llexpr, ll_t_out),
2136 (Float, Int(_)) => FPToUI(bcx, llexpr, ll_t_out),
2138 _ => ccx.sess().span_bug(expr.span,
2139 &format!("translating unsupported cast: \
2145 return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
2148 fn trans_assign_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2153 -> Block<'blk, 'tcx> {
2154 let _icx = push_ctxt("trans_assign_op");
2157 debug!("trans_assign_op(expr={:?})", expr);
2159 // User-defined operator methods cannot be used with `+=` etc right now
2160 assert!(!bcx.tcx().tables.borrow().method_map.contains_key(&MethodCall::expr(expr.id)));
2162 // Evaluate LHS (destination), which should be an lvalue
2163 let dst_datum = unpack_datum!(bcx, trans_to_lvalue(bcx, dst, "assign_op"));
2164 assert!(!bcx.fcx.type_needs_drop(dst_datum.ty));
2165 let dst_ty = dst_datum.ty;
2166 let dst = load_ty(bcx, dst_datum.val, dst_datum.ty);
2169 let rhs_datum = unpack_datum!(bcx, trans(bcx, &*src));
2170 let rhs_ty = rhs_datum.ty;
2171 let rhs = rhs_datum.to_llscalarish(bcx);
2173 // Perform computation and store the result
2174 let result_datum = unpack_datum!(
2175 bcx, trans_eager_binop(bcx, expr, dst_datum.ty, op,
2176 dst_ty, dst, rhs_ty, rhs));
2177 return result_datum.store_to(bcx, dst_datum.val);
2180 fn auto_ref<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2181 datum: Datum<'tcx, Expr>,
2183 -> DatumBlock<'blk, 'tcx, Expr> {
2186 // Ensure cleanup of `datum` if not already scheduled and obtain
2187 // a "by ref" pointer.
2188 let lv_datum = unpack_datum!(bcx, datum.to_lvalue_datum(bcx, "autoref", expr.id));
2190 // Compute final type. Note that we are loose with the region and
2191 // mutability, since those things don't matter in trans.
2192 let referent_ty = lv_datum.ty;
2193 let ptr_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic), referent_ty);
2196 let llref = lv_datum.to_llref();
2198 // Construct the resulting datum, using what was the "by ref"
2199 // ValueRef of type `referent_ty` to be the "by value" ValueRef
2200 // of type `&referent_ty`.
2201 // Pointers to DST types are non-immediate, and therefore still use ByRef.
2202 let kind = if type_is_sized(bcx.tcx(), referent_ty) { ByValue } else { ByRef };
2203 DatumBlock::new(bcx, Datum::new(llref, ptr_ty, RvalueExpr(Rvalue::new(kind))))
2206 fn deref_multiple<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2208 datum: Datum<'tcx, Expr>,
2210 -> DatumBlock<'blk, 'tcx, Expr> {
2212 let mut datum = datum;
2214 let method_call = MethodCall::autoderef(expr.id, i as u32);
2215 datum = unpack_datum!(bcx, deref_once(bcx, expr, datum, method_call));
2217 DatumBlock { bcx: bcx, datum: datum }
2220 fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2222 datum: Datum<'tcx, Expr>,
2223 method_call: MethodCall)
2224 -> DatumBlock<'blk, 'tcx, Expr> {
2225 let ccx = bcx.ccx();
2227 debug!("deref_once(expr={:?}, datum={}, method_call={:?})",
2229 datum.to_string(ccx),
2234 // Check for overloaded deref.
2235 let method_ty = ccx.tcx()
2239 .get(&method_call).map(|method| method.ty);
2241 let datum = match method_ty {
2242 Some(method_ty) => {
2243 let method_ty = monomorphize_type(bcx, method_ty);
2245 // Overloaded. Evaluate `trans_overloaded_op`, which will
2246 // invoke the user's deref() method, which basically
2247 // converts from the `Smaht<T>` pointer that we have into
2248 // a `&T` pointer. We can then proceed down the normal
2249 // path (below) to dereference that `&T`.
2250 let datum = if method_call.autoderef == 0 {
2253 // Always perform an AutoPtr when applying an overloaded auto-deref
2254 unpack_datum!(bcx, auto_ref(bcx, datum, expr))
2257 let ref_ty = // invoked methods have their LB regions instantiated
2258 ccx.tcx().no_late_bound_regions(&method_ty.fn_ret()).unwrap().unwrap();
2259 let scratch = rvalue_scratch_datum(bcx, ref_ty, "overloaded_deref");
2261 unpack_result!(bcx, trans_overloaded_op(bcx, expr, method_call,
2262 datum, None, Some(SaveIn(scratch.val)),
2264 scratch.to_expr_datum()
2267 // Not overloaded. We already have a pointer we know how to deref.
2272 let r = match datum.ty.sty {
2273 ty::TyBox(content_ty) => {
2274 // Make sure we have an lvalue datum here to get the
2275 // proper cleanups scheduled
2276 let datum = unpack_datum!(
2277 bcx, datum.to_lvalue_datum(bcx, "deref", expr.id));
2279 if type_is_sized(bcx.tcx(), content_ty) {
2280 let ptr = load_ty(bcx, datum.val, datum.ty);
2281 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr))
2283 // A fat pointer and a DST lvalue have the same representation
2284 // just different types. Since there is no temporary for `*e`
2285 // here (because it is unsized), we cannot emulate the sized
2286 // object code path for running drop glue and free. Instead,
2287 // we schedule cleanup for `e`, turning it into an lvalue.
2289 let datum = Datum::new(datum.val, content_ty, LvalueExpr);
2290 DatumBlock::new(bcx, datum)
2294 ty::TyRawPtr(ty::mt { ty: content_ty, .. }) |
2295 ty::TyRef(_, ty::mt { ty: content_ty, .. }) => {
2296 if type_is_sized(bcx.tcx(), content_ty) {
2297 let ptr = datum.to_llscalarish(bcx);
2299 // Always generate an lvalue datum, even if datum.mode is
2300 // an rvalue. This is because datum.mode is only an
2301 // rvalue for non-owning pointers like &T or *T, in which
2302 // case cleanup *is* scheduled elsewhere, by the true
2303 // owner (or, in the case of *T, by the user).
2304 DatumBlock::new(bcx, Datum::new(ptr, content_ty, LvalueExpr))
2306 // A fat pointer and a DST lvalue have the same representation
2307 // just different types.
2308 DatumBlock::new(bcx, Datum::new(datum.val, content_ty, LvalueExpr))
2313 bcx.tcx().sess.span_bug(
2315 &format!("deref invoked on expr of illegal type {:?}",
2320 debug!("deref_once(expr={}, method_call={:?}, result={})",
2321 expr.id, method_call, r.datum.to_string(ccx));
2336 fn codegen_strategy(&self) -> OverflowCodegen {
2337 use self::OverflowCodegen::{ViaIntrinsic, ViaInputCheck};
2339 OverflowOp::Add => ViaIntrinsic(OverflowOpViaIntrinsic::Add),
2340 OverflowOp::Sub => ViaIntrinsic(OverflowOpViaIntrinsic::Sub),
2341 OverflowOp::Mul => ViaIntrinsic(OverflowOpViaIntrinsic::Mul),
2343 OverflowOp::Shl => ViaInputCheck(OverflowOpViaInputCheck::Shl),
2344 OverflowOp::Shr => ViaInputCheck(OverflowOpViaInputCheck::Shr),
2349 enum OverflowCodegen {
2350 ViaIntrinsic(OverflowOpViaIntrinsic),
2351 ViaInputCheck(OverflowOpViaInputCheck),
2354 enum OverflowOpViaInputCheck { Shl, Shr, }
2357 enum OverflowOpViaIntrinsic { Add, Sub, Mul, }
2359 impl OverflowOpViaIntrinsic {
2360 fn to_intrinsic<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>, lhs_ty: Ty) -> ValueRef {
2361 let name = self.to_intrinsic_name(bcx.tcx(), lhs_ty);
2362 bcx.ccx().get_intrinsic(&name)
2364 fn to_intrinsic_name(&self, tcx: &ty::ctxt, ty: Ty) -> &'static str {
2365 use syntax::ast::IntTy::*;
2366 use syntax::ast::UintTy::*;
2367 use middle::ty::{TyInt, TyUint};
2369 let new_sty = match ty.sty {
2370 TyInt(TyIs) => match &tcx.sess.target.target.target_pointer_width[..] {
2371 "32" => TyInt(TyI32),
2372 "64" => TyInt(TyI64),
2373 _ => panic!("unsupported target word size")
2375 TyUint(TyUs) => match &tcx.sess.target.target.target_pointer_width[..] {
2376 "32" => TyUint(TyU32),
2377 "64" => TyUint(TyU64),
2378 _ => panic!("unsupported target word size")
2380 ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
2381 _ => panic!("tried to get overflow intrinsic for {:?} applied to non-int type",
2386 OverflowOpViaIntrinsic::Add => match new_sty {
2387 TyInt(TyI8) => "llvm.sadd.with.overflow.i8",
2388 TyInt(TyI16) => "llvm.sadd.with.overflow.i16",
2389 TyInt(TyI32) => "llvm.sadd.with.overflow.i32",
2390 TyInt(TyI64) => "llvm.sadd.with.overflow.i64",
2392 TyUint(TyU8) => "llvm.uadd.with.overflow.i8",
2393 TyUint(TyU16) => "llvm.uadd.with.overflow.i16",
2394 TyUint(TyU32) => "llvm.uadd.with.overflow.i32",
2395 TyUint(TyU64) => "llvm.uadd.with.overflow.i64",
2397 _ => unreachable!(),
2399 OverflowOpViaIntrinsic::Sub => match new_sty {
2400 TyInt(TyI8) => "llvm.ssub.with.overflow.i8",
2401 TyInt(TyI16) => "llvm.ssub.with.overflow.i16",
2402 TyInt(TyI32) => "llvm.ssub.with.overflow.i32",
2403 TyInt(TyI64) => "llvm.ssub.with.overflow.i64",
2405 TyUint(TyU8) => "llvm.usub.with.overflow.i8",
2406 TyUint(TyU16) => "llvm.usub.with.overflow.i16",
2407 TyUint(TyU32) => "llvm.usub.with.overflow.i32",
2408 TyUint(TyU64) => "llvm.usub.with.overflow.i64",
2410 _ => unreachable!(),
2412 OverflowOpViaIntrinsic::Mul => match new_sty {
2413 TyInt(TyI8) => "llvm.smul.with.overflow.i8",
2414 TyInt(TyI16) => "llvm.smul.with.overflow.i16",
2415 TyInt(TyI32) => "llvm.smul.with.overflow.i32",
2416 TyInt(TyI64) => "llvm.smul.with.overflow.i64",
2418 TyUint(TyU8) => "llvm.umul.with.overflow.i8",
2419 TyUint(TyU16) => "llvm.umul.with.overflow.i16",
2420 TyUint(TyU32) => "llvm.umul.with.overflow.i32",
2421 TyUint(TyU64) => "llvm.umul.with.overflow.i64",
2423 _ => unreachable!(),
2428 fn build_intrinsic_call<'blk, 'tcx>(&self, bcx: Block<'blk, 'tcx>,
2429 info: NodeIdAndSpan,
2430 lhs_t: Ty<'tcx>, lhs: ValueRef,
2432 binop_debug_loc: DebugLoc)
2433 -> (Block<'blk, 'tcx>, ValueRef) {
2434 let llfn = self.to_intrinsic(bcx, lhs_t);
2436 let val = Call(bcx, llfn, &[lhs, rhs], None, binop_debug_loc);
2437 let result = ExtractValue(bcx, val, 0); // iN operation result
2438 let overflow = ExtractValue(bcx, val, 1); // i1 "did it overflow?"
2440 let cond = ICmp(bcx, llvm::IntEQ, overflow, C_integral(Type::i1(bcx.ccx()), 1, false),
2443 let expect = bcx.ccx().get_intrinsic(&"llvm.expect.i1");
2444 Call(bcx, expect, &[cond, C_integral(Type::i1(bcx.ccx()), 0, false)],
2445 None, binop_debug_loc);
2448 base::with_cond(bcx, cond, |bcx|
2449 controlflow::trans_fail(bcx, info,
2450 InternedString::new("arithmetic operation overflowed")));
2456 impl OverflowOpViaInputCheck {
2457 fn build_with_input_check<'blk, 'tcx>(&self,
2458 bcx: Block<'blk, 'tcx>,
2459 info: NodeIdAndSpan,
2463 binop_debug_loc: DebugLoc)
2464 -> (Block<'blk, 'tcx>, ValueRef)
2466 let lhs_llty = val_ty(lhs);
2467 let rhs_llty = val_ty(rhs);
2469 // Panic if any bits are set outside of bits that we always
2472 // Note that the mask's value is derived from the LHS type
2473 // (since that is where the 32/64 distinction is relevant) but
2474 // the mask's type must match the RHS type (since they will
2475 // both be fed into a and-binop)
2476 let invert_mask = shift_mask_val(bcx, lhs_llty, rhs_llty, true);
2478 let outer_bits = And(bcx, rhs, invert_mask, binop_debug_loc);
2479 let cond = build_nonzero_check(bcx, outer_bits, binop_debug_loc);
2480 let result = match *self {
2481 OverflowOpViaInputCheck::Shl =>
2482 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2483 OverflowOpViaInputCheck::Shr =>
2484 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2487 base::with_cond(bcx, cond, |bcx|
2488 controlflow::trans_fail(bcx, info,
2489 InternedString::new("shift operation overflowed")));
2495 fn shift_mask_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2498 invert: bool) -> ValueRef {
2499 let kind = llty.kind();
2501 TypeKind::Integer => {
2502 // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
2503 let val = llty.int_width() - 1;
2505 C_integral(mask_llty, !val, true)
2507 C_integral(mask_llty, val, false)
2510 TypeKind::Vector => {
2511 let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
2512 VectorSplat(bcx, mask_llty.vector_length(), mask)
2514 _ => panic!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
2518 // Check if an integer or vector contains a nonzero element.
2519 fn build_nonzero_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2521 binop_debug_loc: DebugLoc) -> ValueRef {
2522 let llty = val_ty(value);
2523 let kind = llty.kind();
2525 TypeKind::Integer => ICmp(bcx, llvm::IntNE, value, C_null(llty), binop_debug_loc),
2526 TypeKind::Vector => {
2527 // Check if any elements of the vector are nonzero by treating
2528 // it as a wide integer and checking if the integer is nonzero.
2529 let width = llty.vector_length() as u64 * llty.element_type().int_width();
2530 let int_value = BitCast(bcx, value, Type::ix(bcx.ccx(), width));
2531 build_nonzero_check(bcx, int_value, binop_debug_loc)
2533 _ => panic!("build_nonzero_check: expected Integer or Vector, found {:?}", kind),
2537 // To avoid UB from LLVM, these two functions mask RHS with an
2538 // appropriate mask unconditionally (i.e. the fallback behavior for
2539 // all shifts). For 32- and 64-bit types, this matches the semantics
2540 // of Java. (See related discussion on #1877 and #10183.)
2542 fn build_unchecked_lshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2545 binop_debug_loc: DebugLoc) -> ValueRef {
2546 let rhs = base::cast_shift_expr_rhs(bcx, ast::BinOp_::BiShl, lhs, rhs);
2547 // #1877, #10183: Ensure that input is always valid
2548 let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2549 Shl(bcx, lhs, rhs, binop_debug_loc)
2552 fn build_unchecked_rshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2556 binop_debug_loc: DebugLoc) -> ValueRef {
2557 let rhs = base::cast_shift_expr_rhs(bcx, ast::BinOp_::BiShr, lhs, rhs);
2558 // #1877, #10183: Ensure that input is always valid
2559 let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
2560 let tcx = bcx.tcx();
2561 let is_simd = lhs_t.is_simd(tcx);
2562 let intype = if is_simd {
2563 lhs_t.simd_type(tcx)
2567 let is_signed = intype.is_signed();
2569 AShr(bcx, lhs, rhs, binop_debug_loc)
2571 LShr(bcx, lhs, rhs, binop_debug_loc)
2575 fn shift_mask_rhs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
2577 debug_loc: DebugLoc) -> ValueRef {
2578 let rhs_llty = val_ty(rhs);
2579 And(bcx, rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false), debug_loc)
2582 fn with_overflow_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, oop: OverflowOp, info: NodeIdAndSpan,
2583 lhs_t: Ty<'tcx>, lhs: ValueRef,
2585 binop_debug_loc: DebugLoc)
2586 -> (Block<'blk, 'tcx>, ValueRef) {
2587 if bcx.unreachable.get() { return (bcx, _Undef(lhs)); }
2588 if bcx.ccx().check_overflow() {
2590 match oop.codegen_strategy() {
2591 OverflowCodegen::ViaIntrinsic(oop) =>
2592 oop.build_intrinsic_call(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2593 OverflowCodegen::ViaInputCheck(oop) =>
2594 oop.build_with_input_check(bcx, info, lhs_t, lhs, rhs, binop_debug_loc),
2597 let res = match oop {
2598 OverflowOp::Add => Add(bcx, lhs, rhs, binop_debug_loc),
2599 OverflowOp::Sub => Sub(bcx, lhs, rhs, binop_debug_loc),
2600 OverflowOp::Mul => Mul(bcx, lhs, rhs, binop_debug_loc),
2603 build_unchecked_lshift(bcx, lhs, rhs, binop_debug_loc),
2605 build_unchecked_rshift(bcx, lhs_t, lhs, rhs, binop_debug_loc),
2611 /// We categorize expressions into three kinds. The distinction between
2612 /// lvalue/rvalue is fundamental to the language. The distinction between the
2613 /// two kinds of rvalues is an artifact of trans which reflects how we will
2614 /// generate code for that kind of expression. See trans/expr.rs for more
2616 #[derive(Copy, Clone)]
2624 fn expr_kind(tcx: &ty::ctxt, expr: &ast::Expr) -> ExprKind {
2625 if tcx.tables.borrow().method_map.contains_key(&MethodCall::expr(expr.id)) {
2626 // Overloaded operations are generally calls, and hence they are
2627 // generated via DPS, but there are a few exceptions:
2628 return match expr.node {
2629 // `a += b` has a unit result.
2630 ast::ExprAssignOp(..) => ExprKind::RvalueStmt,
2632 // the deref method invoked for `*a` always yields an `&T`
2633 ast::ExprUnary(ast::UnDeref, _) => ExprKind::Lvalue,
2635 // the index method invoked for `a[i]` always yields an `&T`
2636 ast::ExprIndex(..) => ExprKind::Lvalue,
2638 // in the general case, result could be any type, use DPS
2639 _ => ExprKind::RvalueDps
2644 ast::ExprPath(..) => {
2645 match tcx.resolve_expr(expr) {
2646 def::DefStruct(_) | def::DefVariant(..) => {
2647 if let ty::TyBareFn(..) = tcx.node_id_to_type(expr.id).sty {
2649 ExprKind::RvalueDatum
2655 // Special case: A unit like struct's constructor must be called without () at the
2656 // end (like `UnitStruct`) which means this is an ExprPath to a DefFn. But in case
2657 // of unit structs this is should not be interpreted as function pointer but as
2658 // call to the constructor.
2659 def::DefFn(_, true) => ExprKind::RvalueDps,
2661 // Fn pointers are just scalar values.
2662 def::DefFn(..) | def::DefMethod(..) => ExprKind::RvalueDatum,
2664 // Note: there is actually a good case to be made that
2665 // DefArg's, particularly those of immediate type, ought to
2666 // considered rvalues.
2667 def::DefStatic(..) |
2669 def::DefLocal(..) => ExprKind::Lvalue,
2672 def::DefAssociatedConst(..) => ExprKind::RvalueDatum,
2677 &format!("uncategorized def for expr {}: {:?}",
2684 ast::ExprUnary(ast::UnDeref, _) |
2685 ast::ExprField(..) |
2686 ast::ExprTupField(..) |
2687 ast::ExprIndex(..) => {
2692 ast::ExprMethodCall(..) |
2693 ast::ExprStruct(..) |
2694 ast::ExprRange(..) |
2697 ast::ExprMatch(..) |
2698 ast::ExprClosure(..) |
2699 ast::ExprBlock(..) |
2700 ast::ExprRepeat(..) |
2701 ast::ExprVec(..) => {
2705 ast::ExprIfLet(..) => {
2706 tcx.sess.span_bug(expr.span, "non-desugared ExprIfLet");
2708 ast::ExprWhileLet(..) => {
2709 tcx.sess.span_bug(expr.span, "non-desugared ExprWhileLet");
2712 ast::ExprForLoop(..) => {
2713 tcx.sess.span_bug(expr.span, "non-desugared ExprForLoop");
2716 ast::ExprLit(ref lit) if ast_util::lit_is_str(&**lit) => {
2720 ast::ExprBreak(..) |
2721 ast::ExprAgain(..) |
2723 ast::ExprWhile(..) |
2725 ast::ExprAssign(..) |
2726 ast::ExprInlineAsm(..) |
2727 ast::ExprAssignOp(..) => {
2728 ExprKind::RvalueStmt
2731 ast::ExprLit(_) | // Note: LitStr is carved out above
2732 ast::ExprUnary(..) |
2733 ast::ExprBox(None, _) |
2734 ast::ExprAddrOf(..) |
2735 ast::ExprBinary(..) |
2736 ast::ExprCast(..) => {
2737 ExprKind::RvalueDatum
2740 ast::ExprBox(Some(ref place), _) => {
2741 // Special case `Box<T>` for now:
2742 let def_id = match tcx.def_map.borrow().get(&place.id) {
2743 Some(def) => def.def_id(),
2744 None => panic!("no def for place"),
2746 if tcx.lang_items.exchange_heap() == Some(def_id) {
2747 ExprKind::RvalueDatum
2753 ast::ExprParen(ref e) => expr_kind(tcx, &**e),
2755 ast::ExprMac(..) => {
2758 "macro expression remains after expansion");