1 use rustc::ty::{self, Ty, adjustment::{PointerCast}, Instance};
2 use rustc::ty::cast::{CastTy, IntTy};
3 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt};
5 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
6 use rustc_apfloat::{ieee, Float, Status, Round};
8 use syntax::symbol::sym;
9 use syntax::source_map::{DUMMY_SP, Span};
14 use crate::common::{self, RealPredicate, IntPredicate};
18 use super::{FunctionCx, LocalRef};
19 use super::operand::{OperandRef, OperandValue};
20 use super::place::PlaceRef;
22 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
23 pub fn codegen_rvalue(
26 dest: PlaceRef<'tcx, Bx::Value>,
27 rvalue: &mir::Rvalue<'tcx>
29 debug!("codegen_rvalue(dest.llval={:?}, rvalue={:?})",
33 mir::Rvalue::Use(ref operand) => {
34 let cg_operand = self.codegen_operand(&mut bx, operand);
35 // FIXME: consider not copying constants through stack. (fixable by codegenning
36 // constants into OperandValue::Ref, why don’t we do that yet if we don’t?)
37 cg_operand.val.store(&mut bx, dest);
41 mir::Rvalue::Cast(mir::CastKind::Pointer(PointerCast::Unsize), ref source, _) => {
42 // The destination necessarily contains a fat pointer, so if
43 // it's a scalar pair, it's a fat pointer or newtype thereof.
44 if bx.cx().is_backend_scalar_pair(dest.layout) {
45 // into-coerce of a thin pointer to a fat pointer - just
46 // use the operand path.
47 let (mut bx, temp) = self.codegen_rvalue_operand(bx, rvalue);
48 temp.val.store(&mut bx, dest);
52 // Unsize of a nontrivial struct. I would prefer for
53 // this to be eliminated by MIR building, but
54 // `CoerceUnsized` can be passed by a where-clause,
55 // so the (generic) MIR may not be able to expand it.
56 let operand = self.codegen_operand(&mut bx, source);
58 OperandValue::Pair(..) |
59 OperandValue::Immediate(_) => {
60 // unsize from an immediate structure. We don't
61 // really need a temporary alloca here, but
62 // avoiding it would require us to have
63 // `coerce_unsized_into` use extractvalue to
64 // index into the struct, and this case isn't
65 // important enough for it.
66 debug!("codegen_rvalue: creating ugly alloca");
67 let scratch = PlaceRef::alloca(&mut bx, operand.layout, "__unsize_temp");
68 scratch.storage_live(&mut bx);
69 operand.val.store(&mut bx, scratch);
70 base::coerce_unsized_into(&mut bx, scratch, dest);
71 scratch.storage_dead(&mut bx);
73 OperandValue::Ref(llref, None, align) => {
74 let source = PlaceRef::new_sized_aligned(llref, operand.layout, align);
75 base::coerce_unsized_into(&mut bx, source, dest);
77 OperandValue::Ref(_, Some(_), _) => {
78 bug!("unsized coercion on an unsized rvalue")
84 mir::Rvalue::Repeat(ref elem, count) => {
85 let cg_elem = self.codegen_operand(&mut bx, elem);
87 // Do not generate the loop for zero-sized elements or empty arrays.
88 if dest.layout.is_zst() {
92 if let OperandValue::Immediate(v) = cg_elem.val {
93 let zero = bx.const_usize(0);
94 let start = dest.project_index(&mut bx, zero).llval;
95 let size = bx.const_usize(dest.layout.size.bytes());
97 // Use llvm.memset.p0i8.* to initialize all zero arrays
98 if bx.cx().is_const_integral(v) && bx.cx().const_to_uint(v) == 0 {
99 let fill = bx.cx().const_u8(0);
100 bx.memset(start, fill, size, dest.align, MemFlags::empty());
104 // Use llvm.memset.p0i8.* to initialize byte arrays
105 let v = base::from_immediate(&mut bx, v);
106 if bx.cx().val_ty(v) == bx.cx().type_i8() {
107 bx.memset(start, v, size, dest.align, MemFlags::empty());
112 bx.write_operand_repeatedly(cg_elem, count, dest)
115 mir::Rvalue::Aggregate(ref kind, ref operands) => {
116 let (dest, active_field_index) = match **kind {
117 mir::AggregateKind::Adt(adt_def, variant_index, _, _, active_field_index) => {
118 dest.codegen_set_discr(&mut bx, variant_index);
119 if adt_def.is_enum() {
120 (dest.project_downcast(&mut bx, variant_index), active_field_index)
122 (dest, active_field_index)
127 for (i, operand) in operands.iter().enumerate() {
128 let op = self.codegen_operand(&mut bx, operand);
129 // Do not generate stores and GEPis for zero-sized fields.
130 if !op.layout.is_zst() {
131 let field_index = active_field_index.unwrap_or(i);
132 let field = dest.project_field(&mut bx, field_index);
133 op.val.store(&mut bx, field);
140 assert!(self.rvalue_creates_operand(rvalue, DUMMY_SP));
141 let (mut bx, temp) = self.codegen_rvalue_operand(bx, rvalue);
142 temp.val.store(&mut bx, dest);
148 pub fn codegen_rvalue_unsized(
151 indirect_dest: PlaceRef<'tcx, Bx::Value>,
152 rvalue: &mir::Rvalue<'tcx>,
154 debug!("codegen_rvalue_unsized(indirect_dest.llval={:?}, rvalue={:?})",
155 indirect_dest.llval, rvalue);
158 mir::Rvalue::Use(ref operand) => {
159 let cg_operand = self.codegen_operand(&mut bx, operand);
160 cg_operand.val.store_unsized(&mut bx, indirect_dest);
164 _ => bug!("unsized assignment other than Rvalue::Use"),
168 pub fn codegen_rvalue_operand(
171 rvalue: &mir::Rvalue<'tcx>
172 ) -> (Bx, OperandRef<'tcx, Bx::Value>) {
174 self.rvalue_creates_operand(rvalue, DUMMY_SP),
175 "cannot codegen {:?} to operand",
180 mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
181 let operand = self.codegen_operand(&mut bx, source);
182 debug!("cast operand is {:?}", operand);
183 let cast = bx.cx().layout_of(self.monomorphize(&mir_cast_ty));
185 let val = match *kind {
186 mir::CastKind::Pointer(PointerCast::ReifyFnPointer) => {
187 match operand.layout.ty.sty {
188 ty::FnDef(def_id, substs) => {
189 if bx.cx().tcx().has_attr(def_id, sym::rustc_args_required_const) {
190 bug!("reifying a fn ptr that requires const arguments");
192 OperandValue::Immediate(
193 callee::resolve_and_get_fn(bx.cx(), def_id, substs))
196 bug!("{} cannot be reified to a fn ptr", operand.layout.ty)
200 mir::CastKind::Pointer(PointerCast::ClosureFnPointer(_)) => {
201 match operand.layout.ty.sty {
202 ty::Closure(def_id, substs) => {
203 let instance = Instance::resolve_closure(
204 bx.cx().tcx(), def_id, substs, ty::ClosureKind::FnOnce);
205 OperandValue::Immediate(bx.cx().get_fn(instance))
208 bug!("{} cannot be cast to a fn ptr", operand.layout.ty)
212 mir::CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
213 // this is a no-op at the LLVM level
216 mir::CastKind::Pointer(PointerCast::Unsize) => {
217 assert!(bx.cx().is_backend_scalar_pair(cast));
219 OperandValue::Pair(lldata, llextra) => {
220 // unsize from a fat pointer - this is a
221 // "trait-object-to-supertrait" coercion, for
223 // &'a fmt::Debug+Send => &'a fmt::Debug,
225 // HACK(eddyb) have to bitcast pointers
226 // until LLVM removes pointee types.
227 let lldata = bx.pointercast(lldata,
228 bx.cx().scalar_pair_element_backend_type(cast, 0, true));
229 OperandValue::Pair(lldata, llextra)
231 OperandValue::Immediate(lldata) => {
233 let (lldata, llextra) = base::unsize_thin_ptr(&mut bx, lldata,
234 operand.layout.ty, cast.ty);
235 OperandValue::Pair(lldata, llextra)
237 OperandValue::Ref(..) => {
238 bug!("by-ref operand {:?} in codegen_rvalue_operand",
243 mir::CastKind::Pointer(PointerCast::MutToConstPointer)
244 | mir::CastKind::Misc if bx.cx().is_backend_scalar_pair(operand.layout) => {
245 if let OperandValue::Pair(data_ptr, meta) = operand.val {
246 if bx.cx().is_backend_scalar_pair(cast) {
247 let data_cast = bx.pointercast(data_ptr,
248 bx.cx().scalar_pair_element_backend_type(cast, 0, true));
249 OperandValue::Pair(data_cast, meta)
250 } else { // cast to thin-ptr
251 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
252 // pointer-cast of that pointer to desired pointer type.
253 let llcast_ty = bx.cx().immediate_backend_type(cast);
254 let llval = bx.pointercast(data_ptr, llcast_ty);
255 OperandValue::Immediate(llval)
258 bug!("Unexpected non-Pair operand")
261 mir::CastKind::Pointer(PointerCast::MutToConstPointer)
262 | mir::CastKind::Misc => {
263 assert!(bx.cx().is_backend_immediate(cast));
264 let ll_t_out = bx.cx().immediate_backend_type(cast);
265 if operand.layout.abi.is_uninhabited() {
266 let val = OperandValue::Immediate(bx.cx().const_undef(ll_t_out));
267 return (bx, OperandRef {
272 let r_t_in = CastTy::from_ty(operand.layout.ty)
273 .expect("bad input type for cast");
274 let r_t_out = CastTy::from_ty(cast.ty).expect("bad output type for cast");
275 let ll_t_in = bx.cx().immediate_backend_type(operand.layout);
276 match operand.layout.variants {
277 layout::Variants::Single { index } => {
279 operand.layout.ty.discriminant_for_variant(bx.tcx(), index)
281 let discr_val = bx.cx().const_uint_big(ll_t_out, discr.val);
282 return (bx, OperandRef {
283 val: OperandValue::Immediate(discr_val),
288 layout::Variants::Multiple { .. } => {},
290 let llval = operand.immediate();
292 let mut signed = false;
293 if let layout::Abi::Scalar(ref scalar) = operand.layout.abi {
294 if let layout::Int(_, s) = scalar.value {
295 // We use `i1` for bytes that are always `0` or `1`,
296 // e.g., `#[repr(i8)] enum E { A, B }`, but we can't
297 // let LLVM interpret the `i1` as signed, because
298 // then `i1 1` (i.e., E::B) is effectively `i8 -1`.
299 signed = !scalar.is_bool() && s;
301 let er = scalar.valid_range_exclusive(bx.cx());
302 if er.end != er.start &&
303 scalar.valid_range.end() > scalar.valid_range.start() {
304 // We want `table[e as usize]` to not
305 // have bound checks, and this is the most
306 // convenient place to put the `assume`.
308 bx.cx().const_uint_big(ll_t_in, *scalar.valid_range.end());
310 IntPredicate::IntULE,
319 let newval = match (r_t_in, r_t_out) {
320 (CastTy::Int(_), CastTy::Int(_)) => {
321 bx.intcast(llval, ll_t_out, signed)
323 (CastTy::Float, CastTy::Float) => {
324 let srcsz = bx.cx().float_width(ll_t_in);
325 let dstsz = bx.cx().float_width(ll_t_out);
327 bx.fpext(llval, ll_t_out)
328 } else if srcsz > dstsz {
329 bx.fptrunc(llval, ll_t_out)
334 (CastTy::Ptr(_), CastTy::Ptr(_)) |
335 (CastTy::FnPtr, CastTy::Ptr(_)) |
336 (CastTy::RPtr(_), CastTy::Ptr(_)) =>
337 bx.pointercast(llval, ll_t_out),
338 (CastTy::Ptr(_), CastTy::Int(_)) |
339 (CastTy::FnPtr, CastTy::Int(_)) =>
340 bx.ptrtoint(llval, ll_t_out),
341 (CastTy::Int(_), CastTy::Ptr(_)) => {
342 let usize_llval = bx.intcast(llval, bx.cx().type_isize(), signed);
343 bx.inttoptr(usize_llval, ll_t_out)
345 (CastTy::Int(_), CastTy::Float) =>
346 cast_int_to_float(&mut bx, signed, llval, ll_t_in, ll_t_out),
347 (CastTy::Float, CastTy::Int(IntTy::I)) =>
348 cast_float_to_int(&mut bx, true, llval, ll_t_in, ll_t_out),
349 (CastTy::Float, CastTy::Int(_)) =>
350 cast_float_to_int(&mut bx, false, llval, ll_t_in, ll_t_out),
351 _ => bug!("unsupported cast: {:?} to {:?}", operand.layout.ty, cast.ty)
353 OperandValue::Immediate(newval)
362 mir::Rvalue::Ref(_, bk, ref place) => {
363 let cg_place = self.codegen_place(&mut bx, &place.as_ref());
365 let ty = cg_place.layout.ty;
367 // Note: places are indirect, so storing the `llval` into the
368 // destination effectively creates a reference.
369 let val = if !bx.cx().type_has_metadata(ty) {
370 OperandValue::Immediate(cg_place.llval)
372 OperandValue::Pair(cg_place.llval, cg_place.llextra.unwrap())
376 layout: self.cx.layout_of(self.cx.tcx().mk_ref(
377 self.cx.tcx().lifetimes.re_erased,
378 ty::TypeAndMut { ty, mutbl: bk.to_mutbl_lossy() }
383 mir::Rvalue::Len(ref place) => {
384 let size = self.evaluate_array_len(&mut bx, place);
385 let operand = OperandRef {
386 val: OperandValue::Immediate(size),
387 layout: bx.cx().layout_of(bx.tcx().types.usize),
392 mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
393 let lhs = self.codegen_operand(&mut bx, lhs);
394 let rhs = self.codegen_operand(&mut bx, rhs);
395 let llresult = match (lhs.val, rhs.val) {
396 (OperandValue::Pair(lhs_addr, lhs_extra),
397 OperandValue::Pair(rhs_addr, rhs_extra)) => {
398 self.codegen_fat_ptr_binop(&mut bx, op,
404 (OperandValue::Immediate(lhs_val),
405 OperandValue::Immediate(rhs_val)) => {
406 self.codegen_scalar_binop(&mut bx, op, lhs_val, rhs_val, lhs.layout.ty)
411 let operand = OperandRef {
412 val: OperandValue::Immediate(llresult),
413 layout: bx.cx().layout_of(
414 op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
418 mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
419 let lhs = self.codegen_operand(&mut bx, lhs);
420 let rhs = self.codegen_operand(&mut bx, rhs);
421 let result = self.codegen_scalar_checked_binop(&mut bx, op,
422 lhs.immediate(), rhs.immediate(),
424 let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
425 let operand_ty = bx.tcx().intern_tup(&[val_ty, bx.tcx().types.bool]);
426 let operand = OperandRef {
428 layout: bx.cx().layout_of(operand_ty)
434 mir::Rvalue::UnaryOp(op, ref operand) => {
435 let operand = self.codegen_operand(&mut bx, operand);
436 let lloperand = operand.immediate();
437 let is_float = operand.layout.ty.is_floating_point();
438 let llval = match op {
439 mir::UnOp::Not => bx.not(lloperand),
440 mir::UnOp::Neg => if is_float {
447 val: OperandValue::Immediate(llval),
448 layout: operand.layout,
452 mir::Rvalue::Discriminant(ref place) => {
453 let discr_ty = rvalue.ty(&*self.mir, bx.tcx());
454 let discr = self.codegen_place(&mut bx, &place.as_ref())
455 .codegen_get_discr(&mut bx, discr_ty);
457 val: OperandValue::Immediate(discr),
458 layout: self.cx.layout_of(discr_ty)
462 mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
463 assert!(bx.cx().type_is_sized(ty));
464 let val = bx.cx().const_usize(bx.cx().layout_of(ty).size.bytes());
465 let tcx = self.cx.tcx();
467 val: OperandValue::Immediate(val),
468 layout: self.cx.layout_of(tcx.types.usize),
472 mir::Rvalue::NullaryOp(mir::NullOp::Box, content_ty) => {
473 let content_ty = self.monomorphize(&content_ty);
474 let content_layout = bx.cx().layout_of(content_ty);
475 let llsize = bx.cx().const_usize(content_layout.size.bytes());
476 let llalign = bx.cx().const_usize(content_layout.align.abi.bytes());
477 let box_layout = bx.cx().layout_of(bx.tcx().mk_box(content_ty));
478 let llty_ptr = bx.cx().backend_type(box_layout);
481 let def_id = match bx.tcx().lang_items().require(ExchangeMallocFnLangItem) {
484 bx.cx().sess().fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
487 let instance = ty::Instance::mono(bx.tcx(), def_id);
488 let r = bx.cx().get_fn(instance);
489 let call = bx.call(r, &[llsize, llalign], None);
490 let val = bx.pointercast(call, llty_ptr);
492 let operand = OperandRef {
493 val: OperandValue::Immediate(val),
498 mir::Rvalue::Use(ref operand) => {
499 let operand = self.codegen_operand(&mut bx, operand);
502 mir::Rvalue::Repeat(..) |
503 mir::Rvalue::Aggregate(..) => {
504 // According to `rvalue_creates_operand`, only ZST
505 // aggregate rvalues are allowed to be operands.
506 let ty = rvalue.ty(self.mir, self.cx.tcx());
507 let operand = OperandRef::new_zst(
509 self.cx.layout_of(self.monomorphize(&ty)),
516 fn evaluate_array_len(
519 place: &mir::Place<'tcx>,
521 // ZST are passed as operands and require special handling
522 // because codegen_place() panics if Local is operand.
524 base: mir::PlaceBase::Local(index),
527 if let LocalRef::Operand(Some(op)) = self.locals[index] {
528 if let ty::Array(_, n) = op.layout.ty.sty {
529 let n = n.eval_usize(bx.cx().tcx(), ty::ParamEnv::reveal_all());
530 return bx.cx().const_usize(n);
534 // use common size calculation for non zero-sized types
535 let cg_value = self.codegen_place(bx, &place.as_ref());
536 cg_value.len(bx.cx())
539 pub fn codegen_scalar_binop(
547 let is_float = input_ty.is_floating_point();
548 let is_signed = input_ty.is_signed();
549 let is_unit = input_ty.is_unit();
551 mir::BinOp::Add => if is_float {
556 mir::BinOp::Sub => if is_float {
561 mir::BinOp::Mul => if is_float {
566 mir::BinOp::Div => if is_float {
568 } else if is_signed {
573 mir::BinOp::Rem => if is_float {
575 } else if is_signed {
580 mir::BinOp::BitOr => bx.or(lhs, rhs),
581 mir::BinOp::BitAnd => bx.and(lhs, rhs),
582 mir::BinOp::BitXor => bx.xor(lhs, rhs),
583 mir::BinOp::Offset => bx.inbounds_gep(lhs, &[rhs]),
584 mir::BinOp::Shl => common::build_unchecked_lshift(bx, lhs, rhs),
585 mir::BinOp::Shr => common::build_unchecked_rshift(bx, input_ty, lhs, rhs),
586 mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt |
587 mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => if is_unit {
588 bx.cx().const_bool(match op {
589 mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt => false,
590 mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => true,
595 base::bin_op_to_fcmp_predicate(op.to_hir_binop()),
600 base::bin_op_to_icmp_predicate(op.to_hir_binop(), is_signed),
607 pub fn codegen_fat_ptr_binop(
612 lhs_extra: Bx::Value,
614 rhs_extra: Bx::Value,
619 let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
620 let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
624 let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
625 let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
628 mir::BinOp::Le | mir::BinOp::Lt |
629 mir::BinOp::Ge | mir::BinOp::Gt => {
630 // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
631 let (op, strict_op) = match op {
632 mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
633 mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
634 mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
635 mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
638 let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
639 let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
640 let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
641 let rhs = bx.and(and_lhs, and_rhs);
645 bug!("unexpected fat ptr binop");
650 pub fn codegen_scalar_checked_binop(
657 ) -> OperandValue<Bx::Value> {
658 // This case can currently arise only from functions marked
659 // with #[rustc_inherit_overflow_checks] and inlined from
660 // another crate (mostly core::num generic/#[inline] fns),
661 // while the current crate doesn't use overflow checks.
662 if !bx.cx().check_overflow() {
663 let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
664 return OperandValue::Pair(val, bx.cx().const_bool(false));
667 let (val, of) = match op {
668 // These are checked using intrinsics
669 mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
671 mir::BinOp::Add => OverflowOp::Add,
672 mir::BinOp::Sub => OverflowOp::Sub,
673 mir::BinOp::Mul => OverflowOp::Mul,
676 bx.checked_binop(oop, input_ty, lhs, rhs)
678 mir::BinOp::Shl | mir::BinOp::Shr => {
679 let lhs_llty = bx.cx().val_ty(lhs);
680 let rhs_llty = bx.cx().val_ty(rhs);
681 let invert_mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, true);
682 let outer_bits = bx.and(rhs, invert_mask);
684 let of = bx.icmp(IntPredicate::IntNE, outer_bits, bx.cx().const_null(rhs_llty));
685 let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
690 bug!("Operator `{:?}` is not a checkable operator", op)
694 OperandValue::Pair(val, of)
698 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
699 pub fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>, span: Span) -> bool {
701 mir::Rvalue::Ref(..) |
702 mir::Rvalue::Len(..) |
703 mir::Rvalue::Cast(..) | // (*)
704 mir::Rvalue::BinaryOp(..) |
705 mir::Rvalue::CheckedBinaryOp(..) |
706 mir::Rvalue::UnaryOp(..) |
707 mir::Rvalue::Discriminant(..) |
708 mir::Rvalue::NullaryOp(..) |
709 mir::Rvalue::Use(..) => // (*)
711 mir::Rvalue::Repeat(..) |
712 mir::Rvalue::Aggregate(..) => {
713 let ty = rvalue.ty(self.mir, self.cx.tcx());
714 let ty = self.monomorphize(&ty);
715 self.cx.spanned_layout_of(ty, span).is_zst()
719 // (*) this is only true if the type is suitable
723 fn cast_int_to_float<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
730 // Most integer types, even i128, fit into [-f32::MAX, f32::MAX] after rounding.
731 // It's only u128 -> f32 that can cause overflows (i.e., should yield infinity).
732 // LLVM's uitofp produces undef in those cases, so we manually check for that case.
733 let is_u128_to_f32 = !signed &&
734 bx.cx().int_width(int_ty) == 128 &&
735 bx.cx().float_width(float_ty) == 32;
737 // All inputs greater or equal to (f32::MAX + 0.5 ULP) are rounded to infinity,
738 // and for everything else LLVM's uitofp works just fine.
739 use rustc_apfloat::ieee::Single;
740 const MAX_F32_PLUS_HALF_ULP: u128 = ((1 << (Single::PRECISION + 1)) - 1)
741 << (Single::MAX_EXP - Single::PRECISION as i16);
742 let max = bx.cx().const_uint_big(int_ty, MAX_F32_PLUS_HALF_ULP);
743 let overflow = bx.icmp(IntPredicate::IntUGE, x, max);
744 let infinity_bits = bx.cx().const_u32(ieee::Single::INFINITY.to_bits() as u32);
745 let infinity = bx.bitcast(infinity_bits, float_ty);
746 let fp = bx.uitofp(x, float_ty);
747 bx.select(overflow, infinity, fp)
750 bx.sitofp(x, float_ty)
752 bx.uitofp(x, float_ty)
757 fn cast_float_to_int<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
764 let fptosui_result = if signed {
770 if !bx.cx().sess().opts.debugging_opts.saturating_float_casts {
771 return fptosui_result;
774 let int_width = bx.cx().int_width(int_ty);
775 let float_width = bx.cx().float_width(float_ty);
776 // LLVM's fpto[su]i returns undef when the input x is infinite, NaN, or does not fit into the
777 // destination integer type after rounding towards zero. This `undef` value can cause UB in
778 // safe code (see issue #10184), so we implement a saturating conversion on top of it:
779 // Semantically, the mathematical value of the input is rounded towards zero to the next
780 // mathematical integer, and then the result is clamped into the range of the destination
781 // integer type. Positive and negative infinity are mapped to the maximum and minimum value of
782 // the destination integer type. NaN is mapped to 0.
784 // Define f_min and f_max as the largest and smallest (finite) floats that are exactly equal to
785 // a value representable in int_ty.
786 // They are exactly equal to int_ty::{MIN,MAX} if float_ty has enough significand bits.
787 // Otherwise, int_ty::MAX must be rounded towards zero, as it is one less than a power of two.
788 // int_ty::MIN, however, is either zero or a negative power of two and is thus exactly
789 // representable. Note that this only works if float_ty's exponent range is sufficiently large.
790 // f16 or 256 bit integers would break this property. Right now the smallest float type is f32
791 // with exponents ranging up to 127, which is barely enough for i128::MIN = -2^127.
792 // On the other hand, f_max works even if int_ty::MAX is greater than float_ty::MAX. Because
793 // we're rounding towards zero, we just get float_ty::MAX (which is always an integer).
794 // This already happens today with u128::MAX = 2^128 - 1 > f32::MAX.
795 let int_max = |signed: bool, int_width: u64| -> u128 {
796 let shift_amount = 128 - int_width;
798 i128::MAX as u128 >> shift_amount
800 u128::MAX >> shift_amount
803 let int_min = |signed: bool, int_width: u64| -> i128 {
805 i128::MIN >> (128 - int_width)
811 let compute_clamp_bounds_single =
812 |signed: bool, int_width: u64| -> (u128, u128) {
813 let rounded_min = ieee::Single::from_i128_r(int_min(signed, int_width), Round::TowardZero);
814 assert_eq!(rounded_min.status, Status::OK);
815 let rounded_max = ieee::Single::from_u128_r(int_max(signed, int_width), Round::TowardZero);
816 assert!(rounded_max.value.is_finite());
817 (rounded_min.value.to_bits(), rounded_max.value.to_bits())
819 let compute_clamp_bounds_double =
820 |signed: bool, int_width: u64| -> (u128, u128) {
821 let rounded_min = ieee::Double::from_i128_r(int_min(signed, int_width), Round::TowardZero);
822 assert_eq!(rounded_min.status, Status::OK);
823 let rounded_max = ieee::Double::from_u128_r(int_max(signed, int_width), Round::TowardZero);
824 assert!(rounded_max.value.is_finite());
825 (rounded_min.value.to_bits(), rounded_max.value.to_bits())
828 let mut float_bits_to_llval = |bits| {
829 let bits_llval = match float_width {
830 32 => bx.cx().const_u32(bits as u32),
831 64 => bx.cx().const_u64(bits as u64),
832 n => bug!("unsupported float width {}", n),
834 bx.bitcast(bits_llval, float_ty)
836 let (f_min, f_max) = match float_width {
837 32 => compute_clamp_bounds_single(signed, int_width),
838 64 => compute_clamp_bounds_double(signed, int_width),
839 n => bug!("unsupported float width {}", n),
841 let f_min = float_bits_to_llval(f_min);
842 let f_max = float_bits_to_llval(f_max);
843 // To implement saturation, we perform the following steps:
845 // 1. Cast x to an integer with fpto[su]i. This may result in undef.
846 // 2. Compare x to f_min and f_max, and use the comparison results to select:
847 // a) int_ty::MIN if x < f_min or x is NaN
848 // b) int_ty::MAX if x > f_max
849 // c) the result of fpto[su]i otherwise
850 // 3. If x is NaN, return 0.0, otherwise return the result of step 2.
852 // This avoids resulting undef because values in range [f_min, f_max] by definition fit into the
853 // destination type. It creates an undef temporary, but *producing* undef is not UB. Our use of
854 // undef does not introduce any non-determinism either.
855 // More importantly, the above procedure correctly implements saturating conversion.
857 // If x is NaN, 0 is returned by definition.
858 // Otherwise, x is finite or infinite and thus can be compared with f_min and f_max.
859 // This yields three cases to consider:
860 // (1) if x in [f_min, f_max], the result of fpto[su]i is returned, which agrees with
861 // saturating conversion for inputs in that range.
862 // (2) if x > f_max, then x is larger than int_ty::MAX. This holds even if f_max is rounded
863 // (i.e., if f_max < int_ty::MAX) because in those cases, nextUp(f_max) is already larger
864 // than int_ty::MAX. Because x is larger than int_ty::MAX, the return value of int_ty::MAX
866 // (3) if x < f_min, then x is smaller than int_ty::MIN. As shown earlier, f_min exactly equals
867 // int_ty::MIN and therefore the return value of int_ty::MIN is correct.
870 // Step 1 was already performed above.
872 // Step 2: We use two comparisons and two selects, with %s1 being the result:
873 // %less_or_nan = fcmp ult %x, %f_min
874 // %greater = fcmp olt %x, %f_max
875 // %s0 = select %less_or_nan, int_ty::MIN, %fptosi_result
876 // %s1 = select %greater, int_ty::MAX, %s0
877 // Note that %less_or_nan uses an *unordered* comparison. This comparison is true if the
878 // operands are not comparable (i.e., if x is NaN). The unordered comparison ensures that s1
879 // becomes int_ty::MIN if x is NaN.
880 // Performance note: Unordered comparison can be lowered to a "flipped" comparison and a
881 // negation, and the negation can be merged into the select. Therefore, it not necessarily any
882 // more expensive than a ordered ("normal") comparison. Whether these optimizations will be
883 // performed is ultimately up to the backend, but at least x86 does perform them.
884 let less_or_nan = bx.fcmp(RealPredicate::RealULT, x, f_min);
885 let greater = bx.fcmp(RealPredicate::RealOGT, x, f_max);
886 let int_max = bx.cx().const_uint_big(int_ty, int_max(signed, int_width));
887 let int_min = bx.cx().const_uint_big(int_ty, int_min(signed, int_width) as u128);
888 let s0 = bx.select(less_or_nan, int_min, fptosui_result);
889 let s1 = bx.select(greater, int_max, s0);
891 // Step 3: NaN replacement.
892 // For unsigned types, the above step already yielded int_ty::MIN == 0 if x is NaN.
893 // Therefore we only need to execute this step for signed integer types.
895 // LLVM has no isNaN predicate, so we use (x == x) instead
896 let zero = bx.cx().const_uint(int_ty, 0);
897 let cmp = bx.fcmp(RealPredicate::RealOEQ, x, x);
898 bx.select(cmp, s1, zero)