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