]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/rvalue.rs
Rollup merge of #41249 - GuillaumeGomez:rustdoc-render, r=steveklabnik,frewsxcv
[rust.git] / src / librustc_trans / mir / rvalue.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use llvm::{self, ValueRef};
12 use rustc::ty::{self, Ty};
13 use rustc::ty::cast::{CastTy, IntTy};
14 use rustc::ty::layout::{Layout, LayoutTyper};
15 use rustc::mir::tcx::LvalueTy;
16 use rustc::mir;
17 use middle::lang_items::ExchangeMallocFnLangItem;
18
19 use base;
20 use builder::Builder;
21 use callee;
22 use common::{self, val_ty, C_bool, C_null, C_uint};
23 use common::{C_integral};
24 use adt;
25 use machine;
26 use monomorphize;
27 use type_::Type;
28 use type_of;
29 use tvec;
30 use value::Value;
31 use Disr;
32
33 use super::MirContext;
34 use super::constant::const_scalar_checked_binop;
35 use super::operand::{OperandRef, OperandValue};
36 use super::lvalue::LvalueRef;
37
38 impl<'a, 'tcx> MirContext<'a, 'tcx> {
39     pub fn trans_rvalue(&mut self,
40                         bcx: Builder<'a, 'tcx>,
41                         dest: LvalueRef<'tcx>,
42                         rvalue: &mir::Rvalue<'tcx>)
43                         -> Builder<'a, 'tcx>
44     {
45         debug!("trans_rvalue(dest.llval={:?}, rvalue={:?})",
46                Value(dest.llval), rvalue);
47
48         match *rvalue {
49            mir::Rvalue::Use(ref operand) => {
50                let tr_operand = self.trans_operand(&bcx, operand);
51                // FIXME: consider not copying constants through stack. (fixable by translating
52                // constants into OperandValue::Ref, why don’t we do that yet if we don’t?)
53                self.store_operand(&bcx, dest.llval, dest.alignment.to_align(), tr_operand);
54                bcx
55            }
56
57             mir::Rvalue::Cast(mir::CastKind::Unsize, ref source, cast_ty) => {
58                 let cast_ty = self.monomorphize(&cast_ty);
59
60                 if common::type_is_fat_ptr(bcx.ccx, cast_ty) {
61                     // into-coerce of a thin pointer to a fat pointer - just
62                     // use the operand path.
63                     let (bcx, temp) = self.trans_rvalue_operand(bcx, rvalue);
64                     self.store_operand(&bcx, dest.llval, dest.alignment.to_align(), temp);
65                     return bcx;
66                 }
67
68                 // Unsize of a nontrivial struct. I would prefer for
69                 // this to be eliminated by MIR translation, but
70                 // `CoerceUnsized` can be passed by a where-clause,
71                 // so the (generic) MIR may not be able to expand it.
72                 let operand = self.trans_operand(&bcx, source);
73                 let operand = operand.pack_if_pair(&bcx);
74                 let llref = match operand.val {
75                     OperandValue::Pair(..) => bug!(),
76                     OperandValue::Immediate(llval) => {
77                         // unsize from an immediate structure. We don't
78                         // really need a temporary alloca here, but
79                         // avoiding it would require us to have
80                         // `coerce_unsized_into` use extractvalue to
81                         // index into the struct, and this case isn't
82                         // important enough for it.
83                         debug!("trans_rvalue: creating ugly alloca");
84                         let scratch = LvalueRef::alloca(&bcx, operand.ty, "__unsize_temp");
85                         base::store_ty(&bcx, llval, scratch.llval, scratch.alignment, operand.ty);
86                         scratch
87                     }
88                     OperandValue::Ref(llref, align) => {
89                         LvalueRef::new_sized_ty(llref, operand.ty, align)
90                     }
91                 };
92                 base::coerce_unsized_into(&bcx, &llref, &dest);
93                 bcx
94             }
95
96             mir::Rvalue::Repeat(ref elem, ref count) => {
97                 let tr_elem = self.trans_operand(&bcx, elem);
98                 let size = count.as_u64(bcx.tcx().sess.target.uint_type);
99                 let size = C_uint(bcx.ccx, size);
100                 let base = base::get_dataptr(&bcx, dest.llval);
101                 tvec::slice_for_each(&bcx, base, tr_elem.ty, size, |bcx, llslot, loop_bb| {
102                     self.store_operand(bcx, llslot, dest.alignment.to_align(), tr_elem);
103                     bcx.br(loop_bb);
104                 })
105             }
106
107             mir::Rvalue::Aggregate(ref kind, ref operands) => {
108                 match *kind {
109                     mir::AggregateKind::Adt(adt_def, variant_index, substs, active_field_index) => {
110                         let disr = Disr::for_variant(bcx.tcx(), adt_def, variant_index);
111                         let dest_ty = dest.ty.to_ty(bcx.tcx());
112                         adt::trans_set_discr(&bcx, dest_ty, dest.llval, disr);
113                         for (i, operand) in operands.iter().enumerate() {
114                             let op = self.trans_operand(&bcx, operand);
115                             // Do not generate stores and GEPis for zero-sized fields.
116                             if !common::type_is_zero_size(bcx.ccx, op.ty) {
117                                 let mut val = LvalueRef::new_sized(
118                                     dest.llval, dest.ty, dest.alignment);
119                                 let field_index = active_field_index.unwrap_or(i);
120                                 val.ty = LvalueTy::Downcast {
121                                     adt_def: adt_def,
122                                     substs: self.monomorphize(&substs),
123                                     variant_index: variant_index,
124                                 };
125                                 let (lldest_i, align) = val.trans_field_ptr(&bcx, field_index);
126                                 self.store_operand(&bcx, lldest_i, align.to_align(), op);
127                             }
128                         }
129                     },
130                     _ => {
131                         // If this is a tuple or closure, we need to translate GEP indices.
132                         let layout = bcx.ccx.layout_of(dest.ty.to_ty(bcx.tcx()));
133                         let translation = if let Layout::Univariant { ref variant, .. } = *layout {
134                             Some(&variant.memory_index)
135                         } else {
136                             None
137                         };
138                         let alignment = dest.alignment;
139                         for (i, operand) in operands.iter().enumerate() {
140                             let op = self.trans_operand(&bcx, operand);
141                             // Do not generate stores and GEPis for zero-sized fields.
142                             if !common::type_is_zero_size(bcx.ccx, op.ty) {
143                                 // Note: perhaps this should be StructGep, but
144                                 // note that in some cases the values here will
145                                 // not be structs but arrays.
146                                 let i = if let Some(ref t) = translation {
147                                     t[i] as usize
148                                 } else {
149                                     i
150                                 };
151                                 let dest = bcx.gepi(dest.llval, &[0, i]);
152                                 self.store_operand(&bcx, dest, alignment.to_align(), op);
153                             }
154                         }
155                     }
156                 }
157                 bcx
158             }
159
160             _ => {
161                 assert!(self.rvalue_creates_operand(rvalue));
162                 let (bcx, temp) = self.trans_rvalue_operand(bcx, rvalue);
163                 self.store_operand(&bcx, dest.llval, dest.alignment.to_align(), temp);
164                 bcx
165             }
166         }
167     }
168
169     pub fn trans_rvalue_operand(&mut self,
170                                 bcx: Builder<'a, 'tcx>,
171                                 rvalue: &mir::Rvalue<'tcx>)
172                                 -> (Builder<'a, 'tcx>, OperandRef<'tcx>)
173     {
174         assert!(self.rvalue_creates_operand(rvalue), "cannot trans {:?} to operand", rvalue);
175
176         match *rvalue {
177             mir::Rvalue::Cast(ref kind, ref source, cast_ty) => {
178                 let operand = self.trans_operand(&bcx, source);
179                 debug!("cast operand is {:?}", operand);
180                 let cast_ty = self.monomorphize(&cast_ty);
181
182                 let val = match *kind {
183                     mir::CastKind::ReifyFnPointer => {
184                         match operand.ty.sty {
185                             ty::TyFnDef(def_id, substs, _) => {
186                                 OperandValue::Immediate(
187                                     callee::resolve_and_get_fn(bcx.ccx, def_id, substs))
188                             }
189                             _ => {
190                                 bug!("{} cannot be reified to a fn ptr", operand.ty)
191                             }
192                         }
193                     }
194                     mir::CastKind::ClosureFnPointer => {
195                         match operand.ty.sty {
196                             ty::TyClosure(def_id, substs) => {
197                                 let instance = monomorphize::resolve_closure(
198                                     bcx.ccx.shared(), def_id, substs, ty::ClosureKind::FnOnce);
199                                 OperandValue::Immediate(callee::get_fn(bcx.ccx, instance))
200                             }
201                             _ => {
202                                 bug!("{} cannot be cast to a fn ptr", operand.ty)
203                             }
204                         }
205                     }
206                     mir::CastKind::UnsafeFnPointer => {
207                         // this is a no-op at the LLVM level
208                         operand.val
209                     }
210                     mir::CastKind::Unsize => {
211                         // unsize targets other than to a fat pointer currently
212                         // can't be operands.
213                         assert!(common::type_is_fat_ptr(bcx.ccx, cast_ty));
214
215                         match operand.val {
216                             OperandValue::Pair(lldata, llextra) => {
217                                 // unsize from a fat pointer - this is a
218                                 // "trait-object-to-supertrait" coercion, for
219                                 // example,
220                                 //   &'a fmt::Debug+Send => &'a fmt::Debug,
221                                 // So we need to pointercast the base to ensure
222                                 // the types match up.
223                                 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, cast_ty);
224                                 let lldata = bcx.pointercast(lldata, llcast_ty);
225                                 OperandValue::Pair(lldata, llextra)
226                             }
227                             OperandValue::Immediate(lldata) => {
228                                 // "standard" unsize
229                                 let (lldata, llextra) = base::unsize_thin_ptr(&bcx, lldata,
230                                     operand.ty, cast_ty);
231                                 OperandValue::Pair(lldata, llextra)
232                             }
233                             OperandValue::Ref(..) => {
234                                 bug!("by-ref operand {:?} in trans_rvalue_operand",
235                                      operand);
236                             }
237                         }
238                     }
239                     mir::CastKind::Misc if common::type_is_fat_ptr(bcx.ccx, operand.ty) => {
240                         let ll_cast_ty = type_of::immediate_type_of(bcx.ccx, cast_ty);
241                         let ll_from_ty = type_of::immediate_type_of(bcx.ccx, operand.ty);
242                         if let OperandValue::Pair(data_ptr, meta_ptr) = operand.val {
243                             if common::type_is_fat_ptr(bcx.ccx, cast_ty) {
244                                 let ll_cft = ll_cast_ty.field_types();
245                                 let ll_fft = ll_from_ty.field_types();
246                                 let data_cast = bcx.pointercast(data_ptr, ll_cft[0]);
247                                 assert_eq!(ll_cft[1].kind(), ll_fft[1].kind());
248                                 OperandValue::Pair(data_cast, meta_ptr)
249                             } else { // cast to thin-ptr
250                                 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
251                                 // pointer-cast of that pointer to desired pointer type.
252                                 let llval = bcx.pointercast(data_ptr, ll_cast_ty);
253                                 OperandValue::Immediate(llval)
254                             }
255                         } else {
256                             bug!("Unexpected non-Pair operand")
257                         }
258                     }
259                     mir::CastKind::Misc => {
260                         debug_assert!(common::type_is_immediate(bcx.ccx, cast_ty));
261                         let r_t_in = CastTy::from_ty(operand.ty).expect("bad input type for cast");
262                         let r_t_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
263                         let ll_t_in = type_of::immediate_type_of(bcx.ccx, operand.ty);
264                         let ll_t_out = type_of::immediate_type_of(bcx.ccx, cast_ty);
265                         let llval = operand.immediate();
266                         let l = bcx.ccx.layout_of(operand.ty);
267                         let signed = if let Layout::CEnum { signed, min, max, .. } = *l {
268                             if max > min {
269                                 // We want `table[e as usize]` to not
270                                 // have bound checks, and this is the most
271                                 // convenient place to put the `assume`.
272
273                                 base::call_assume(&bcx, bcx.icmp(
274                                     llvm::IntULE,
275                                     llval,
276                                     C_integral(common::val_ty(llval), max, false)
277                                 ));
278                             }
279
280                             signed
281                         } else {
282                             operand.ty.is_signed()
283                         };
284
285                         let newval = match (r_t_in, r_t_out) {
286                             (CastTy::Int(_), CastTy::Int(_)) => {
287                                 bcx.intcast(llval, ll_t_out, signed)
288                             }
289                             (CastTy::Float, CastTy::Float) => {
290                                 let srcsz = ll_t_in.float_width();
291                                 let dstsz = ll_t_out.float_width();
292                                 if dstsz > srcsz {
293                                     bcx.fpext(llval, ll_t_out)
294                                 } else if srcsz > dstsz {
295                                     bcx.fptrunc(llval, ll_t_out)
296                                 } else {
297                                     llval
298                                 }
299                             }
300                             (CastTy::Ptr(_), CastTy::Ptr(_)) |
301                             (CastTy::FnPtr, CastTy::Ptr(_)) |
302                             (CastTy::RPtr(_), CastTy::Ptr(_)) =>
303                                 bcx.pointercast(llval, ll_t_out),
304                             (CastTy::Ptr(_), CastTy::Int(_)) |
305                             (CastTy::FnPtr, CastTy::Int(_)) =>
306                                 bcx.ptrtoint(llval, ll_t_out),
307                             (CastTy::Int(_), CastTy::Ptr(_)) =>
308                                 bcx.inttoptr(llval, ll_t_out),
309                             (CastTy::Int(_), CastTy::Float) if signed =>
310                                 bcx.sitofp(llval, ll_t_out),
311                             (CastTy::Int(_), CastTy::Float) =>
312                                 bcx.uitofp(llval, ll_t_out),
313                             (CastTy::Float, CastTy::Int(IntTy::I)) =>
314                                 bcx.fptosi(llval, ll_t_out),
315                             (CastTy::Float, CastTy::Int(_)) =>
316                                 bcx.fptoui(llval, ll_t_out),
317                             _ => bug!("unsupported cast: {:?} to {:?}", operand.ty, cast_ty)
318                         };
319                         OperandValue::Immediate(newval)
320                     }
321                 };
322                 let operand = OperandRef {
323                     val: val,
324                     ty: cast_ty
325                 };
326                 (bcx, operand)
327             }
328
329             mir::Rvalue::Ref(_, bk, ref lvalue) => {
330                 let tr_lvalue = self.trans_lvalue(&bcx, lvalue);
331
332                 let ty = tr_lvalue.ty.to_ty(bcx.tcx());
333                 let ref_ty = bcx.tcx().mk_ref(
334                     bcx.tcx().mk_region(ty::ReErased),
335                     ty::TypeAndMut { ty: ty, mutbl: bk.to_mutbl_lossy() }
336                 );
337
338                 // Note: lvalues are indirect, so storing the `llval` into the
339                 // destination effectively creates a reference.
340                 let operand = if bcx.ccx.shared().type_is_sized(ty) {
341                     OperandRef {
342                         val: OperandValue::Immediate(tr_lvalue.llval),
343                         ty: ref_ty,
344                     }
345                 } else {
346                     OperandRef {
347                         val: OperandValue::Pair(tr_lvalue.llval,
348                                                 tr_lvalue.llextra),
349                         ty: ref_ty,
350                     }
351                 };
352                 (bcx, operand)
353             }
354
355             mir::Rvalue::Len(ref lvalue) => {
356                 let tr_lvalue = self.trans_lvalue(&bcx, lvalue);
357                 let operand = OperandRef {
358                     val: OperandValue::Immediate(tr_lvalue.len(bcx.ccx)),
359                     ty: bcx.tcx().types.usize,
360                 };
361                 (bcx, operand)
362             }
363
364             mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
365                 let lhs = self.trans_operand(&bcx, lhs);
366                 let rhs = self.trans_operand(&bcx, rhs);
367                 let llresult = if common::type_is_fat_ptr(bcx.ccx, lhs.ty) {
368                     match (lhs.val, rhs.val) {
369                         (OperandValue::Pair(lhs_addr, lhs_extra),
370                          OperandValue::Pair(rhs_addr, rhs_extra)) => {
371                             self.trans_fat_ptr_binop(&bcx, op,
372                                                      lhs_addr, lhs_extra,
373                                                      rhs_addr, rhs_extra,
374                                                      lhs.ty)
375                         }
376                         _ => bug!()
377                     }
378
379                 } else {
380                     self.trans_scalar_binop(&bcx, op,
381                                             lhs.immediate(), rhs.immediate(),
382                                             lhs.ty)
383                 };
384                 let operand = OperandRef {
385                     val: OperandValue::Immediate(llresult),
386                     ty: op.ty(bcx.tcx(), lhs.ty, rhs.ty),
387                 };
388                 (bcx, operand)
389             }
390             mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
391                 let lhs = self.trans_operand(&bcx, lhs);
392                 let rhs = self.trans_operand(&bcx, rhs);
393                 let result = self.trans_scalar_checked_binop(&bcx, op,
394                                                              lhs.immediate(), rhs.immediate(),
395                                                              lhs.ty);
396                 let val_ty = op.ty(bcx.tcx(), lhs.ty, rhs.ty);
397                 let operand_ty = bcx.tcx().intern_tup(&[val_ty, bcx.tcx().types.bool], false);
398                 let operand = OperandRef {
399                     val: result,
400                     ty: operand_ty
401                 };
402
403                 (bcx, operand)
404             }
405
406             mir::Rvalue::UnaryOp(op, ref operand) => {
407                 let operand = self.trans_operand(&bcx, operand);
408                 let lloperand = operand.immediate();
409                 let is_float = operand.ty.is_fp();
410                 let llval = match op {
411                     mir::UnOp::Not => bcx.not(lloperand),
412                     mir::UnOp::Neg => if is_float {
413                         bcx.fneg(lloperand)
414                     } else {
415                         bcx.neg(lloperand)
416                     }
417                 };
418                 (bcx, OperandRef {
419                     val: OperandValue::Immediate(llval),
420                     ty: operand.ty,
421                 })
422             }
423
424             mir::Rvalue::Discriminant(ref lvalue) => {
425                 let discr_lvalue = self.trans_lvalue(&bcx, lvalue);
426                 let enum_ty = discr_lvalue.ty.to_ty(bcx.tcx());
427                 let discr_ty = rvalue.ty(&*self.mir, bcx.tcx());
428                 let discr_type = type_of::immediate_type_of(bcx.ccx, discr_ty);
429                 let discr = adt::trans_get_discr(&bcx, enum_ty, discr_lvalue.llval,
430                                                   discr_lvalue.alignment, Some(discr_type), true);
431                 (bcx, OperandRef {
432                     val: OperandValue::Immediate(discr),
433                     ty: discr_ty
434                 })
435             }
436
437             mir::Rvalue::Box(content_ty) => {
438                 let content_ty: Ty<'tcx> = self.monomorphize(&content_ty);
439                 let llty = type_of::type_of(bcx.ccx, content_ty);
440                 let llsize = machine::llsize_of(bcx.ccx, llty);
441                 let align = bcx.ccx.align_of(content_ty);
442                 let llalign = C_uint(bcx.ccx, align);
443                 let llty_ptr = llty.ptr_to();
444                 let box_ty = bcx.tcx().mk_box(content_ty);
445
446                 // Allocate space:
447                 let def_id = match bcx.tcx().lang_items.require(ExchangeMallocFnLangItem) {
448                     Ok(id) => id,
449                     Err(s) => {
450                         bcx.sess().fatal(&format!("allocation of `{}` {}", box_ty, s));
451                     }
452                 };
453                 let instance = ty::Instance::mono(bcx.tcx(), def_id);
454                 let r = callee::get_fn(bcx.ccx, instance);
455                 let val = bcx.pointercast(bcx.call(r, &[llsize, llalign], None), llty_ptr);
456
457                 let operand = OperandRef {
458                     val: OperandValue::Immediate(val),
459                     ty: box_ty,
460                 };
461                 (bcx, operand)
462             }
463             mir::Rvalue::Use(ref operand) => {
464                 let operand = self.trans_operand(&bcx, operand);
465                 (bcx, operand)
466             }
467             mir::Rvalue::Repeat(..) |
468             mir::Rvalue::Aggregate(..) => {
469                 // According to `rvalue_creates_operand`, only ZST
470                 // aggregate rvalues are allowed to be operands.
471                 let ty = rvalue.ty(self.mir, self.ccx.tcx());
472                 (bcx, OperandRef::new_zst(self.ccx, self.monomorphize(&ty)))
473             }
474         }
475     }
476
477     pub fn trans_scalar_binop(&mut self,
478                               bcx: &Builder<'a, 'tcx>,
479                               op: mir::BinOp,
480                               lhs: ValueRef,
481                               rhs: ValueRef,
482                               input_ty: Ty<'tcx>) -> ValueRef {
483         let is_float = input_ty.is_fp();
484         let is_signed = input_ty.is_signed();
485         let is_nil = input_ty.is_nil();
486         let is_bool = input_ty.is_bool();
487         match op {
488             mir::BinOp::Add => if is_float {
489                 bcx.fadd(lhs, rhs)
490             } else {
491                 bcx.add(lhs, rhs)
492             },
493             mir::BinOp::Sub => if is_float {
494                 bcx.fsub(lhs, rhs)
495             } else {
496                 bcx.sub(lhs, rhs)
497             },
498             mir::BinOp::Mul => if is_float {
499                 bcx.fmul(lhs, rhs)
500             } else {
501                 bcx.mul(lhs, rhs)
502             },
503             mir::BinOp::Div => if is_float {
504                 bcx.fdiv(lhs, rhs)
505             } else if is_signed {
506                 bcx.sdiv(lhs, rhs)
507             } else {
508                 bcx.udiv(lhs, rhs)
509             },
510             mir::BinOp::Rem => if is_float {
511                 bcx.frem(lhs, rhs)
512             } else if is_signed {
513                 bcx.srem(lhs, rhs)
514             } else {
515                 bcx.urem(lhs, rhs)
516             },
517             mir::BinOp::BitOr => bcx.or(lhs, rhs),
518             mir::BinOp::BitAnd => bcx.and(lhs, rhs),
519             mir::BinOp::BitXor => bcx.xor(lhs, rhs),
520             mir::BinOp::Shl => common::build_unchecked_lshift(bcx, lhs, rhs),
521             mir::BinOp::Shr => common::build_unchecked_rshift(bcx, input_ty, lhs, rhs),
522             mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt |
523             mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => if is_nil {
524                 C_bool(bcx.ccx, match op {
525                     mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt => false,
526                     mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => true,
527                     _ => unreachable!()
528                 })
529             } else if is_float {
530                 bcx.fcmp(
531                     base::bin_op_to_fcmp_predicate(op.to_hir_binop()),
532                     lhs, rhs
533                 )
534             } else {
535                 let (lhs, rhs) = if is_bool {
536                     // FIXME(#36856) -- extend the bools into `i8` because
537                     // LLVM's i1 comparisons are broken.
538                     (bcx.zext(lhs, Type::i8(bcx.ccx)),
539                      bcx.zext(rhs, Type::i8(bcx.ccx)))
540                 } else {
541                     (lhs, rhs)
542                 };
543
544                 bcx.icmp(
545                     base::bin_op_to_icmp_predicate(op.to_hir_binop(), is_signed),
546                     lhs, rhs
547                 )
548             }
549         }
550     }
551
552     pub fn trans_fat_ptr_binop(&mut self,
553                                bcx: &Builder<'a, 'tcx>,
554                                op: mir::BinOp,
555                                lhs_addr: ValueRef,
556                                lhs_extra: ValueRef,
557                                rhs_addr: ValueRef,
558                                rhs_extra: ValueRef,
559                                _input_ty: Ty<'tcx>)
560                                -> ValueRef {
561         match op {
562             mir::BinOp::Eq => {
563                 bcx.and(
564                     bcx.icmp(llvm::IntEQ, lhs_addr, rhs_addr),
565                     bcx.icmp(llvm::IntEQ, lhs_extra, rhs_extra)
566                 )
567             }
568             mir::BinOp::Ne => {
569                 bcx.or(
570                     bcx.icmp(llvm::IntNE, lhs_addr, rhs_addr),
571                     bcx.icmp(llvm::IntNE, lhs_extra, rhs_extra)
572                 )
573             }
574             mir::BinOp::Le | mir::BinOp::Lt |
575             mir::BinOp::Ge | mir::BinOp::Gt => {
576                 // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
577                 let (op, strict_op) = match op {
578                     mir::BinOp::Lt => (llvm::IntULT, llvm::IntULT),
579                     mir::BinOp::Le => (llvm::IntULE, llvm::IntULT),
580                     mir::BinOp::Gt => (llvm::IntUGT, llvm::IntUGT),
581                     mir::BinOp::Ge => (llvm::IntUGE, llvm::IntUGT),
582                     _ => bug!(),
583                 };
584
585                 bcx.or(
586                     bcx.icmp(strict_op, lhs_addr, rhs_addr),
587                     bcx.and(
588                         bcx.icmp(llvm::IntEQ, lhs_addr, rhs_addr),
589                         bcx.icmp(op, lhs_extra, rhs_extra)
590                     )
591                 )
592             }
593             _ => {
594                 bug!("unexpected fat ptr binop");
595             }
596         }
597     }
598
599     pub fn trans_scalar_checked_binop(&mut self,
600                                       bcx: &Builder<'a, 'tcx>,
601                                       op: mir::BinOp,
602                                       lhs: ValueRef,
603                                       rhs: ValueRef,
604                                       input_ty: Ty<'tcx>) -> OperandValue {
605         // This case can currently arise only from functions marked
606         // with #[rustc_inherit_overflow_checks] and inlined from
607         // another crate (mostly core::num generic/#[inline] fns),
608         // while the current crate doesn't use overflow checks.
609         if !bcx.ccx.check_overflow() {
610             let val = self.trans_scalar_binop(bcx, op, lhs, rhs, input_ty);
611             return OperandValue::Pair(val, C_bool(bcx.ccx, false));
612         }
613
614         // First try performing the operation on constants, which
615         // will only succeed if both operands are constant.
616         // This is necessary to determine when an overflow Assert
617         // will always panic at runtime, and produce a warning.
618         if let Some((val, of)) = const_scalar_checked_binop(bcx.tcx(), op, lhs, rhs, input_ty) {
619             return OperandValue::Pair(val, C_bool(bcx.ccx, of));
620         }
621
622         let (val, of) = match op {
623             // These are checked using intrinsics
624             mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
625                 let oop = match op {
626                     mir::BinOp::Add => OverflowOp::Add,
627                     mir::BinOp::Sub => OverflowOp::Sub,
628                     mir::BinOp::Mul => OverflowOp::Mul,
629                     _ => unreachable!()
630                 };
631                 let intrinsic = get_overflow_intrinsic(oop, bcx, input_ty);
632                 let res = bcx.call(intrinsic, &[lhs, rhs], None);
633
634                 (bcx.extract_value(res, 0),
635                  bcx.extract_value(res, 1))
636             }
637             mir::BinOp::Shl | mir::BinOp::Shr => {
638                 let lhs_llty = val_ty(lhs);
639                 let rhs_llty = val_ty(rhs);
640                 let invert_mask = common::shift_mask_val(&bcx, lhs_llty, rhs_llty, true);
641                 let outer_bits = bcx.and(rhs, invert_mask);
642
643                 let of = bcx.icmp(llvm::IntNE, outer_bits, C_null(rhs_llty));
644                 let val = self.trans_scalar_binop(bcx, op, lhs, rhs, input_ty);
645
646                 (val, of)
647             }
648             _ => {
649                 bug!("Operator `{:?}` is not a checkable operator", op)
650             }
651         };
652
653         OperandValue::Pair(val, of)
654     }
655
656     pub fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>) -> bool {
657         match *rvalue {
658             mir::Rvalue::Ref(..) |
659             mir::Rvalue::Len(..) |
660             mir::Rvalue::Cast(..) | // (*)
661             mir::Rvalue::BinaryOp(..) |
662             mir::Rvalue::CheckedBinaryOp(..) |
663             mir::Rvalue::UnaryOp(..) |
664             mir::Rvalue::Discriminant(..) |
665             mir::Rvalue::Box(..) |
666             mir::Rvalue::Use(..) => // (*)
667                 true,
668             mir::Rvalue::Repeat(..) |
669             mir::Rvalue::Aggregate(..) => {
670                 let ty = rvalue.ty(self.mir, self.ccx.tcx());
671                 let ty = self.monomorphize(&ty);
672                 common::type_is_zero_size(self.ccx, ty)
673             }
674         }
675
676         // (*) this is only true if the type is suitable
677     }
678 }
679
680 #[derive(Copy, Clone)]
681 enum OverflowOp {
682     Add, Sub, Mul
683 }
684
685 fn get_overflow_intrinsic(oop: OverflowOp, bcx: &Builder, ty: Ty) -> ValueRef {
686     use syntax::ast::IntTy::*;
687     use syntax::ast::UintTy::*;
688     use rustc::ty::{TyInt, TyUint};
689
690     let tcx = bcx.tcx();
691
692     let new_sty = match ty.sty {
693         TyInt(Is) => match &tcx.sess.target.target.target_pointer_width[..] {
694             "16" => TyInt(I16),
695             "32" => TyInt(I32),
696             "64" => TyInt(I64),
697             _ => panic!("unsupported target word size")
698         },
699         TyUint(Us) => match &tcx.sess.target.target.target_pointer_width[..] {
700             "16" => TyUint(U16),
701             "32" => TyUint(U32),
702             "64" => TyUint(U64),
703             _ => panic!("unsupported target word size")
704         },
705         ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
706         _ => panic!("tried to get overflow intrinsic for op applied to non-int type")
707     };
708
709     let name = match oop {
710         OverflowOp::Add => match new_sty {
711             TyInt(I8) => "llvm.sadd.with.overflow.i8",
712             TyInt(I16) => "llvm.sadd.with.overflow.i16",
713             TyInt(I32) => "llvm.sadd.with.overflow.i32",
714             TyInt(I64) => "llvm.sadd.with.overflow.i64",
715             TyInt(I128) => "llvm.sadd.with.overflow.i128",
716
717             TyUint(U8) => "llvm.uadd.with.overflow.i8",
718             TyUint(U16) => "llvm.uadd.with.overflow.i16",
719             TyUint(U32) => "llvm.uadd.with.overflow.i32",
720             TyUint(U64) => "llvm.uadd.with.overflow.i64",
721             TyUint(U128) => "llvm.uadd.with.overflow.i128",
722
723             _ => unreachable!(),
724         },
725         OverflowOp::Sub => match new_sty {
726             TyInt(I8) => "llvm.ssub.with.overflow.i8",
727             TyInt(I16) => "llvm.ssub.with.overflow.i16",
728             TyInt(I32) => "llvm.ssub.with.overflow.i32",
729             TyInt(I64) => "llvm.ssub.with.overflow.i64",
730             TyInt(I128) => "llvm.ssub.with.overflow.i128",
731
732             TyUint(U8) => "llvm.usub.with.overflow.i8",
733             TyUint(U16) => "llvm.usub.with.overflow.i16",
734             TyUint(U32) => "llvm.usub.with.overflow.i32",
735             TyUint(U64) => "llvm.usub.with.overflow.i64",
736             TyUint(U128) => "llvm.usub.with.overflow.i128",
737
738             _ => unreachable!(),
739         },
740         OverflowOp::Mul => match new_sty {
741             TyInt(I8) => "llvm.smul.with.overflow.i8",
742             TyInt(I16) => "llvm.smul.with.overflow.i16",
743             TyInt(I32) => "llvm.smul.with.overflow.i32",
744             TyInt(I64) => "llvm.smul.with.overflow.i64",
745             TyInt(I128) => "llvm.smul.with.overflow.i128",
746
747             TyUint(U8) => "llvm.umul.with.overflow.i8",
748             TyUint(U16) => "llvm.umul.with.overflow.i16",
749             TyUint(U32) => "llvm.umul.with.overflow.i32",
750             TyUint(U64) => "llvm.umul.with.overflow.i64",
751             TyUint(U128) => "llvm.umul.with.overflow.i128",
752
753             _ => unreachable!(),
754         },
755     };
756
757     bcx.ccx.get_intrinsic(&name)
758 }