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 use rustc::ty::{self, Ty};
12 use rustc::ty::cast::{CastTy, IntTy};
13 use rustc::ty::layout::{self, LayoutOf};
15 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
16 use rustc_apfloat::{ieee, Float, Status, Round};
17 use std::{u128, i128};
22 use common::{self, IntPredicate, RealPredicate};
26 use type_of::LayoutLlvmExt;
29 use interfaces::{BuilderMethods, CommonMethods, CommonWriteMethods, TypeMethods};
31 use super::{FunctionCx, LocalRef};
32 use super::operand::{OperandRef, OperandValue};
33 use super::place::PlaceRef;
35 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
36 pub fn codegen_rvalue(&mut self,
37 bx: Builder<'a, 'll, 'tcx>,
38 dest: PlaceRef<'tcx, &'ll Value>,
39 rvalue: &mir::Rvalue<'tcx>)
40 -> Builder<'a, 'll, 'tcx>
42 debug!("codegen_rvalue(dest.llval={:?}, rvalue={:?})",
46 mir::Rvalue::Use(ref operand) => {
47 let cg_operand = self.codegen_operand(&bx, operand);
48 // FIXME: consider not copying constants through stack. (fixable by codegenning
49 // constants into OperandValue::Ref, why don’t we do that yet if we don’t?)
50 cg_operand.val.store(&bx, dest);
54 mir::Rvalue::Cast(mir::CastKind::Unsize, ref source, _) => {
55 // The destination necessarily contains a fat pointer, so if
56 // it's a scalar pair, it's a fat pointer or newtype thereof.
57 if dest.layout.is_llvm_scalar_pair() {
58 // into-coerce of a thin pointer to a fat pointer - just
59 // use the operand path.
60 let (bx, temp) = self.codegen_rvalue_operand(bx, rvalue);
61 temp.val.store(&bx, dest);
65 // Unsize of a nontrivial struct. I would prefer for
66 // this to be eliminated by MIR building, but
67 // `CoerceUnsized` can be passed by a where-clause,
68 // so the (generic) MIR may not be able to expand it.
69 let operand = self.codegen_operand(&bx, source);
71 OperandValue::Pair(..) |
72 OperandValue::Immediate(_) => {
73 // unsize from an immediate structure. We don't
74 // really need a temporary alloca here, but
75 // avoiding it would require us to have
76 // `coerce_unsized_into` use extractvalue to
77 // index into the struct, and this case isn't
78 // important enough for it.
79 debug!("codegen_rvalue: creating ugly alloca");
80 let scratch = PlaceRef::alloca(&bx, operand.layout, "__unsize_temp");
81 scratch.storage_live(&bx);
82 operand.val.store(&bx, scratch);
83 base::coerce_unsized_into(&bx, scratch, dest);
84 scratch.storage_dead(&bx);
86 OperandValue::Ref(llref, None, align) => {
87 let source = PlaceRef::new_sized(llref, operand.layout, align);
88 base::coerce_unsized_into(&bx, source, dest);
90 OperandValue::Ref(_, Some(_), _) => {
91 bug!("unsized coercion on an unsized rvalue")
97 mir::Rvalue::Repeat(ref elem, count) => {
98 let cg_elem = self.codegen_operand(&bx, elem);
100 // Do not generate the loop for zero-sized elements or empty arrays.
101 if dest.layout.is_zst() {
105 let start = dest.project_index(&bx, bx.cx().c_usize(0)).llval;
107 if let OperandValue::Immediate(v) = cg_elem.val {
108 let align = bx.cx().c_i32(dest.align.abi() as i32);
109 let size = bx.cx().c_usize(dest.layout.size.bytes());
111 // Use llvm.memset.p0i8.* to initialize all zero arrays
112 if bx.cx().is_const_integral(v) && bx.cx().const_to_uint(v) == 0 {
113 let fill = bx.cx().c_u8(0);
114 base::call_memset(&bx, start, fill, size, align, false);
118 // Use llvm.memset.p0i8.* to initialize byte arrays
119 let v = base::from_immediate(&bx, v);
120 if bx.cx().val_ty(v) == bx.cx().i8() {
121 base::call_memset(&bx, start, v, size, align, false);
126 let count = bx.cx().c_usize(count);
127 let end = dest.project_index(&bx, count).llval;
129 let header_bx = bx.build_sibling_block("repeat_loop_header");
130 let body_bx = bx.build_sibling_block("repeat_loop_body");
131 let next_bx = bx.build_sibling_block("repeat_loop_next");
133 bx.br(header_bx.llbb());
134 let current = header_bx.phi(bx.cx().val_ty(start), &[start], &[bx.llbb()]);
136 let keep_going = header_bx.icmp(IntPredicate::IntNE, current, end);
137 header_bx.cond_br(keep_going, body_bx.llbb(), next_bx.llbb());
139 cg_elem.val.store(&body_bx,
140 PlaceRef::new_sized(current, cg_elem.layout, dest.align));
142 let next = body_bx.inbounds_gep(current, &[bx.cx().c_usize(1)]);
143 body_bx.br(header_bx.llbb());
144 header_bx.add_incoming_to_phi(current, next, body_bx.llbb());
149 mir::Rvalue::Aggregate(ref kind, ref operands) => {
150 let (dest, active_field_index) = match **kind {
151 mir::AggregateKind::Adt(adt_def, variant_index, _, _, active_field_index) => {
152 dest.codegen_set_discr(&bx, variant_index);
153 if adt_def.is_enum() {
154 (dest.project_downcast(&bx, variant_index), active_field_index)
156 (dest, active_field_index)
161 for (i, operand) in operands.iter().enumerate() {
162 let op = self.codegen_operand(&bx, operand);
163 // Do not generate stores and GEPis for zero-sized fields.
164 if !op.layout.is_zst() {
165 let field_index = active_field_index.unwrap_or(i);
166 op.val.store(&bx, dest.project_field(&bx, field_index));
173 assert!(self.rvalue_creates_operand(rvalue));
174 let (bx, temp) = self.codegen_rvalue_operand(bx, rvalue);
175 temp.val.store(&bx, dest);
181 pub fn codegen_rvalue_unsized(&mut self,
182 bx: Builder<'a, 'll, 'tcx>,
183 indirect_dest: PlaceRef<'tcx, &'ll Value>,
184 rvalue: &mir::Rvalue<'tcx>)
185 -> Builder<'a, 'll, 'tcx>
187 debug!("codegen_rvalue_unsized(indirect_dest.llval={:?}, rvalue={:?})",
188 indirect_dest.llval, rvalue);
191 mir::Rvalue::Use(ref operand) => {
192 let cg_operand = self.codegen_operand(&bx, operand);
193 cg_operand.val.store_unsized(&bx, indirect_dest);
197 _ => bug!("unsized assignment other than Rvalue::Use"),
201 pub fn codegen_rvalue_operand(
203 bx: Builder<'a, 'll, 'tcx>,
204 rvalue: &mir::Rvalue<'tcx>
205 ) -> (Builder<'a, 'll, 'tcx>, OperandRef<'tcx, &'ll Value>) {
206 assert!(self.rvalue_creates_operand(rvalue), "cannot codegen {:?} to operand", rvalue);
209 mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
210 let operand = self.codegen_operand(&bx, source);
211 debug!("cast operand is {:?}", operand);
212 let cast = bx.cx().layout_of(self.monomorphize(&mir_cast_ty));
214 let val = match *kind {
215 mir::CastKind::ReifyFnPointer => {
216 match operand.layout.ty.sty {
217 ty::FnDef(def_id, substs) => {
218 if bx.cx().tcx.has_attr(def_id, "rustc_args_required_const") {
219 bug!("reifying a fn ptr that requires \
222 OperandValue::Immediate(
223 callee::resolve_and_get_fn(bx.cx(), def_id, substs))
226 bug!("{} cannot be reified to a fn ptr", operand.layout.ty)
230 mir::CastKind::ClosureFnPointer => {
231 match operand.layout.ty.sty {
232 ty::Closure(def_id, substs) => {
233 let instance = monomorphize::resolve_closure(
234 bx.cx().tcx, def_id, substs, ty::ClosureKind::FnOnce);
235 OperandValue::Immediate(callee::get_fn(bx.cx(), instance))
238 bug!("{} cannot be cast to a fn ptr", operand.layout.ty)
242 mir::CastKind::UnsafeFnPointer => {
243 // this is a no-op at the LLVM level
246 mir::CastKind::Unsize => {
247 assert!(cast.is_llvm_scalar_pair());
249 OperandValue::Pair(lldata, llextra) => {
250 // unsize from a fat pointer - this is a
251 // "trait-object-to-supertrait" coercion, for
253 // &'a fmt::Debug+Send => &'a fmt::Debug,
255 // HACK(eddyb) have to bitcast pointers
256 // until LLVM removes pointee types.
257 let lldata = bx.pointercast(lldata,
258 cast.scalar_pair_element_llvm_type(bx.cx(), 0, true));
259 OperandValue::Pair(lldata, llextra)
261 OperandValue::Immediate(lldata) => {
263 let (lldata, llextra) = base::unsize_thin_ptr(&bx, lldata,
264 operand.layout.ty, cast.ty);
265 OperandValue::Pair(lldata, llextra)
267 OperandValue::Ref(..) => {
268 bug!("by-ref operand {:?} in codegen_rvalue_operand",
273 mir::CastKind::Misc if operand.layout.is_llvm_scalar_pair() => {
274 if let OperandValue::Pair(data_ptr, meta) = operand.val {
275 if cast.is_llvm_scalar_pair() {
276 let data_cast = bx.pointercast(data_ptr,
277 cast.scalar_pair_element_llvm_type(bx.cx(), 0, true));
278 OperandValue::Pair(data_cast, meta)
279 } else { // cast to thin-ptr
280 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
281 // pointer-cast of that pointer to desired pointer type.
282 let llcast_ty = cast.immediate_llvm_type(bx.cx());
283 let llval = bx.pointercast(data_ptr, llcast_ty);
284 OperandValue::Immediate(llval)
287 bug!("Unexpected non-Pair operand")
290 mir::CastKind::Misc => {
291 assert!(cast.is_llvm_immediate());
292 let ll_t_out = cast.immediate_llvm_type(bx.cx());
293 if operand.layout.abi.is_uninhabited() {
294 let val = OperandValue::Immediate(bx.cx().c_undef(ll_t_out));
295 return (bx, OperandRef {
300 let r_t_in = CastTy::from_ty(operand.layout.ty)
301 .expect("bad input type for cast");
302 let r_t_out = CastTy::from_ty(cast.ty).expect("bad output type for cast");
303 let ll_t_in = operand.layout.immediate_llvm_type(bx.cx());
304 match operand.layout.variants {
305 layout::Variants::Single { index } => {
306 if let Some(def) = operand.layout.ty.ty_adt_def() {
308 .discriminant_for_variant(bx.cx().tcx, index)
310 let discr = bx.cx().c_uint_big(ll_t_out, discr_val);
311 return (bx, OperandRef {
312 val: OperandValue::Immediate(discr),
317 layout::Variants::Tagged { .. } |
318 layout::Variants::NicheFilling { .. } => {},
320 let llval = operand.immediate();
322 let mut signed = false;
323 if let layout::Abi::Scalar(ref scalar) = operand.layout.abi {
324 if let layout::Int(_, s) = scalar.value {
325 // We use `i1` for bytes that are always `0` or `1`,
326 // e.g. `#[repr(i8)] enum E { A, B }`, but we can't
327 // let LLVM interpret the `i1` as signed, because
328 // then `i1 1` (i.e. E::B) is effectively `i8 -1`.
329 signed = !scalar.is_bool() && s;
331 let er = scalar.valid_range_exclusive(bx.cx());
332 if er.end != er.start &&
333 scalar.valid_range.end() > scalar.valid_range.start() {
334 // We want `table[e as usize]` to not
335 // have bound checks, and this is the most
336 // convenient place to put the `assume`.
338 base::call_assume(&bx, bx.icmp(
339 IntPredicate::IntULE,
341 bx.cx().c_uint_big(ll_t_in, *scalar.valid_range.end())
347 let newval = match (r_t_in, r_t_out) {
348 (CastTy::Int(_), CastTy::Int(_)) => {
349 bx.intcast(llval, ll_t_out, signed)
351 (CastTy::Float, CastTy::Float) => {
352 let srcsz = bx.cx().float_width(ll_t_in);
353 let dstsz = bx.cx().float_width(ll_t_out);
355 bx.fpext(llval, ll_t_out)
356 } else if srcsz > dstsz {
357 bx.fptrunc(llval, ll_t_out)
362 (CastTy::Ptr(_), CastTy::Ptr(_)) |
363 (CastTy::FnPtr, CastTy::Ptr(_)) |
364 (CastTy::RPtr(_), CastTy::Ptr(_)) =>
365 bx.pointercast(llval, ll_t_out),
366 (CastTy::Ptr(_), CastTy::Int(_)) |
367 (CastTy::FnPtr, CastTy::Int(_)) =>
368 bx.ptrtoint(llval, ll_t_out),
369 (CastTy::Int(_), CastTy::Ptr(_)) => {
370 let usize_llval = bx.intcast(llval, bx.cx().isize_ty, signed);
371 bx.inttoptr(usize_llval, ll_t_out)
373 (CastTy::Int(_), CastTy::Float) =>
374 cast_int_to_float(&bx, signed, llval, ll_t_in, ll_t_out),
375 (CastTy::Float, CastTy::Int(IntTy::I)) =>
376 cast_float_to_int(&bx, true, llval, ll_t_in, ll_t_out),
377 (CastTy::Float, CastTy::Int(_)) =>
378 cast_float_to_int(&bx, false, llval, ll_t_in, ll_t_out),
379 _ => bug!("unsupported cast: {:?} to {:?}", operand.layout.ty, cast.ty)
381 OperandValue::Immediate(newval)
390 mir::Rvalue::Ref(_, bk, ref place) => {
391 let cg_place = self.codegen_place(&bx, place);
393 let ty = cg_place.layout.ty;
395 // Note: places are indirect, so storing the `llval` into the
396 // destination effectively creates a reference.
397 let val = if !bx.cx().type_has_metadata(ty) {
398 OperandValue::Immediate(cg_place.llval)
400 OperandValue::Pair(cg_place.llval, cg_place.llextra.unwrap())
404 layout: self.cx.layout_of(self.cx.tcx.mk_ref(
405 self.cx.tcx.types.re_erased,
406 ty::TypeAndMut { ty, mutbl: bk.to_mutbl_lossy() }
411 mir::Rvalue::Len(ref place) => {
412 let size = self.evaluate_array_len(&bx, place);
413 let operand = OperandRef {
414 val: OperandValue::Immediate(size),
415 layout: bx.cx().layout_of(bx.tcx().types.usize),
420 mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
421 let lhs = self.codegen_operand(&bx, lhs);
422 let rhs = self.codegen_operand(&bx, rhs);
423 let llresult = match (lhs.val, rhs.val) {
424 (OperandValue::Pair(lhs_addr, lhs_extra),
425 OperandValue::Pair(rhs_addr, rhs_extra)) => {
426 self.codegen_fat_ptr_binop(&bx, op,
432 (OperandValue::Immediate(lhs_val),
433 OperandValue::Immediate(rhs_val)) => {
434 self.codegen_scalar_binop(&bx, op, lhs_val, rhs_val, lhs.layout.ty)
439 let operand = OperandRef {
440 val: OperandValue::Immediate(llresult),
441 layout: bx.cx().layout_of(
442 op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
446 mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
447 let lhs = self.codegen_operand(&bx, lhs);
448 let rhs = self.codegen_operand(&bx, rhs);
449 let result = self.codegen_scalar_checked_binop(&bx, op,
450 lhs.immediate(), rhs.immediate(),
452 let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
453 let operand_ty = bx.tcx().intern_tup(&[val_ty, bx.tcx().types.bool]);
454 let operand = OperandRef {
456 layout: bx.cx().layout_of(operand_ty)
462 mir::Rvalue::UnaryOp(op, ref operand) => {
463 let operand = self.codegen_operand(&bx, operand);
464 let lloperand = operand.immediate();
465 let is_float = operand.layout.ty.is_fp();
466 let llval = match op {
467 mir::UnOp::Not => bx.not(lloperand),
468 mir::UnOp::Neg => if is_float {
475 val: OperandValue::Immediate(llval),
476 layout: operand.layout,
480 mir::Rvalue::Discriminant(ref place) => {
481 let discr_ty = rvalue.ty(&*self.mir, bx.tcx());
482 let discr = self.codegen_place(&bx, place)
483 .codegen_get_discr(&bx, discr_ty);
485 val: OperandValue::Immediate(discr),
486 layout: self.cx.layout_of(discr_ty)
490 mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
491 assert!(bx.cx().type_is_sized(ty));
492 let val = bx.cx().c_usize(bx.cx().size_of(ty).bytes());
495 val: OperandValue::Immediate(val),
496 layout: self.cx.layout_of(tcx.types.usize),
500 mir::Rvalue::NullaryOp(mir::NullOp::Box, content_ty) => {
501 let content_ty: Ty<'tcx> = self.monomorphize(&content_ty);
502 let (size, align) = bx.cx().size_and_align_of(content_ty);
503 let llsize = bx.cx().c_usize(size.bytes());
504 let llalign = bx.cx().c_usize(align.abi());
505 let box_layout = bx.cx().layout_of(bx.tcx().mk_box(content_ty));
506 let llty_ptr = box_layout.llvm_type(bx.cx());
509 let def_id = match bx.tcx().lang_items().require(ExchangeMallocFnLangItem) {
512 bx.sess().fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
515 let instance = ty::Instance::mono(bx.tcx(), def_id);
516 let r = callee::get_fn(bx.cx(), instance);
517 let val = bx.pointercast(bx.call(r, &[llsize, llalign], None), llty_ptr);
519 let operand = OperandRef {
520 val: OperandValue::Immediate(val),
525 mir::Rvalue::Use(ref operand) => {
526 let operand = self.codegen_operand(&bx, operand);
529 mir::Rvalue::Repeat(..) |
530 mir::Rvalue::Aggregate(..) => {
531 // According to `rvalue_creates_operand`, only ZST
532 // aggregate rvalues are allowed to be operands.
533 let ty = rvalue.ty(self.mir, self.cx.tcx);
534 (bx, OperandRef::new_zst(self.cx,
535 self.cx.layout_of(self.monomorphize(&ty))))
540 fn evaluate_array_len(
542 bx: &Builder<'a, 'll, 'tcx>,
543 place: &mir::Place<'tcx>,
545 // ZST are passed as operands and require special handling
546 // because codegen_place() panics if Local is operand.
547 if let mir::Place::Local(index) = *place {
548 if let LocalRef::Operand(Some(op)) = self.locals[index] {
549 if let ty::Array(_, n) = op.layout.ty.sty {
550 let n = n.unwrap_usize(bx.cx().tcx);
551 return bx.cx().c_usize(n);
555 // use common size calculation for non zero-sized types
556 let cg_value = self.codegen_place(&bx, place);
557 return cg_value.len(bx.cx());
560 pub fn codegen_scalar_binop(
562 bx: &Builder<'a, 'll, 'tcx>,
568 let is_float = input_ty.is_fp();
569 let is_signed = input_ty.is_signed();
570 let is_unit = input_ty.is_unit();
572 mir::BinOp::Add => if is_float {
577 mir::BinOp::Sub => if is_float {
582 mir::BinOp::Mul => if is_float {
587 mir::BinOp::Div => if is_float {
589 } else if is_signed {
594 mir::BinOp::Rem => if is_float {
596 } else if is_signed {
601 mir::BinOp::BitOr => bx.or(lhs, rhs),
602 mir::BinOp::BitAnd => bx.and(lhs, rhs),
603 mir::BinOp::BitXor => bx.xor(lhs, rhs),
604 mir::BinOp::Offset => bx.inbounds_gep(lhs, &[rhs]),
605 mir::BinOp::Shl => common::build_unchecked_lshift(bx, lhs, rhs),
606 mir::BinOp::Shr => common::build_unchecked_rshift(bx, input_ty, lhs, rhs),
607 mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt |
608 mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => if is_unit {
609 bx.cx().c_bool(match op {
610 mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt => false,
611 mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => true,
616 base::bin_op_to_fcmp_predicate(op.to_hir_binop()),
621 base::bin_op_to_icmp_predicate(op.to_hir_binop(), is_signed),
628 pub fn codegen_fat_ptr_binop(
630 bx: &Builder<'a, 'll, 'tcx>,
632 lhs_addr: &'ll Value,
633 lhs_extra: &'ll Value,
634 rhs_addr: &'ll Value,
635 rhs_extra: &'ll Value,
641 bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr),
642 bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra)
647 bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr),
648 bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra)
651 mir::BinOp::Le | mir::BinOp::Lt |
652 mir::BinOp::Ge | mir::BinOp::Gt => {
653 // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
654 let (op, strict_op) = match op {
655 mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
656 mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
657 mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
658 mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
663 bx.icmp(strict_op, lhs_addr, rhs_addr),
665 bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr),
666 bx.icmp(op, lhs_extra, rhs_extra)
671 bug!("unexpected fat ptr binop");
676 pub fn codegen_scalar_checked_binop(&mut self,
677 bx: &Builder<'a, 'll, 'tcx>,
681 input_ty: Ty<'tcx>) -> OperandValue<&'ll Value> {
682 // This case can currently arise only from functions marked
683 // with #[rustc_inherit_overflow_checks] and inlined from
684 // another crate (mostly core::num generic/#[inline] fns),
685 // while the current crate doesn't use overflow checks.
686 if !bx.cx().check_overflow {
687 let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
688 return OperandValue::Pair(val, bx.cx().c_bool(false));
691 let (val, of) = match op {
692 // These are checked using intrinsics
693 mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
695 mir::BinOp::Add => OverflowOp::Add,
696 mir::BinOp::Sub => OverflowOp::Sub,
697 mir::BinOp::Mul => OverflowOp::Mul,
700 let intrinsic = get_overflow_intrinsic(oop, bx, input_ty);
701 let res = bx.call(intrinsic, &[lhs, rhs], None);
703 (bx.extract_value(res, 0),
704 bx.extract_value(res, 1))
706 mir::BinOp::Shl | mir::BinOp::Shr => {
707 let lhs_llty = bx.cx().val_ty(lhs);
708 let rhs_llty = bx.cx().val_ty(rhs);
709 let invert_mask = common::shift_mask_val(&bx, lhs_llty, rhs_llty, true);
710 let outer_bits = bx.and(rhs, invert_mask);
712 let of = bx.icmp(IntPredicate::IntNE, outer_bits, bx.cx().c_null(rhs_llty));
713 let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
718 bug!("Operator `{:?}` is not a checkable operator", op)
722 OperandValue::Pair(val, of)
725 pub fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>) -> bool {
727 mir::Rvalue::Ref(..) |
728 mir::Rvalue::Len(..) |
729 mir::Rvalue::Cast(..) | // (*)
730 mir::Rvalue::BinaryOp(..) |
731 mir::Rvalue::CheckedBinaryOp(..) |
732 mir::Rvalue::UnaryOp(..) |
733 mir::Rvalue::Discriminant(..) |
734 mir::Rvalue::NullaryOp(..) |
735 mir::Rvalue::Use(..) => // (*)
737 mir::Rvalue::Repeat(..) |
738 mir::Rvalue::Aggregate(..) => {
739 let ty = rvalue.ty(self.mir, self.cx.tcx);
740 let ty = self.monomorphize(&ty);
741 self.cx.layout_of(ty).is_zst()
745 // (*) this is only true if the type is suitable
749 #[derive(Copy, Clone)]
754 fn get_overflow_intrinsic(
756 bx: &Builder<'_, 'll, '_>,
759 use syntax::ast::IntTy::*;
760 use syntax::ast::UintTy::*;
761 use rustc::ty::{Int, Uint};
765 let new_sty = match ty.sty {
766 Int(Isize) => Int(tcx.sess.target.isize_ty),
767 Uint(Usize) => Uint(tcx.sess.target.usize_ty),
768 ref t @ Uint(_) | ref t @ Int(_) => t.clone(),
769 _ => panic!("tried to get overflow intrinsic for op applied to non-int type")
772 let name = match oop {
773 OverflowOp::Add => match new_sty {
774 Int(I8) => "llvm.sadd.with.overflow.i8",
775 Int(I16) => "llvm.sadd.with.overflow.i16",
776 Int(I32) => "llvm.sadd.with.overflow.i32",
777 Int(I64) => "llvm.sadd.with.overflow.i64",
778 Int(I128) => "llvm.sadd.with.overflow.i128",
780 Uint(U8) => "llvm.uadd.with.overflow.i8",
781 Uint(U16) => "llvm.uadd.with.overflow.i16",
782 Uint(U32) => "llvm.uadd.with.overflow.i32",
783 Uint(U64) => "llvm.uadd.with.overflow.i64",
784 Uint(U128) => "llvm.uadd.with.overflow.i128",
788 OverflowOp::Sub => match new_sty {
789 Int(I8) => "llvm.ssub.with.overflow.i8",
790 Int(I16) => "llvm.ssub.with.overflow.i16",
791 Int(I32) => "llvm.ssub.with.overflow.i32",
792 Int(I64) => "llvm.ssub.with.overflow.i64",
793 Int(I128) => "llvm.ssub.with.overflow.i128",
795 Uint(U8) => "llvm.usub.with.overflow.i8",
796 Uint(U16) => "llvm.usub.with.overflow.i16",
797 Uint(U32) => "llvm.usub.with.overflow.i32",
798 Uint(U64) => "llvm.usub.with.overflow.i64",
799 Uint(U128) => "llvm.usub.with.overflow.i128",
803 OverflowOp::Mul => match new_sty {
804 Int(I8) => "llvm.smul.with.overflow.i8",
805 Int(I16) => "llvm.smul.with.overflow.i16",
806 Int(I32) => "llvm.smul.with.overflow.i32",
807 Int(I64) => "llvm.smul.with.overflow.i64",
808 Int(I128) => "llvm.smul.with.overflow.i128",
810 Uint(U8) => "llvm.umul.with.overflow.i8",
811 Uint(U16) => "llvm.umul.with.overflow.i16",
812 Uint(U32) => "llvm.umul.with.overflow.i32",
813 Uint(U64) => "llvm.umul.with.overflow.i64",
814 Uint(U128) => "llvm.umul.with.overflow.i128",
820 bx.cx().get_intrinsic(&name)
823 fn cast_int_to_float(bx: &Builder<'_, 'll, '_>,
827 float_ty: &'ll Type) -> &'ll Value {
828 // Most integer types, even i128, fit into [-f32::MAX, f32::MAX] after rounding.
829 // It's only u128 -> f32 that can cause overflows (i.e., should yield infinity).
830 // LLVM's uitofp produces undef in those cases, so we manually check for that case.
831 let is_u128_to_f32 = !signed &&
832 bx.cx().int_width(int_ty) == 128 &&
833 bx.cx().float_width(float_ty) == 32;
835 // All inputs greater or equal to (f32::MAX + 0.5 ULP) are rounded to infinity,
836 // and for everything else LLVM's uitofp works just fine.
837 use rustc_apfloat::ieee::Single;
838 use rustc_apfloat::Float;
839 const MAX_F32_PLUS_HALF_ULP: u128 = ((1 << (Single::PRECISION + 1)) - 1)
840 << (Single::MAX_EXP - Single::PRECISION as i16);
841 let max = bx.cx().c_uint_big(int_ty, MAX_F32_PLUS_HALF_ULP);
842 let overflow = bx.icmp(IntPredicate::IntUGE, x, max);
843 let infinity_bits = bx.cx().c_u32(ieee::Single::INFINITY.to_bits() as u32);
844 let infinity = consts::bitcast(infinity_bits, float_ty);
845 bx.select(overflow, infinity, bx.uitofp(x, float_ty))
848 bx.sitofp(x, float_ty)
850 bx.uitofp(x, float_ty)
855 fn cast_float_to_int(bx: &Builder<'_, 'll, '_>,
859 int_ty: &'ll Type) -> &'ll Value {
860 let fptosui_result = if signed {
866 if !bx.sess().opts.debugging_opts.saturating_float_casts {
867 return fptosui_result;
869 // LLVM's fpto[su]i returns undef when the input x is infinite, NaN, or does not fit into the
870 // destination integer type after rounding towards zero. This `undef` value can cause UB in
871 // safe code (see issue #10184), so we implement a saturating conversion on top of it:
872 // Semantically, the mathematical value of the input is rounded towards zero to the next
873 // mathematical integer, and then the result is clamped into the range of the destination
874 // integer type. Positive and negative infinity are mapped to the maximum and minimum value of
875 // the destination integer type. NaN is mapped to 0.
877 // Define f_min and f_max as the largest and smallest (finite) floats that are exactly equal to
878 // a value representable in int_ty.
879 // They are exactly equal to int_ty::{MIN,MAX} if float_ty has enough significand bits.
880 // Otherwise, int_ty::MAX must be rounded towards zero, as it is one less than a power of two.
881 // int_ty::MIN, however, is either zero or a negative power of two and is thus exactly
882 // representable. Note that this only works if float_ty's exponent range is sufficiently large.
883 // f16 or 256 bit integers would break this property. Right now the smallest float type is f32
884 // with exponents ranging up to 127, which is barely enough for i128::MIN = -2^127.
885 // On the other hand, f_max works even if int_ty::MAX is greater than float_ty::MAX. Because
886 // we're rounding towards zero, we just get float_ty::MAX (which is always an integer).
887 // This already happens today with u128::MAX = 2^128 - 1 > f32::MAX.
888 let int_max = |signed: bool, int_ty: &'ll Type| -> u128 {
889 let shift_amount = 128 - bx.cx().int_width(int_ty);
891 i128::MAX as u128 >> shift_amount
893 u128::MAX >> shift_amount
896 let int_min = |signed: bool, int_ty: &'ll Type| -> i128 {
898 i128::MIN >> (128 - bx.cx().int_width(int_ty))
904 let compute_clamp_bounds_single = |signed: bool, int_ty: &'ll Type| -> (u128, u128) {
905 let rounded_min = ieee::Single::from_i128_r(int_min(signed, int_ty), Round::TowardZero);
906 assert_eq!(rounded_min.status, Status::OK);
907 let rounded_max = ieee::Single::from_u128_r(int_max(signed, int_ty), Round::TowardZero);
908 assert!(rounded_max.value.is_finite());
909 (rounded_min.value.to_bits(), rounded_max.value.to_bits())
911 let compute_clamp_bounds_double = |signed: bool, int_ty: &'ll Type| -> (u128, u128) {
912 let rounded_min = ieee::Double::from_i128_r(int_min(signed, int_ty), Round::TowardZero);
913 assert_eq!(rounded_min.status, Status::OK);
914 let rounded_max = ieee::Double::from_u128_r(int_max(signed, int_ty), Round::TowardZero);
915 assert!(rounded_max.value.is_finite());
916 (rounded_min.value.to_bits(), rounded_max.value.to_bits())
919 let float_bits_to_llval = |bits| {
920 let bits_llval = match bx.cx().float_width(float_ty) {
921 32 => bx.cx().c_u32(bits as u32),
922 64 => bx.cx().c_u64(bits as u64),
923 n => bug!("unsupported float width {}", n),
925 consts::bitcast(bits_llval, float_ty)
927 let (f_min, f_max) = match bx.cx().float_width(float_ty) {
928 32 => compute_clamp_bounds_single(signed, int_ty),
929 64 => compute_clamp_bounds_double(signed, int_ty),
930 n => bug!("unsupported float width {}", n),
932 let f_min = float_bits_to_llval(f_min);
933 let f_max = float_bits_to_llval(f_max);
934 // To implement saturation, we perform the following steps:
936 // 1. Cast x to an integer with fpto[su]i. This may result in undef.
937 // 2. Compare x to f_min and f_max, and use the comparison results to select:
938 // a) int_ty::MIN if x < f_min or x is NaN
939 // b) int_ty::MAX if x > f_max
940 // c) the result of fpto[su]i otherwise
941 // 3. If x is NaN, return 0.0, otherwise return the result of step 2.
943 // This avoids resulting undef because values in range [f_min, f_max] by definition fit into the
944 // destination type. It creates an undef temporary, but *producing* undef is not UB. Our use of
945 // undef does not introduce any non-determinism either.
946 // More importantly, the above procedure correctly implements saturating conversion.
948 // If x is NaN, 0 is returned by definition.
949 // Otherwise, x is finite or infinite and thus can be compared with f_min and f_max.
950 // This yields three cases to consider:
951 // (1) if x in [f_min, f_max], the result of fpto[su]i is returned, which agrees with
952 // saturating conversion for inputs in that range.
953 // (2) if x > f_max, then x is larger than int_ty::MAX. This holds even if f_max is rounded
954 // (i.e., if f_max < int_ty::MAX) because in those cases, nextUp(f_max) is already larger
955 // than int_ty::MAX. Because x is larger than int_ty::MAX, the return value of int_ty::MAX
957 // (3) if x < f_min, then x is smaller than int_ty::MIN. As shown earlier, f_min exactly equals
958 // int_ty::MIN and therefore the return value of int_ty::MIN is correct.
961 // Step 1 was already performed above.
963 // Step 2: We use two comparisons and two selects, with %s1 being the result:
964 // %less_or_nan = fcmp ult %x, %f_min
965 // %greater = fcmp olt %x, %f_max
966 // %s0 = select %less_or_nan, int_ty::MIN, %fptosi_result
967 // %s1 = select %greater, int_ty::MAX, %s0
968 // Note that %less_or_nan uses an *unordered* comparison. This comparison is true if the
969 // operands are not comparable (i.e., if x is NaN). The unordered comparison ensures that s1
970 // becomes int_ty::MIN if x is NaN.
971 // Performance note: Unordered comparison can be lowered to a "flipped" comparison and a
972 // negation, and the negation can be merged into the select. Therefore, it not necessarily any
973 // more expensive than a ordered ("normal") comparison. Whether these optimizations will be
974 // performed is ultimately up to the backend, but at least x86 does perform them.
975 let less_or_nan = bx.fcmp(RealPredicate::RealULT, x, f_min);
976 let greater = bx.fcmp(RealPredicate::RealOGT, x, f_max);
977 let int_max = bx.cx().c_uint_big(int_ty, int_max(signed, int_ty));
978 let int_min = bx.cx().c_uint_big(int_ty, int_min(signed, int_ty) as u128);
979 let s0 = bx.select(less_or_nan, int_min, fptosui_result);
980 let s1 = bx.select(greater, int_max, s0);
982 // Step 3: NaN replacement.
983 // For unsigned types, the above step already yielded int_ty::MIN == 0 if x is NaN.
984 // Therefore we only need to execute this step for signed integer types.
986 // LLVM has no isNaN predicate, so we use (x == x) instead
987 bx.select(bx.fcmp(RealPredicate::RealOEQ, x, x), s1, bx.cx().c_uint(int_ty, 0))