]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/mir/rvalue.rs
Place::as_place_ref is now Place::as_ref
[rust.git] / src / librustc_codegen_ssa / mir / rvalue.rs
1 use rustc::ty::{self, Ty, adjustment::{PointerCast}, Instance};
2 use rustc::ty::cast::{CastTy, IntTy};
3 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt};
4 use rustc::mir;
5 use rustc::middle::lang_items::ExchangeMallocFnLangItem;
6 use rustc_apfloat::{ieee, Float, Status, Round};
7 use std::{u128, i128};
8 use syntax::symbol::sym;
9
10 use crate::base;
11 use crate::MemFlags;
12 use crate::callee;
13 use crate::common::{self, RealPredicate, IntPredicate};
14
15 use crate::traits::*;
16
17 use super::{FunctionCx, LocalRef};
18 use super::operand::{OperandRef, OperandValue};
19 use super::place::PlaceRef;
20
21 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
22     pub fn codegen_rvalue(
23         &mut self,
24         mut bx: Bx,
25         dest: PlaceRef<'tcx, Bx::Value>,
26         rvalue: &mir::Rvalue<'tcx>
27     ) -> Bx {
28         debug!("codegen_rvalue(dest.llval={:?}, rvalue={:?})",
29                dest.llval, rvalue);
30
31         match *rvalue {
32            mir::Rvalue::Use(ref operand) => {
33                let cg_operand = self.codegen_operand(&mut bx, operand);
34                // FIXME: consider not copying constants through stack. (fixable by codegenning
35                // constants into OperandValue::Ref, why don’t we do that yet if we don’t?)
36                cg_operand.val.store(&mut bx, dest);
37                bx
38            }
39
40             mir::Rvalue::Cast(mir::CastKind::Pointer(PointerCast::Unsize), ref source, _) => {
41                 // The destination necessarily contains a fat pointer, so if
42                 // it's a scalar pair, it's a fat pointer or newtype thereof.
43                 if bx.cx().is_backend_scalar_pair(dest.layout) {
44                     // into-coerce of a thin pointer to a fat pointer - just
45                     // use the operand path.
46                     let (mut bx, temp) = self.codegen_rvalue_operand(bx, rvalue);
47                     temp.val.store(&mut bx, dest);
48                     return bx;
49                 }
50
51                 // Unsize of a nontrivial struct. I would prefer for
52                 // this to be eliminated by MIR building, but
53                 // `CoerceUnsized` can be passed by a where-clause,
54                 // so the (generic) MIR may not be able to expand it.
55                 let operand = self.codegen_operand(&mut bx, source);
56                 match operand.val {
57                     OperandValue::Pair(..) |
58                     OperandValue::Immediate(_) => {
59                         // unsize from an immediate structure. We don't
60                         // really need a temporary alloca here, but
61                         // avoiding it would require us to have
62                         // `coerce_unsized_into` use extractvalue to
63                         // index into the struct, and this case isn't
64                         // important enough for it.
65                         debug!("codegen_rvalue: creating ugly alloca");
66                         let scratch = PlaceRef::alloca(&mut bx, operand.layout, "__unsize_temp");
67                         scratch.storage_live(&mut bx);
68                         operand.val.store(&mut bx, scratch);
69                         base::coerce_unsized_into(&mut bx, scratch, dest);
70                         scratch.storage_dead(&mut bx);
71                     }
72                     OperandValue::Ref(llref, None, align) => {
73                         let source = PlaceRef::new_sized(llref, operand.layout, align);
74                         base::coerce_unsized_into(&mut bx, source, dest);
75                     }
76                     OperandValue::Ref(_, Some(_), _) => {
77                         bug!("unsized coercion on an unsized rvalue")
78                     }
79                 }
80                 bx
81             }
82
83             mir::Rvalue::Repeat(ref elem, count) => {
84                 let cg_elem = self.codegen_operand(&mut bx, elem);
85
86                 // Do not generate the loop for zero-sized elements or empty arrays.
87                 if dest.layout.is_zst() {
88                     return bx;
89                 }
90
91                 if let OperandValue::Immediate(v) = cg_elem.val {
92                     let zero = bx.const_usize(0);
93                     let start = dest.project_index(&mut bx, zero).llval;
94                     let size = bx.const_usize(dest.layout.size.bytes());
95
96                     // Use llvm.memset.p0i8.* to initialize all zero arrays
97                     if bx.cx().is_const_integral(v) && bx.cx().const_to_uint(v) == 0 {
98                         let fill = bx.cx().const_u8(0);
99                         bx.memset(start, fill, size, dest.align, MemFlags::empty());
100                         return bx;
101                     }
102
103                     // Use llvm.memset.p0i8.* to initialize byte arrays
104                     let v = base::from_immediate(&mut bx, v);
105                     if bx.cx().val_ty(v) == bx.cx().type_i8() {
106                         bx.memset(start, v, size, dest.align, MemFlags::empty());
107                         return bx;
108                     }
109                 }
110
111                 bx.write_operand_repeatedly(cg_elem, count, dest)
112             }
113
114             mir::Rvalue::Aggregate(ref kind, ref operands) => {
115                 let (dest, active_field_index) = match **kind {
116                     mir::AggregateKind::Adt(adt_def, variant_index, _, _, active_field_index) => {
117                         dest.codegen_set_discr(&mut bx, variant_index);
118                         if adt_def.is_enum() {
119                             (dest.project_downcast(&mut bx, variant_index), active_field_index)
120                         } else {
121                             (dest, active_field_index)
122                         }
123                     }
124                     _ => (dest, None)
125                 };
126                 for (i, operand) in operands.iter().enumerate() {
127                     let op = self.codegen_operand(&mut bx, operand);
128                     // Do not generate stores and GEPis for zero-sized fields.
129                     if !op.layout.is_zst() {
130                         let field_index = active_field_index.unwrap_or(i);
131                         let field = dest.project_field(&mut bx, field_index);
132                         op.val.store(&mut bx, field);
133                     }
134                 }
135                 bx
136             }
137
138             _ => {
139                 assert!(self.rvalue_creates_operand(rvalue));
140                 let (mut bx, temp) = self.codegen_rvalue_operand(bx, rvalue);
141                 temp.val.store(&mut bx, dest);
142                 bx
143             }
144         }
145     }
146
147     pub fn codegen_rvalue_unsized(
148         &mut self,
149         mut bx: Bx,
150         indirect_dest: PlaceRef<'tcx, Bx::Value>,
151         rvalue: &mir::Rvalue<'tcx>,
152     ) -> Bx {
153         debug!("codegen_rvalue_unsized(indirect_dest.llval={:?}, rvalue={:?})",
154                indirect_dest.llval, rvalue);
155
156         match *rvalue {
157             mir::Rvalue::Use(ref operand) => {
158                 let cg_operand = self.codegen_operand(&mut bx, operand);
159                 cg_operand.val.store_unsized(&mut bx, indirect_dest);
160                 bx
161             }
162
163             _ => bug!("unsized assignment other than Rvalue::Use"),
164         }
165     }
166
167     pub fn codegen_rvalue_operand(
168         &mut self,
169         mut bx: Bx,
170         rvalue: &mir::Rvalue<'tcx>
171     ) -> (Bx, OperandRef<'tcx, Bx::Value>) {
172         assert!(self.rvalue_creates_operand(rvalue), "cannot codegen {:?} to operand", rvalue);
173
174         match *rvalue {
175             mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
176                 let operand = self.codegen_operand(&mut bx, source);
177                 debug!("cast operand is {:?}", operand);
178                 let cast = bx.cx().layout_of(self.monomorphize(&mir_cast_ty));
179
180                 let val = match *kind {
181                     mir::CastKind::Pointer(PointerCast::ReifyFnPointer) => {
182                         match operand.layout.ty.sty {
183                             ty::FnDef(def_id, substs) => {
184                                 if bx.cx().tcx().has_attr(def_id, sym::rustc_args_required_const) {
185                                     bug!("reifying a fn ptr that requires const arguments");
186                                 }
187                                 OperandValue::Immediate(
188                                     callee::resolve_and_get_fn(bx.cx(), def_id, substs))
189                             }
190                             _ => {
191                                 bug!("{} cannot be reified to a fn ptr", operand.layout.ty)
192                             }
193                         }
194                     }
195                     mir::CastKind::Pointer(PointerCast::ClosureFnPointer(_)) => {
196                         match operand.layout.ty.sty {
197                             ty::Closure(def_id, substs) => {
198                                 let instance = Instance::resolve_closure(
199                                     bx.cx().tcx(), def_id, substs, ty::ClosureKind::FnOnce);
200                                 OperandValue::Immediate(bx.cx().get_fn(instance))
201                             }
202                             _ => {
203                                 bug!("{} cannot be cast to a fn ptr", operand.layout.ty)
204                             }
205                         }
206                     }
207                     mir::CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
208                         // this is a no-op at the LLVM level
209                         operand.val
210                     }
211                     mir::CastKind::Pointer(PointerCast::Unsize) => {
212                         assert!(bx.cx().is_backend_scalar_pair(cast));
213                         match operand.val {
214                             OperandValue::Pair(lldata, llextra) => {
215                                 // unsize from a fat pointer - this is a
216                                 // "trait-object-to-supertrait" coercion, for
217                                 // example,
218                                 //   &'a fmt::Debug+Send => &'a fmt::Debug,
219
220                                 // HACK(eddyb) have to bitcast pointers
221                                 // until LLVM removes pointee types.
222                                 let lldata = bx.pointercast(lldata,
223                                     bx.cx().scalar_pair_element_backend_type(cast, 0, true));
224                                 OperandValue::Pair(lldata, llextra)
225                             }
226                             OperandValue::Immediate(lldata) => {
227                                 // "standard" unsize
228                                 let (lldata, llextra) = base::unsize_thin_ptr(&mut bx, lldata,
229                                     operand.layout.ty, cast.ty);
230                                 OperandValue::Pair(lldata, llextra)
231                             }
232                             OperandValue::Ref(..) => {
233                                 bug!("by-ref operand {:?} in codegen_rvalue_operand",
234                                      operand);
235                             }
236                         }
237                     }
238                     mir::CastKind::Pointer(PointerCast::MutToConstPointer)
239                     | mir::CastKind::Misc if bx.cx().is_backend_scalar_pair(operand.layout) => {
240                         if let OperandValue::Pair(data_ptr, meta) = operand.val {
241                             if bx.cx().is_backend_scalar_pair(cast) {
242                                 let data_cast = bx.pointercast(data_ptr,
243                                     bx.cx().scalar_pair_element_backend_type(cast, 0, true));
244                                 OperandValue::Pair(data_cast, meta)
245                             } else { // cast to thin-ptr
246                                 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
247                                 // pointer-cast of that pointer to desired pointer type.
248                                 let llcast_ty = bx.cx().immediate_backend_type(cast);
249                                 let llval = bx.pointercast(data_ptr, llcast_ty);
250                                 OperandValue::Immediate(llval)
251                             }
252                         } else {
253                             bug!("Unexpected non-Pair operand")
254                         }
255                     }
256                     mir::CastKind::Pointer(PointerCast::MutToConstPointer)
257                     | mir::CastKind::Misc => {
258                         assert!(bx.cx().is_backend_immediate(cast));
259                         let ll_t_out = bx.cx().immediate_backend_type(cast);
260                         if operand.layout.abi.is_uninhabited() {
261                             let val = OperandValue::Immediate(bx.cx().const_undef(ll_t_out));
262                             return (bx, OperandRef {
263                                 val,
264                                 layout: cast,
265                             });
266                         }
267                         let r_t_in = CastTy::from_ty(operand.layout.ty)
268                             .expect("bad input type for cast");
269                         let r_t_out = CastTy::from_ty(cast.ty).expect("bad output type for cast");
270                         let ll_t_in = bx.cx().immediate_backend_type(operand.layout);
271                         match operand.layout.variants {
272                             layout::Variants::Single { index } => {
273                                 if let Some(discr) =
274                                     operand.layout.ty.discriminant_for_variant(bx.tcx(), index)
275                                 {
276                                     let discr_val = bx.cx().const_uint_big(ll_t_out, discr.val);
277                                     return (bx, OperandRef {
278                                         val: OperandValue::Immediate(discr_val),
279                                         layout: cast,
280                                     });
281                                 }
282                             }
283                             layout::Variants::Multiple { .. } => {},
284                         }
285                         let llval = operand.immediate();
286
287                         let mut signed = false;
288                         if let layout::Abi::Scalar(ref scalar) = operand.layout.abi {
289                             if let layout::Int(_, s) = scalar.value {
290                                 // We use `i1` for bytes that are always `0` or `1`,
291                                 // e.g., `#[repr(i8)] enum E { A, B }`, but we can't
292                                 // let LLVM interpret the `i1` as signed, because
293                                 // then `i1 1` (i.e., E::B) is effectively `i8 -1`.
294                                 signed = !scalar.is_bool() && s;
295
296                                 let er = scalar.valid_range_exclusive(bx.cx());
297                                 if er.end != er.start &&
298                                    scalar.valid_range.end() > scalar.valid_range.start() {
299                                     // We want `table[e as usize]` to not
300                                     // have bound checks, and this is the most
301                                     // convenient place to put the `assume`.
302                                     let ll_t_in_const =
303                                         bx.cx().const_uint_big(ll_t_in, *scalar.valid_range.end());
304                                     let cmp = bx.icmp(
305                                         IntPredicate::IntULE,
306                                         llval,
307                                         ll_t_in_const
308                                     );
309                                     bx.assume(cmp);
310                                 }
311                             }
312                         }
313
314                         let newval = match (r_t_in, r_t_out) {
315                             (CastTy::Int(_), CastTy::Int(_)) => {
316                                 bx.intcast(llval, ll_t_out, signed)
317                             }
318                             (CastTy::Float, CastTy::Float) => {
319                                 let srcsz = bx.cx().float_width(ll_t_in);
320                                 let dstsz = bx.cx().float_width(ll_t_out);
321                                 if dstsz > srcsz {
322                                     bx.fpext(llval, ll_t_out)
323                                 } else if srcsz > dstsz {
324                                     bx.fptrunc(llval, ll_t_out)
325                                 } else {
326                                     llval
327                                 }
328                             }
329                             (CastTy::Ptr(_), CastTy::Ptr(_)) |
330                             (CastTy::FnPtr, CastTy::Ptr(_)) |
331                             (CastTy::RPtr(_), CastTy::Ptr(_)) =>
332                                 bx.pointercast(llval, ll_t_out),
333                             (CastTy::Ptr(_), CastTy::Int(_)) |
334                             (CastTy::FnPtr, CastTy::Int(_)) =>
335                                 bx.ptrtoint(llval, ll_t_out),
336                             (CastTy::Int(_), CastTy::Ptr(_)) => {
337                                 let usize_llval = bx.intcast(llval, bx.cx().type_isize(), signed);
338                                 bx.inttoptr(usize_llval, ll_t_out)
339                             }
340                             (CastTy::Int(_), CastTy::Float) =>
341                                 cast_int_to_float(&mut bx, signed, llval, ll_t_in, ll_t_out),
342                             (CastTy::Float, CastTy::Int(IntTy::I)) =>
343                                 cast_float_to_int(&mut bx, true, llval, ll_t_in, ll_t_out),
344                             (CastTy::Float, CastTy::Int(_)) =>
345                                 cast_float_to_int(&mut bx, false, llval, ll_t_in, ll_t_out),
346                             _ => bug!("unsupported cast: {:?} to {:?}", operand.layout.ty, cast.ty)
347                         };
348                         OperandValue::Immediate(newval)
349                     }
350                 };
351                 (bx, OperandRef {
352                     val,
353                     layout: cast
354                 })
355             }
356
357             mir::Rvalue::Ref(_, bk, ref place) => {
358                 let cg_place = self.codegen_place(&mut bx, &place.as_ref());
359
360                 let ty = cg_place.layout.ty;
361
362                 // Note: places are indirect, so storing the `llval` into the
363                 // destination effectively creates a reference.
364                 let val = if !bx.cx().type_has_metadata(ty) {
365                     OperandValue::Immediate(cg_place.llval)
366                 } else {
367                     OperandValue::Pair(cg_place.llval, cg_place.llextra.unwrap())
368                 };
369                 (bx, OperandRef {
370                     val,
371                     layout: self.cx.layout_of(self.cx.tcx().mk_ref(
372                         self.cx.tcx().lifetimes.re_erased,
373                         ty::TypeAndMut { ty, mutbl: bk.to_mutbl_lossy() }
374                     )),
375                 })
376             }
377
378             mir::Rvalue::Len(ref place) => {
379                 let size = self.evaluate_array_len(&mut bx, place);
380                 let operand = OperandRef {
381                     val: OperandValue::Immediate(size),
382                     layout: bx.cx().layout_of(bx.tcx().types.usize),
383                 };
384                 (bx, operand)
385             }
386
387             mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
388                 let lhs = self.codegen_operand(&mut bx, lhs);
389                 let rhs = self.codegen_operand(&mut bx, rhs);
390                 let llresult = match (lhs.val, rhs.val) {
391                     (OperandValue::Pair(lhs_addr, lhs_extra),
392                      OperandValue::Pair(rhs_addr, rhs_extra)) => {
393                         self.codegen_fat_ptr_binop(&mut bx, op,
394                                                  lhs_addr, lhs_extra,
395                                                  rhs_addr, rhs_extra,
396                                                  lhs.layout.ty)
397                     }
398
399                     (OperandValue::Immediate(lhs_val),
400                      OperandValue::Immediate(rhs_val)) => {
401                         self.codegen_scalar_binop(&mut bx, op, lhs_val, rhs_val, lhs.layout.ty)
402                     }
403
404                     _ => bug!()
405                 };
406                 let operand = OperandRef {
407                     val: OperandValue::Immediate(llresult),
408                     layout: bx.cx().layout_of(
409                         op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
410                 };
411                 (bx, operand)
412             }
413             mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
414                 let lhs = self.codegen_operand(&mut bx, lhs);
415                 let rhs = self.codegen_operand(&mut bx, rhs);
416                 let result = self.codegen_scalar_checked_binop(&mut bx, op,
417                                                              lhs.immediate(), rhs.immediate(),
418                                                              lhs.layout.ty);
419                 let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
420                 let operand_ty = bx.tcx().intern_tup(&[val_ty, bx.tcx().types.bool]);
421                 let operand = OperandRef {
422                     val: result,
423                     layout: bx.cx().layout_of(operand_ty)
424                 };
425
426                 (bx, operand)
427             }
428
429             mir::Rvalue::UnaryOp(op, ref operand) => {
430                 let operand = self.codegen_operand(&mut bx, operand);
431                 let lloperand = operand.immediate();
432                 let is_float = operand.layout.ty.is_floating_point();
433                 let llval = match op {
434                     mir::UnOp::Not => bx.not(lloperand),
435                     mir::UnOp::Neg => if is_float {
436                         bx.fneg(lloperand)
437                     } else {
438                         bx.neg(lloperand)
439                     }
440                 };
441                 (bx, OperandRef {
442                     val: OperandValue::Immediate(llval),
443                     layout: operand.layout,
444                 })
445             }
446
447             mir::Rvalue::Discriminant(ref place) => {
448                 let discr_ty = rvalue.ty(&*self.mir, bx.tcx());
449                 let discr =  self.codegen_place(&mut bx, &place.as_ref())
450                     .codegen_get_discr(&mut bx, discr_ty);
451                 (bx, OperandRef {
452                     val: OperandValue::Immediate(discr),
453                     layout: self.cx.layout_of(discr_ty)
454                 })
455             }
456
457             mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
458                 assert!(bx.cx().type_is_sized(ty));
459                 let val = bx.cx().const_usize(bx.cx().layout_of(ty).size.bytes());
460                 let tcx = self.cx.tcx();
461                 (bx, OperandRef {
462                     val: OperandValue::Immediate(val),
463                     layout: self.cx.layout_of(tcx.types.usize),
464                 })
465             }
466
467             mir::Rvalue::NullaryOp(mir::NullOp::Box, content_ty) => {
468                 let content_ty = self.monomorphize(&content_ty);
469                 let content_layout = bx.cx().layout_of(content_ty);
470                 let llsize = bx.cx().const_usize(content_layout.size.bytes());
471                 let llalign = bx.cx().const_usize(content_layout.align.abi.bytes());
472                 let box_layout = bx.cx().layout_of(bx.tcx().mk_box(content_ty));
473                 let llty_ptr = bx.cx().backend_type(box_layout);
474
475                 // Allocate space:
476                 let def_id = match bx.tcx().lang_items().require(ExchangeMallocFnLangItem) {
477                     Ok(id) => id,
478                     Err(s) => {
479                         bx.cx().sess().fatal(&format!("allocation of `{}` {}", box_layout.ty, s));
480                     }
481                 };
482                 let instance = ty::Instance::mono(bx.tcx(), def_id);
483                 let r = bx.cx().get_fn(instance);
484                 let call = bx.call(r, &[llsize, llalign], None);
485                 let val = bx.pointercast(call, llty_ptr);
486
487                 let operand = OperandRef {
488                     val: OperandValue::Immediate(val),
489                     layout: box_layout,
490                 };
491                 (bx, operand)
492             }
493             mir::Rvalue::Use(ref operand) => {
494                 let operand = self.codegen_operand(&mut bx, operand);
495                 (bx, operand)
496             }
497             mir::Rvalue::Repeat(..) |
498             mir::Rvalue::Aggregate(..) => {
499                 // According to `rvalue_creates_operand`, only ZST
500                 // aggregate rvalues are allowed to be operands.
501                 let ty = rvalue.ty(self.mir, self.cx.tcx());
502                 let operand = OperandRef::new_zst(
503                     &mut bx,
504                     self.cx.layout_of(self.monomorphize(&ty)),
505                 );
506                 (bx, operand)
507             }
508         }
509     }
510
511     fn evaluate_array_len(
512         &mut self,
513         bx: &mut Bx,
514         place: &mir::Place<'tcx>,
515     ) -> Bx::Value {
516         // ZST are passed as operands and require special handling
517         // because codegen_place() panics if Local is operand.
518         if let mir::Place {
519             base: mir::PlaceBase::Local(index),
520             projection: None,
521         } = *place {
522             if let LocalRef::Operand(Some(op)) = self.locals[index] {
523                 if let ty::Array(_, n) = op.layout.ty.sty {
524                     let n = n.unwrap_usize(bx.cx().tcx());
525                     return bx.cx().const_usize(n);
526                 }
527             }
528         }
529         // use common size calculation for non zero-sized types
530         let cg_value = self.codegen_place(bx, &place.as_ref());
531         cg_value.len(bx.cx())
532     }
533
534     pub fn codegen_scalar_binop(
535         &mut self,
536         bx: &mut Bx,
537         op: mir::BinOp,
538         lhs: Bx::Value,
539         rhs: Bx::Value,
540         input_ty: Ty<'tcx>,
541     ) -> Bx::Value {
542         let is_float = input_ty.is_floating_point();
543         let is_signed = input_ty.is_signed();
544         let is_unit = input_ty.is_unit();
545         match op {
546             mir::BinOp::Add => if is_float {
547                 bx.fadd(lhs, rhs)
548             } else {
549                 bx.add(lhs, rhs)
550             },
551             mir::BinOp::Sub => if is_float {
552                 bx.fsub(lhs, rhs)
553             } else {
554                 bx.sub(lhs, rhs)
555             },
556             mir::BinOp::Mul => if is_float {
557                 bx.fmul(lhs, rhs)
558             } else {
559                 bx.mul(lhs, rhs)
560             },
561             mir::BinOp::Div => if is_float {
562                 bx.fdiv(lhs, rhs)
563             } else if is_signed {
564                 bx.sdiv(lhs, rhs)
565             } else {
566                 bx.udiv(lhs, rhs)
567             },
568             mir::BinOp::Rem => if is_float {
569                 bx.frem(lhs, rhs)
570             } else if is_signed {
571                 bx.srem(lhs, rhs)
572             } else {
573                 bx.urem(lhs, rhs)
574             },
575             mir::BinOp::BitOr => bx.or(lhs, rhs),
576             mir::BinOp::BitAnd => bx.and(lhs, rhs),
577             mir::BinOp::BitXor => bx.xor(lhs, rhs),
578             mir::BinOp::Offset => bx.inbounds_gep(lhs, &[rhs]),
579             mir::BinOp::Shl => common::build_unchecked_lshift(bx, lhs, rhs),
580             mir::BinOp::Shr => common::build_unchecked_rshift(bx, input_ty, lhs, rhs),
581             mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt |
582             mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => if is_unit {
583                 bx.cx().const_bool(match op {
584                     mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt => false,
585                     mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => true,
586                     _ => unreachable!()
587                 })
588             } else if is_float {
589                 bx.fcmp(
590                     base::bin_op_to_fcmp_predicate(op.to_hir_binop()),
591                     lhs, rhs
592                 )
593             } else {
594                 bx.icmp(
595                     base::bin_op_to_icmp_predicate(op.to_hir_binop(), is_signed),
596                     lhs, rhs
597                 )
598             }
599         }
600     }
601
602     pub fn codegen_fat_ptr_binop(
603         &mut self,
604         bx: &mut Bx,
605         op: mir::BinOp,
606         lhs_addr: Bx::Value,
607         lhs_extra: Bx::Value,
608         rhs_addr: Bx::Value,
609         rhs_extra: Bx::Value,
610         _input_ty: Ty<'tcx>,
611     ) -> Bx::Value {
612         match op {
613             mir::BinOp::Eq => {
614                 let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
615                 let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
616                 bx.and(lhs, rhs)
617             }
618             mir::BinOp::Ne => {
619                 let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
620                 let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
621                 bx.or(lhs, rhs)
622             }
623             mir::BinOp::Le | mir::BinOp::Lt |
624             mir::BinOp::Ge | mir::BinOp::Gt => {
625                 // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
626                 let (op, strict_op) = match op {
627                     mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
628                     mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
629                     mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
630                     mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
631                     _ => bug!(),
632                 };
633                 let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
634                 let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
635                 let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
636                 let rhs = bx.and(and_lhs, and_rhs);
637                 bx.or(lhs, rhs)
638             }
639             _ => {
640                 bug!("unexpected fat ptr binop");
641             }
642         }
643     }
644
645     pub fn codegen_scalar_checked_binop(
646         &mut self,
647         bx: &mut Bx,
648         op: mir::BinOp,
649         lhs: Bx::Value,
650         rhs: Bx::Value,
651         input_ty: Ty<'tcx>
652     ) -> OperandValue<Bx::Value> {
653         // This case can currently arise only from functions marked
654         // with #[rustc_inherit_overflow_checks] and inlined from
655         // another crate (mostly core::num generic/#[inline] fns),
656         // while the current crate doesn't use overflow checks.
657         if !bx.cx().check_overflow() {
658             let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
659             return OperandValue::Pair(val, bx.cx().const_bool(false));
660         }
661
662         let (val, of) = match op {
663             // These are checked using intrinsics
664             mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
665                 let oop = match op {
666                     mir::BinOp::Add => OverflowOp::Add,
667                     mir::BinOp::Sub => OverflowOp::Sub,
668                     mir::BinOp::Mul => OverflowOp::Mul,
669                     _ => unreachable!()
670                 };
671                 bx.checked_binop(oop, input_ty, lhs, rhs)
672             }
673             mir::BinOp::Shl | mir::BinOp::Shr => {
674                 let lhs_llty = bx.cx().val_ty(lhs);
675                 let rhs_llty = bx.cx().val_ty(rhs);
676                 let invert_mask = common::shift_mask_val(bx, lhs_llty, rhs_llty, true);
677                 let outer_bits = bx.and(rhs, invert_mask);
678
679                 let of = bx.icmp(IntPredicate::IntNE, outer_bits, bx.cx().const_null(rhs_llty));
680                 let val = self.codegen_scalar_binop(bx, op, lhs, rhs, input_ty);
681
682                 (val, of)
683             }
684             _ => {
685                 bug!("Operator `{:?}` is not a checkable operator", op)
686             }
687         };
688
689         OperandValue::Pair(val, of)
690     }
691 }
692
693 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
694     pub fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>) -> bool {
695         match *rvalue {
696             mir::Rvalue::Ref(..) |
697             mir::Rvalue::Len(..) |
698             mir::Rvalue::Cast(..) | // (*)
699             mir::Rvalue::BinaryOp(..) |
700             mir::Rvalue::CheckedBinaryOp(..) |
701             mir::Rvalue::UnaryOp(..) |
702             mir::Rvalue::Discriminant(..) |
703             mir::Rvalue::NullaryOp(..) |
704             mir::Rvalue::Use(..) => // (*)
705                 true,
706             mir::Rvalue::Repeat(..) |
707             mir::Rvalue::Aggregate(..) => {
708                 let ty = rvalue.ty(self.mir, self.cx.tcx());
709                 let ty = self.monomorphize(&ty);
710                 self.cx.layout_of(ty).is_zst()
711             }
712         }
713
714         // (*) this is only true if the type is suitable
715     }
716 }
717
718 fn cast_int_to_float<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
719     bx: &mut Bx,
720     signed: bool,
721     x: Bx::Value,
722     int_ty: Bx::Type,
723     float_ty: Bx::Type
724 ) -> Bx::Value {
725     // Most integer types, even i128, fit into [-f32::MAX, f32::MAX] after rounding.
726     // It's only u128 -> f32 that can cause overflows (i.e., should yield infinity).
727     // LLVM's uitofp produces undef in those cases, so we manually check for that case.
728     let is_u128_to_f32 = !signed &&
729         bx.cx().int_width(int_ty) == 128 &&
730         bx.cx().float_width(float_ty) == 32;
731     if is_u128_to_f32 {
732         // All inputs greater or equal to (f32::MAX + 0.5 ULP) are rounded to infinity,
733         // and for everything else LLVM's uitofp works just fine.
734         use rustc_apfloat::ieee::Single;
735         const MAX_F32_PLUS_HALF_ULP: u128 = ((1 << (Single::PRECISION + 1)) - 1)
736                                             << (Single::MAX_EXP - Single::PRECISION as i16);
737         let max = bx.cx().const_uint_big(int_ty, MAX_F32_PLUS_HALF_ULP);
738         let overflow = bx.icmp(IntPredicate::IntUGE, x, max);
739         let infinity_bits = bx.cx().const_u32(ieee::Single::INFINITY.to_bits() as u32);
740         let infinity = bx.bitcast(infinity_bits, float_ty);
741         let fp = bx.uitofp(x, float_ty);
742         bx.select(overflow, infinity, fp)
743     } else {
744         if signed {
745             bx.sitofp(x, float_ty)
746         } else {
747             bx.uitofp(x, float_ty)
748         }
749     }
750 }
751
752 fn cast_float_to_int<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
753     bx: &mut Bx,
754     signed: bool,
755     x: Bx::Value,
756     float_ty: Bx::Type,
757     int_ty: Bx::Type
758 ) -> Bx::Value {
759     let fptosui_result = if signed {
760         bx.fptosi(x, int_ty)
761     } else {
762         bx.fptoui(x, int_ty)
763     };
764
765     if !bx.cx().sess().opts.debugging_opts.saturating_float_casts {
766         return fptosui_result;
767     }
768
769     let int_width = bx.cx().int_width(int_ty);
770     let float_width = bx.cx().float_width(float_ty);
771     // LLVM's fpto[su]i returns undef when the input x is infinite, NaN, or does not fit into the
772     // destination integer type after rounding towards zero. This `undef` value can cause UB in
773     // safe code (see issue #10184), so we implement a saturating conversion on top of it:
774     // Semantically, the mathematical value of the input is rounded towards zero to the next
775     // mathematical integer, and then the result is clamped into the range of the destination
776     // integer type. Positive and negative infinity are mapped to the maximum and minimum value of
777     // the destination integer type. NaN is mapped to 0.
778     //
779     // Define f_min and f_max as the largest and smallest (finite) floats that are exactly equal to
780     // a value representable in int_ty.
781     // They are exactly equal to int_ty::{MIN,MAX} if float_ty has enough significand bits.
782     // Otherwise, int_ty::MAX must be rounded towards zero, as it is one less than a power of two.
783     // int_ty::MIN, however, is either zero or a negative power of two and is thus exactly
784     // representable. Note that this only works if float_ty's exponent range is sufficiently large.
785     // f16 or 256 bit integers would break this property. Right now the smallest float type is f32
786     // with exponents ranging up to 127, which is barely enough for i128::MIN = -2^127.
787     // On the other hand, f_max works even if int_ty::MAX is greater than float_ty::MAX. Because
788     // we're rounding towards zero, we just get float_ty::MAX (which is always an integer).
789     // This already happens today with u128::MAX = 2^128 - 1 > f32::MAX.
790     let int_max = |signed: bool, int_width: u64| -> u128 {
791         let shift_amount = 128 - int_width;
792         if signed {
793             i128::MAX as u128 >> shift_amount
794         } else {
795             u128::MAX >> shift_amount
796         }
797     };
798     let int_min = |signed: bool, int_width: u64| -> i128 {
799         if signed {
800             i128::MIN >> (128 - int_width)
801         } else {
802             0
803         }
804     };
805
806     let compute_clamp_bounds_single =
807     |signed: bool, int_width: u64| -> (u128, u128) {
808         let rounded_min = ieee::Single::from_i128_r(int_min(signed, int_width), Round::TowardZero);
809         assert_eq!(rounded_min.status, Status::OK);
810         let rounded_max = ieee::Single::from_u128_r(int_max(signed, int_width), Round::TowardZero);
811         assert!(rounded_max.value.is_finite());
812         (rounded_min.value.to_bits(), rounded_max.value.to_bits())
813     };
814     let compute_clamp_bounds_double =
815     |signed: bool, int_width: u64| -> (u128, u128) {
816         let rounded_min = ieee::Double::from_i128_r(int_min(signed, int_width), Round::TowardZero);
817         assert_eq!(rounded_min.status, Status::OK);
818         let rounded_max = ieee::Double::from_u128_r(int_max(signed, int_width), Round::TowardZero);
819         assert!(rounded_max.value.is_finite());
820         (rounded_min.value.to_bits(), rounded_max.value.to_bits())
821     };
822
823     let mut float_bits_to_llval = |bits| {
824         let bits_llval = match float_width  {
825             32 => bx.cx().const_u32(bits as u32),
826             64 => bx.cx().const_u64(bits as u64),
827             n => bug!("unsupported float width {}", n),
828         };
829         bx.bitcast(bits_llval, float_ty)
830     };
831     let (f_min, f_max) = match float_width {
832         32 => compute_clamp_bounds_single(signed, int_width),
833         64 => compute_clamp_bounds_double(signed, int_width),
834         n => bug!("unsupported float width {}", n),
835     };
836     let f_min = float_bits_to_llval(f_min);
837     let f_max = float_bits_to_llval(f_max);
838     // To implement saturation, we perform the following steps:
839     //
840     // 1. Cast x to an integer with fpto[su]i. This may result in undef.
841     // 2. Compare x to f_min and f_max, and use the comparison results to select:
842     //  a) int_ty::MIN if x < f_min or x is NaN
843     //  b) int_ty::MAX if x > f_max
844     //  c) the result of fpto[su]i otherwise
845     // 3. If x is NaN, return 0.0, otherwise return the result of step 2.
846     //
847     // This avoids resulting undef because values in range [f_min, f_max] by definition fit into the
848     // destination type. It creates an undef temporary, but *producing* undef is not UB. Our use of
849     // undef does not introduce any non-determinism either.
850     // More importantly, the above procedure correctly implements saturating conversion.
851     // Proof (sketch):
852     // If x is NaN, 0 is returned by definition.
853     // Otherwise, x is finite or infinite and thus can be compared with f_min and f_max.
854     // This yields three cases to consider:
855     // (1) if x in [f_min, f_max], the result of fpto[su]i is returned, which agrees with
856     //     saturating conversion for inputs in that range.
857     // (2) if x > f_max, then x is larger than int_ty::MAX. This holds even if f_max is rounded
858     //     (i.e., if f_max < int_ty::MAX) because in those cases, nextUp(f_max) is already larger
859     //     than int_ty::MAX. Because x is larger than int_ty::MAX, the return value of int_ty::MAX
860     //     is correct.
861     // (3) if x < f_min, then x is smaller than int_ty::MIN. As shown earlier, f_min exactly equals
862     //     int_ty::MIN and therefore the return value of int_ty::MIN is correct.
863     // QED.
864
865     // Step 1 was already performed above.
866
867     // Step 2: We use two comparisons and two selects, with %s1 being the result:
868     //     %less_or_nan = fcmp ult %x, %f_min
869     //     %greater = fcmp olt %x, %f_max
870     //     %s0 = select %less_or_nan, int_ty::MIN, %fptosi_result
871     //     %s1 = select %greater, int_ty::MAX, %s0
872     // Note that %less_or_nan uses an *unordered* comparison. This comparison is true if the
873     // operands are not comparable (i.e., if x is NaN). The unordered comparison ensures that s1
874     // becomes int_ty::MIN if x is NaN.
875     // Performance note: Unordered comparison can be lowered to a "flipped" comparison and a
876     // negation, and the negation can be merged into the select. Therefore, it not necessarily any
877     // more expensive than a ordered ("normal") comparison. Whether these optimizations will be
878     // performed is ultimately up to the backend, but at least x86 does perform them.
879     let less_or_nan = bx.fcmp(RealPredicate::RealULT, x, f_min);
880     let greater = bx.fcmp(RealPredicate::RealOGT, x, f_max);
881     let int_max = bx.cx().const_uint_big(int_ty, int_max(signed, int_width));
882     let int_min = bx.cx().const_uint_big(int_ty, int_min(signed, int_width) as u128);
883     let s0 = bx.select(less_or_nan, int_min, fptosui_result);
884     let s1 = bx.select(greater, int_max, s0);
885
886     // Step 3: NaN replacement.
887     // For unsigned types, the above step already yielded int_ty::MIN == 0 if x is NaN.
888     // Therefore we only need to execute this step for signed integer types.
889     if signed {
890         // LLVM has no isNaN predicate, so we use (x == x) instead
891         let zero = bx.cx().const_uint(int_ty, 0);
892         let cmp = bx.fcmp(RealPredicate::RealOEQ, x, x);
893         bx.select(cmp, s1, zero)
894     } else {
895         s1
896     }
897 }