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