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