]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/rvalue.rs
Fix invalid associated type rendering in rustdoc
[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!(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!(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                 bug!("cannot generate operand from rvalue {:?}", rvalue);
470
471             }
472         }
473     }
474
475     pub fn trans_scalar_binop(&mut self,
476                               bcx: &Builder<'a, 'tcx>,
477                               op: mir::BinOp,
478                               lhs: ValueRef,
479                               rhs: ValueRef,
480                               input_ty: Ty<'tcx>) -> ValueRef {
481         let is_float = input_ty.is_fp();
482         let is_signed = input_ty.is_signed();
483         let is_nil = input_ty.is_nil();
484         let is_bool = input_ty.is_bool();
485         match op {
486             mir::BinOp::Add => if is_float {
487                 bcx.fadd(lhs, rhs)
488             } else {
489                 bcx.add(lhs, rhs)
490             },
491             mir::BinOp::Sub => if is_float {
492                 bcx.fsub(lhs, rhs)
493             } else {
494                 bcx.sub(lhs, rhs)
495             },
496             mir::BinOp::Mul => if is_float {
497                 bcx.fmul(lhs, rhs)
498             } else {
499                 bcx.mul(lhs, rhs)
500             },
501             mir::BinOp::Div => if is_float {
502                 bcx.fdiv(lhs, rhs)
503             } else if is_signed {
504                 bcx.sdiv(lhs, rhs)
505             } else {
506                 bcx.udiv(lhs, rhs)
507             },
508             mir::BinOp::Rem => if is_float {
509                 bcx.frem(lhs, rhs)
510             } else if is_signed {
511                 bcx.srem(lhs, rhs)
512             } else {
513                 bcx.urem(lhs, rhs)
514             },
515             mir::BinOp::BitOr => bcx.or(lhs, rhs),
516             mir::BinOp::BitAnd => bcx.and(lhs, rhs),
517             mir::BinOp::BitXor => bcx.xor(lhs, rhs),
518             mir::BinOp::Shl => common::build_unchecked_lshift(bcx, lhs, rhs),
519             mir::BinOp::Shr => common::build_unchecked_rshift(bcx, input_ty, lhs, rhs),
520             mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt |
521             mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => if is_nil {
522                 C_bool(bcx.ccx, match op {
523                     mir::BinOp::Ne | mir::BinOp::Lt | mir::BinOp::Gt => false,
524                     mir::BinOp::Eq | mir::BinOp::Le | mir::BinOp::Ge => true,
525                     _ => unreachable!()
526                 })
527             } else if is_float {
528                 bcx.fcmp(
529                     base::bin_op_to_fcmp_predicate(op.to_hir_binop()),
530                     lhs, rhs
531                 )
532             } else {
533                 let (lhs, rhs) = if is_bool {
534                     // FIXME(#36856) -- extend the bools into `i8` because
535                     // LLVM's i1 comparisons are broken.
536                     (bcx.zext(lhs, Type::i8(bcx.ccx)),
537                      bcx.zext(rhs, Type::i8(bcx.ccx)))
538                 } else {
539                     (lhs, rhs)
540                 };
541
542                 bcx.icmp(
543                     base::bin_op_to_icmp_predicate(op.to_hir_binop(), is_signed),
544                     lhs, rhs
545                 )
546             }
547         }
548     }
549
550     pub fn trans_fat_ptr_binop(&mut self,
551                                bcx: &Builder<'a, 'tcx>,
552                                op: mir::BinOp,
553                                lhs_addr: ValueRef,
554                                lhs_extra: ValueRef,
555                                rhs_addr: ValueRef,
556                                rhs_extra: ValueRef,
557                                _input_ty: Ty<'tcx>)
558                                -> ValueRef {
559         match op {
560             mir::BinOp::Eq => {
561                 bcx.and(
562                     bcx.icmp(llvm::IntEQ, lhs_addr, rhs_addr),
563                     bcx.icmp(llvm::IntEQ, lhs_extra, rhs_extra)
564                 )
565             }
566             mir::BinOp::Ne => {
567                 bcx.or(
568                     bcx.icmp(llvm::IntNE, lhs_addr, rhs_addr),
569                     bcx.icmp(llvm::IntNE, lhs_extra, rhs_extra)
570                 )
571             }
572             mir::BinOp::Le | mir::BinOp::Lt |
573             mir::BinOp::Ge | mir::BinOp::Gt => {
574                 // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
575                 let (op, strict_op) = match op {
576                     mir::BinOp::Lt => (llvm::IntULT, llvm::IntULT),
577                     mir::BinOp::Le => (llvm::IntULE, llvm::IntULT),
578                     mir::BinOp::Gt => (llvm::IntUGT, llvm::IntUGT),
579                     mir::BinOp::Ge => (llvm::IntUGE, llvm::IntUGT),
580                     _ => bug!(),
581                 };
582
583                 bcx.or(
584                     bcx.icmp(strict_op, lhs_addr, rhs_addr),
585                     bcx.and(
586                         bcx.icmp(llvm::IntEQ, lhs_addr, rhs_addr),
587                         bcx.icmp(op, lhs_extra, rhs_extra)
588                     )
589                 )
590             }
591             _ => {
592                 bug!("unexpected fat ptr binop");
593             }
594         }
595     }
596
597     pub fn trans_scalar_checked_binop(&mut self,
598                                       bcx: &Builder<'a, 'tcx>,
599                                       op: mir::BinOp,
600                                       lhs: ValueRef,
601                                       rhs: ValueRef,
602                                       input_ty: Ty<'tcx>) -> OperandValue {
603         // This case can currently arise only from functions marked
604         // with #[rustc_inherit_overflow_checks] and inlined from
605         // another crate (mostly core::num generic/#[inline] fns),
606         // while the current crate doesn't use overflow checks.
607         if !bcx.ccx.check_overflow() {
608             let val = self.trans_scalar_binop(bcx, op, lhs, rhs, input_ty);
609             return OperandValue::Pair(val, C_bool(bcx.ccx, false));
610         }
611
612         // First try performing the operation on constants, which
613         // will only succeed if both operands are constant.
614         // This is necessary to determine when an overflow Assert
615         // will always panic at runtime, and produce a warning.
616         if let Some((val, of)) = const_scalar_checked_binop(bcx.tcx(), op, lhs, rhs, input_ty) {
617             return OperandValue::Pair(val, C_bool(bcx.ccx, of));
618         }
619
620         let (val, of) = match op {
621             // These are checked using intrinsics
622             mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
623                 let oop = match op {
624                     mir::BinOp::Add => OverflowOp::Add,
625                     mir::BinOp::Sub => OverflowOp::Sub,
626                     mir::BinOp::Mul => OverflowOp::Mul,
627                     _ => unreachable!()
628                 };
629                 let intrinsic = get_overflow_intrinsic(oop, bcx, input_ty);
630                 let res = bcx.call(intrinsic, &[lhs, rhs], None);
631
632                 (bcx.extract_value(res, 0),
633                  bcx.extract_value(res, 1))
634             }
635             mir::BinOp::Shl | mir::BinOp::Shr => {
636                 let lhs_llty = val_ty(lhs);
637                 let rhs_llty = val_ty(rhs);
638                 let invert_mask = common::shift_mask_val(&bcx, lhs_llty, rhs_llty, true);
639                 let outer_bits = bcx.and(rhs, invert_mask);
640
641                 let of = bcx.icmp(llvm::IntNE, outer_bits, C_null(rhs_llty));
642                 let val = self.trans_scalar_binop(bcx, op, lhs, rhs, input_ty);
643
644                 (val, of)
645             }
646             _ => {
647                 bug!("Operator `{:?}` is not a checkable operator", op)
648             }
649         };
650
651         OperandValue::Pair(val, of)
652     }
653 }
654
655 pub fn rvalue_creates_operand(rvalue: &mir::Rvalue) -> bool {
656     match *rvalue {
657         mir::Rvalue::Ref(..) |
658         mir::Rvalue::Len(..) |
659         mir::Rvalue::Cast(..) | // (*)
660         mir::Rvalue::BinaryOp(..) |
661         mir::Rvalue::CheckedBinaryOp(..) |
662         mir::Rvalue::UnaryOp(..) |
663         mir::Rvalue::Discriminant(..) |
664         mir::Rvalue::Box(..) |
665         mir::Rvalue::Use(..) => // (*)
666             true,
667         mir::Rvalue::Repeat(..) |
668         mir::Rvalue::Aggregate(..) =>
669             false,
670     }
671
672     // (*) this is only true if the type is suitable
673 }
674
675 #[derive(Copy, Clone)]
676 enum OverflowOp {
677     Add, Sub, Mul
678 }
679
680 fn get_overflow_intrinsic(oop: OverflowOp, bcx: &Builder, ty: Ty) -> ValueRef {
681     use syntax::ast::IntTy::*;
682     use syntax::ast::UintTy::*;
683     use rustc::ty::{TyInt, TyUint};
684
685     let tcx = bcx.tcx();
686
687     let new_sty = match ty.sty {
688         TyInt(Is) => match &tcx.sess.target.target.target_pointer_width[..] {
689             "16" => TyInt(I16),
690             "32" => TyInt(I32),
691             "64" => TyInt(I64),
692             _ => panic!("unsupported target word size")
693         },
694         TyUint(Us) => match &tcx.sess.target.target.target_pointer_width[..] {
695             "16" => TyUint(U16),
696             "32" => TyUint(U32),
697             "64" => TyUint(U64),
698             _ => panic!("unsupported target word size")
699         },
700         ref t @ TyUint(_) | ref t @ TyInt(_) => t.clone(),
701         _ => panic!("tried to get overflow intrinsic for op applied to non-int type")
702     };
703
704     let name = match oop {
705         OverflowOp::Add => match new_sty {
706             TyInt(I8) => "llvm.sadd.with.overflow.i8",
707             TyInt(I16) => "llvm.sadd.with.overflow.i16",
708             TyInt(I32) => "llvm.sadd.with.overflow.i32",
709             TyInt(I64) => "llvm.sadd.with.overflow.i64",
710             TyInt(I128) => "llvm.sadd.with.overflow.i128",
711
712             TyUint(U8) => "llvm.uadd.with.overflow.i8",
713             TyUint(U16) => "llvm.uadd.with.overflow.i16",
714             TyUint(U32) => "llvm.uadd.with.overflow.i32",
715             TyUint(U64) => "llvm.uadd.with.overflow.i64",
716             TyUint(U128) => "llvm.uadd.with.overflow.i128",
717
718             _ => unreachable!(),
719         },
720         OverflowOp::Sub => match new_sty {
721             TyInt(I8) => "llvm.ssub.with.overflow.i8",
722             TyInt(I16) => "llvm.ssub.with.overflow.i16",
723             TyInt(I32) => "llvm.ssub.with.overflow.i32",
724             TyInt(I64) => "llvm.ssub.with.overflow.i64",
725             TyInt(I128) => "llvm.ssub.with.overflow.i128",
726
727             TyUint(U8) => "llvm.usub.with.overflow.i8",
728             TyUint(U16) => "llvm.usub.with.overflow.i16",
729             TyUint(U32) => "llvm.usub.with.overflow.i32",
730             TyUint(U64) => "llvm.usub.with.overflow.i64",
731             TyUint(U128) => "llvm.usub.with.overflow.i128",
732
733             _ => unreachable!(),
734         },
735         OverflowOp::Mul => match new_sty {
736             TyInt(I8) => "llvm.smul.with.overflow.i8",
737             TyInt(I16) => "llvm.smul.with.overflow.i16",
738             TyInt(I32) => "llvm.smul.with.overflow.i32",
739             TyInt(I64) => "llvm.smul.with.overflow.i64",
740             TyInt(I128) => "llvm.smul.with.overflow.i128",
741
742             TyUint(U8) => "llvm.umul.with.overflow.i8",
743             TyUint(U16) => "llvm.umul.with.overflow.i16",
744             TyUint(U32) => "llvm.umul.with.overflow.i32",
745             TyUint(U64) => "llvm.umul.with.overflow.i64",
746             TyUint(U128) => "llvm.umul.with.overflow.i128",
747
748             _ => unreachable!(),
749         },
750     };
751
752     bcx.ccx.get_intrinsic(&name)
753 }