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