]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/intrinsic.rs
54e20f590c6718350bd22c1b4326402202f4cc63
[rust.git] / src / librustc_trans / intrinsic.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 #![allow(non_upper_case_globals)]
12
13 use intrinsics::{self, Intrinsic};
14 use libc;
15 use llvm;
16 use llvm::{ValueRef};
17 use abi::{Abi, FnType};
18 use adt;
19 use mir::lvalue::{LvalueRef, Alignment};
20 use base::*;
21 use common::*;
22 use declare;
23 use glue;
24 use type_of;
25 use machine;
26 use type_::Type;
27 use rustc::ty::{self, Ty};
28 use rustc::hir;
29 use syntax::ast;
30 use syntax::symbol::Symbol;
31 use builder::Builder;
32
33 use rustc::session::Session;
34 use syntax_pos::Span;
35
36 use std::cmp::Ordering;
37 use std::iter;
38
39 fn get_simple_intrinsic(ccx: &CrateContext, name: &str) -> Option<ValueRef> {
40     let llvm_name = match name {
41         "sqrtf32" => "llvm.sqrt.f32",
42         "sqrtf64" => "llvm.sqrt.f64",
43         "powif32" => "llvm.powi.f32",
44         "powif64" => "llvm.powi.f64",
45         "sinf32" => "llvm.sin.f32",
46         "sinf64" => "llvm.sin.f64",
47         "cosf32" => "llvm.cos.f32",
48         "cosf64" => "llvm.cos.f64",
49         "powf32" => "llvm.pow.f32",
50         "powf64" => "llvm.pow.f64",
51         "expf32" => "llvm.exp.f32",
52         "expf64" => "llvm.exp.f64",
53         "exp2f32" => "llvm.exp2.f32",
54         "exp2f64" => "llvm.exp2.f64",
55         "logf32" => "llvm.log.f32",
56         "logf64" => "llvm.log.f64",
57         "log10f32" => "llvm.log10.f32",
58         "log10f64" => "llvm.log10.f64",
59         "log2f32" => "llvm.log2.f32",
60         "log2f64" => "llvm.log2.f64",
61         "fmaf32" => "llvm.fma.f32",
62         "fmaf64" => "llvm.fma.f64",
63         "fabsf32" => "llvm.fabs.f32",
64         "fabsf64" => "llvm.fabs.f64",
65         "copysignf32" => "llvm.copysign.f32",
66         "copysignf64" => "llvm.copysign.f64",
67         "floorf32" => "llvm.floor.f32",
68         "floorf64" => "llvm.floor.f64",
69         "ceilf32" => "llvm.ceil.f32",
70         "ceilf64" => "llvm.ceil.f64",
71         "truncf32" => "llvm.trunc.f32",
72         "truncf64" => "llvm.trunc.f64",
73         "rintf32" => "llvm.rint.f32",
74         "rintf64" => "llvm.rint.f64",
75         "nearbyintf32" => "llvm.nearbyint.f32",
76         "nearbyintf64" => "llvm.nearbyint.f64",
77         "roundf32" => "llvm.round.f32",
78         "roundf64" => "llvm.round.f64",
79         "assume" => "llvm.assume",
80         "abort" => "llvm.trap",
81         _ => return None
82     };
83     Some(ccx.get_intrinsic(&llvm_name))
84 }
85
86 /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs,
87 /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics,
88 /// add them to librustc_trans/trans/context.rs
89 pub fn trans_intrinsic_call<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
90                                       callee_ty: Ty<'tcx>,
91                                       fn_ty: &FnType,
92                                       llargs: &[ValueRef],
93                                       llresult: ValueRef,
94                                       span: Span) {
95     let ccx = bcx.ccx;
96     let tcx = ccx.tcx();
97
98     let (def_id, substs, sig) = match callee_ty.sty {
99         ty::TyFnDef(def_id, substs, sig) => (def_id, substs, sig),
100         _ => bug!("expected fn item type, found {}", callee_ty)
101     };
102
103     let sig = tcx.erase_late_bound_regions_and_normalize(&sig);
104     let arg_tys = sig.inputs();
105     let ret_ty = sig.output();
106     let name = &*tcx.item_name(def_id).as_str();
107
108     let llret_ty = type_of::type_of(ccx, ret_ty);
109
110     let simple = get_simple_intrinsic(ccx, name);
111     let llval = match name {
112         _ if simple.is_some() => {
113             bcx.call(simple.unwrap(), &llargs, None)
114         }
115         "unreachable" => {
116             return;
117         },
118         "likely" => {
119             let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
120             bcx.call(expect, &[llargs[0], C_bool(ccx, true)], None)
121         }
122         "unlikely" => {
123             let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
124             bcx.call(expect, &[llargs[0], C_bool(ccx, false)], None)
125         }
126         "try" => {
127             try_intrinsic(bcx, ccx, llargs[0], llargs[1], llargs[2], llresult);
128             C_nil(ccx)
129         }
130         "breakpoint" => {
131             let llfn = ccx.get_intrinsic(&("llvm.debugtrap"));
132             bcx.call(llfn, &[], None)
133         }
134         "size_of" => {
135             let tp_ty = substs.type_at(0);
136             let lltp_ty = type_of::type_of(ccx, tp_ty);
137             C_uint(ccx, machine::llsize_of_alloc(ccx, lltp_ty))
138         }
139         "size_of_val" => {
140             let tp_ty = substs.type_at(0);
141             if !bcx.ccx.shared().type_is_sized(tp_ty) {
142                 let (llsize, _) =
143                     glue::size_and_align_of_dst(bcx, tp_ty, llargs[1]);
144                 llsize
145             } else {
146                 let lltp_ty = type_of::type_of(ccx, tp_ty);
147                 C_uint(ccx, machine::llsize_of_alloc(ccx, lltp_ty))
148             }
149         }
150         "min_align_of" => {
151             let tp_ty = substs.type_at(0);
152             C_uint(ccx, ccx.align_of(tp_ty))
153         }
154         "min_align_of_val" => {
155             let tp_ty = substs.type_at(0);
156             if !bcx.ccx.shared().type_is_sized(tp_ty) {
157                 let (_, llalign) =
158                     glue::size_and_align_of_dst(bcx, tp_ty, llargs[1]);
159                 llalign
160             } else {
161                 C_uint(ccx, ccx.align_of(tp_ty))
162             }
163         }
164         "pref_align_of" => {
165             let tp_ty = substs.type_at(0);
166             let lltp_ty = type_of::type_of(ccx, tp_ty);
167             C_uint(ccx, machine::llalign_of_pref(ccx, lltp_ty))
168         }
169         "type_name" => {
170             let tp_ty = substs.type_at(0);
171             let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
172             C_str_slice(ccx, ty_name)
173         }
174         "type_id" => {
175             C_u64(ccx, ccx.tcx().type_id_hash(substs.type_at(0)))
176         }
177         "init" => {
178             let ty = substs.type_at(0);
179             if !type_is_zero_size(ccx, ty) {
180                 // Just zero out the stack slot.
181                 // If we store a zero constant, LLVM will drown in vreg allocation for large data
182                 // structures, and the generated code will be awful. (A telltale sign of this is
183                 // large quantities of `mov [byte ptr foo],0` in the generated code.)
184                 memset_intrinsic(bcx, false, ty, llresult, C_u8(ccx, 0), C_uint(ccx, 1usize));
185             }
186             C_nil(ccx)
187         }
188         // Effectively no-ops
189         "uninit" => {
190             C_nil(ccx)
191         }
192         "needs_drop" => {
193             let tp_ty = substs.type_at(0);
194
195             C_bool(ccx, bcx.ccx.shared().type_needs_drop(tp_ty))
196         }
197         "offset" => {
198             let ptr = llargs[0];
199             let offset = llargs[1];
200             bcx.inbounds_gep(ptr, &[offset])
201         }
202         "arith_offset" => {
203             let ptr = llargs[0];
204             let offset = llargs[1];
205             bcx.gep(ptr, &[offset])
206         }
207
208         "copy_nonoverlapping" => {
209             copy_intrinsic(bcx, false, false, substs.type_at(0), llargs[1], llargs[0], llargs[2])
210         }
211         "copy" => {
212             copy_intrinsic(bcx, true, false, substs.type_at(0), llargs[1], llargs[0], llargs[2])
213         }
214         "write_bytes" => {
215             memset_intrinsic(bcx, false, substs.type_at(0), llargs[0], llargs[1], llargs[2])
216         }
217
218         "volatile_copy_nonoverlapping_memory" => {
219             copy_intrinsic(bcx, false, true, substs.type_at(0), llargs[0], llargs[1], llargs[2])
220         }
221         "volatile_copy_memory" => {
222             copy_intrinsic(bcx, true, true, substs.type_at(0), llargs[0], llargs[1], llargs[2])
223         }
224         "volatile_set_memory" => {
225             memset_intrinsic(bcx, true, substs.type_at(0), llargs[0], llargs[1], llargs[2])
226         }
227         "volatile_load" => {
228             let tp_ty = substs.type_at(0);
229             let mut ptr = llargs[0];
230             if let Some(ty) = fn_ty.ret.cast {
231                 ptr = bcx.pointercast(ptr, ty.ptr_to());
232             }
233             let load = bcx.volatile_load(ptr);
234             unsafe {
235                 llvm::LLVMSetAlignment(load, ccx.align_of(tp_ty));
236             }
237             to_immediate(bcx, load, tp_ty)
238         },
239         "volatile_store" => {
240             let tp_ty = substs.type_at(0);
241             if type_is_fat_ptr(bcx.ccx, tp_ty) {
242                 bcx.volatile_store(llargs[1], get_dataptr(bcx, llargs[0]));
243                 bcx.volatile_store(llargs[2], get_meta(bcx, llargs[0]));
244             } else {
245                 let val = if fn_ty.args[1].is_indirect() {
246                     bcx.load(llargs[1], None)
247                 } else {
248                     from_immediate(bcx, llargs[1])
249                 };
250                 let ptr = bcx.pointercast(llargs[0], val_ty(val).ptr_to());
251                 let store = bcx.volatile_store(val, ptr);
252                 unsafe {
253                     llvm::LLVMSetAlignment(store, ccx.align_of(tp_ty));
254                 }
255             }
256             C_nil(ccx)
257         },
258
259         "ctlz" | "cttz" | "ctpop" | "bswap" |
260         "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" |
261         "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
262         "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" => {
263             let sty = &arg_tys[0].sty;
264             match int_type_width_signed(sty, ccx) {
265                 Some((width, signed)) =>
266                     match name {
267                         "ctlz" | "cttz" => {
268                             let y = C_bool(bcx.ccx, false);
269                             let llfn = ccx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
270                             bcx.call(llfn, &[llargs[0], y], None)
271                         }
272                         "ctpop" => bcx.call(ccx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
273                                         &llargs, None),
274                         "bswap" => {
275                             if width == 8 {
276                                 llargs[0] // byte swap a u8/i8 is just a no-op
277                             } else {
278                                 bcx.call(ccx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
279                                         &llargs, None)
280                             }
281                         }
282                         "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
283                             let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
284                                                     if signed { 's' } else { 'u' },
285                                                     &name[..3], width);
286                             let llfn = bcx.ccx.get_intrinsic(&intrinsic);
287
288                             // Convert `i1` to a `bool`, and write it to the out parameter
289                             let val = bcx.call(llfn, &[llargs[0], llargs[1]], None);
290                             let result = bcx.extract_value(val, 0);
291                             let overflow = bcx.zext(bcx.extract_value(val, 1), Type::bool(ccx));
292                             bcx.store(result, bcx.struct_gep(llresult, 0), None);
293                             bcx.store(overflow, bcx.struct_gep(llresult, 1), None);
294
295                             C_nil(bcx.ccx)
296                         },
297                         "overflowing_add" => bcx.add(llargs[0], llargs[1]),
298                         "overflowing_sub" => bcx.sub(llargs[0], llargs[1]),
299                         "overflowing_mul" => bcx.mul(llargs[0], llargs[1]),
300                         "unchecked_div" =>
301                             if signed {
302                                 bcx.sdiv(llargs[0], llargs[1])
303                             } else {
304                                 bcx.udiv(llargs[0], llargs[1])
305                             },
306                         "unchecked_rem" =>
307                             if signed {
308                                 bcx.srem(llargs[0], llargs[1])
309                             } else {
310                                 bcx.urem(llargs[0], llargs[1])
311                             },
312                         "unchecked_shl" => bcx.shl(llargs[0], llargs[1]),
313                         "unchecked_shr" =>
314                             if signed {
315                                 bcx.ashr(llargs[0], llargs[1])
316                             } else {
317                                 bcx.lshr(llargs[0], llargs[1])
318                             },
319                         _ => bug!(),
320                     },
321                 None => {
322                     span_invalid_monomorphization_error(
323                         tcx.sess, span,
324                         &format!("invalid monomorphization of `{}` intrinsic: \
325                                   expected basic integer type, found `{}`", name, sty));
326                         C_nil(ccx)
327                 }
328             }
329
330         },
331         "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
332             let sty = &arg_tys[0].sty;
333             match float_type_width(sty) {
334                 Some(_width) =>
335                     match name {
336                         "fadd_fast" => bcx.fadd_fast(llargs[0], llargs[1]),
337                         "fsub_fast" => bcx.fsub_fast(llargs[0], llargs[1]),
338                         "fmul_fast" => bcx.fmul_fast(llargs[0], llargs[1]),
339                         "fdiv_fast" => bcx.fdiv_fast(llargs[0], llargs[1]),
340                         "frem_fast" => bcx.frem_fast(llargs[0], llargs[1]),
341                         _ => bug!(),
342                     },
343                 None => {
344                     span_invalid_monomorphization_error(
345                         tcx.sess, span,
346                         &format!("invalid monomorphization of `{}` intrinsic: \
347                                   expected basic float type, found `{}`", name, sty));
348                         C_nil(ccx)
349                 }
350             }
351
352         },
353
354         "discriminant_value" => {
355             let val_ty = substs.type_at(0);
356             match val_ty.sty {
357                 ty::TyAdt(adt, ..) if adt.is_enum() => {
358                     adt::trans_get_discr(bcx, val_ty, llargs[0], Alignment::AbiAligned,
359                                          Some(llret_ty), true)
360                 }
361                 _ => C_null(llret_ty)
362             }
363         }
364         name if name.starts_with("simd_") => {
365             generic_simd_intrinsic(bcx, name,
366                                    callee_ty,
367                                    &llargs,
368                                    ret_ty, llret_ty,
369                                    span)
370         }
371         // This requires that atomic intrinsics follow a specific naming pattern:
372         // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
373         name if name.starts_with("atomic_") => {
374             use llvm::AtomicOrdering::*;
375
376             let split: Vec<&str> = name.split('_').collect();
377
378             let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
379             let (order, failorder) = match split.len() {
380                 2 => (SequentiallyConsistent, SequentiallyConsistent),
381                 3 => match split[2] {
382                     "unordered" => (Unordered, Unordered),
383                     "relaxed" => (Monotonic, Monotonic),
384                     "acq"     => (Acquire, Acquire),
385                     "rel"     => (Release, Monotonic),
386                     "acqrel"  => (AcquireRelease, Acquire),
387                     "failrelaxed" if is_cxchg =>
388                         (SequentiallyConsistent, Monotonic),
389                     "failacq" if is_cxchg =>
390                         (SequentiallyConsistent, Acquire),
391                     _ => ccx.sess().fatal("unknown ordering in atomic intrinsic")
392                 },
393                 4 => match (split[2], split[3]) {
394                     ("acq", "failrelaxed") if is_cxchg =>
395                         (Acquire, Monotonic),
396                     ("acqrel", "failrelaxed") if is_cxchg =>
397                         (AcquireRelease, Monotonic),
398                     _ => ccx.sess().fatal("unknown ordering in atomic intrinsic")
399                 },
400                 _ => ccx.sess().fatal("Atomic intrinsic not in correct format"),
401             };
402
403             let invalid_monomorphization = |sty| {
404                 span_invalid_monomorphization_error(tcx.sess, span,
405                     &format!("invalid monomorphization of `{}` intrinsic: \
406                               expected basic integer type, found `{}`", name, sty));
407             };
408
409             match split[1] {
410                 "cxchg" | "cxchgweak" => {
411                     let sty = &substs.type_at(0).sty;
412                     if int_type_width_signed(sty, ccx).is_some() {
413                         let weak = if split[1] == "cxchgweak" { llvm::True } else { llvm::False };
414                         let val = bcx.atomic_cmpxchg(llargs[0], llargs[1], llargs[2], order,
415                             failorder, weak);
416                         let result = bcx.extract_value(val, 0);
417                         let success = bcx.zext(bcx.extract_value(val, 1), Type::bool(bcx.ccx));
418                         bcx.store(result, bcx.struct_gep(llresult, 0), None);
419                         bcx.store(success, bcx.struct_gep(llresult, 1), None);
420                     } else {
421                         invalid_monomorphization(sty);
422                     }
423                     C_nil(ccx)
424                 }
425
426                 "load" => {
427                     let sty = &substs.type_at(0).sty;
428                     if int_type_width_signed(sty, ccx).is_some() {
429                         bcx.atomic_load(llargs[0], order)
430                     } else {
431                         invalid_monomorphization(sty);
432                         C_nil(ccx)
433                     }
434                 }
435
436                 "store" => {
437                     let sty = &substs.type_at(0).sty;
438                     if int_type_width_signed(sty, ccx).is_some() {
439                         bcx.atomic_store(llargs[1], llargs[0], order);
440                     } else {
441                         invalid_monomorphization(sty);
442                     }
443                     C_nil(ccx)
444                 }
445
446                 "fence" => {
447                     bcx.atomic_fence(order, llvm::SynchronizationScope::CrossThread);
448                     C_nil(ccx)
449                 }
450
451                 "singlethreadfence" => {
452                     bcx.atomic_fence(order, llvm::SynchronizationScope::SingleThread);
453                     C_nil(ccx)
454                 }
455
456                 // These are all AtomicRMW ops
457                 op => {
458                     let atom_op = match op {
459                         "xchg"  => llvm::AtomicXchg,
460                         "xadd"  => llvm::AtomicAdd,
461                         "xsub"  => llvm::AtomicSub,
462                         "and"   => llvm::AtomicAnd,
463                         "nand"  => llvm::AtomicNand,
464                         "or"    => llvm::AtomicOr,
465                         "xor"   => llvm::AtomicXor,
466                         "max"   => llvm::AtomicMax,
467                         "min"   => llvm::AtomicMin,
468                         "umax"  => llvm::AtomicUMax,
469                         "umin"  => llvm::AtomicUMin,
470                         _ => ccx.sess().fatal("unknown atomic operation")
471                     };
472
473                     let sty = &substs.type_at(0).sty;
474                     if int_type_width_signed(sty, ccx).is_some() {
475                         bcx.atomic_rmw(atom_op, llargs[0], llargs[1], order)
476                     } else {
477                         invalid_monomorphization(sty);
478                         C_nil(ccx)
479                     }
480                 }
481             }
482         }
483
484         _ => {
485             let intr = match Intrinsic::find(&name) {
486                 Some(intr) => intr,
487                 None => bug!("unknown intrinsic '{}'", name),
488             };
489             fn one<T>(x: Vec<T>) -> T {
490                 assert_eq!(x.len(), 1);
491                 x.into_iter().next().unwrap()
492             }
493             fn ty_to_type(ccx: &CrateContext, t: &intrinsics::Type,
494                           any_changes_needed: &mut bool) -> Vec<Type> {
495                 use intrinsics::Type::*;
496                 match *t {
497                     Void => vec![Type::void(ccx)],
498                     Integer(_signed, width, llvm_width) => {
499                         *any_changes_needed |= width != llvm_width;
500                         vec![Type::ix(ccx, llvm_width as u64)]
501                     }
502                     Float(x) => {
503                         match x {
504                             32 => vec![Type::f32(ccx)],
505                             64 => vec![Type::f64(ccx)],
506                             _ => bug!()
507                         }
508                     }
509                     Pointer(ref t, ref llvm_elem, _const) => {
510                         *any_changes_needed |= llvm_elem.is_some();
511
512                         let t = llvm_elem.as_ref().unwrap_or(t);
513                         let elem = one(ty_to_type(ccx, t, any_changes_needed));
514                         vec![elem.ptr_to()]
515                     }
516                     Vector(ref t, ref llvm_elem, length) => {
517                         *any_changes_needed |= llvm_elem.is_some();
518
519                         let t = llvm_elem.as_ref().unwrap_or(t);
520                         let elem = one(ty_to_type(ccx, t, any_changes_needed));
521                         vec![Type::vector(&elem, length as u64)]
522                     }
523                     Aggregate(false, ref contents) => {
524                         let elems = contents.iter()
525                                             .map(|t| one(ty_to_type(ccx, t, any_changes_needed)))
526                                             .collect::<Vec<_>>();
527                         vec![Type::struct_(ccx, &elems, false)]
528                     }
529                     Aggregate(true, ref contents) => {
530                         *any_changes_needed = true;
531                         contents.iter()
532                                 .flat_map(|t| ty_to_type(ccx, t, any_changes_needed))
533                                 .collect()
534                     }
535                 }
536             }
537
538             // This allows an argument list like `foo, (bar, baz),
539             // qux` to be converted into `foo, bar, baz, qux`, integer
540             // arguments to be truncated as needed and pointers to be
541             // cast.
542             fn modify_as_needed<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
543                                           t: &intrinsics::Type,
544                                           arg_type: Ty<'tcx>,
545                                           llarg: ValueRef)
546                                           -> Vec<ValueRef>
547             {
548                 match *t {
549                     intrinsics::Type::Aggregate(true, ref contents) => {
550                         // We found a tuple that needs squishing! So
551                         // run over the tuple and load each field.
552                         //
553                         // This assumes the type is "simple", i.e. no
554                         // destructors, and the contents are SIMD
555                         // etc.
556                         assert!(!bcx.ccx.shared().type_needs_drop(arg_type));
557                         let arg = LvalueRef::new_sized_ty(llarg, arg_type, Alignment::AbiAligned);
558                         (0..contents.len()).map(|i| {
559                             let (ptr, align) = arg.trans_field_ptr(bcx, i);
560                             bcx.load(ptr, align.to_align())
561                         }).collect()
562                     }
563                     intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
564                         let llvm_elem = one(ty_to_type(bcx.ccx, llvm_elem, &mut false));
565                         vec![bcx.pointercast(llarg, llvm_elem.ptr_to())]
566                     }
567                     intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
568                         let llvm_elem = one(ty_to_type(bcx.ccx, llvm_elem, &mut false));
569                         vec![bcx.bitcast(llarg, Type::vector(&llvm_elem, length as u64))]
570                     }
571                     intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
572                         // the LLVM intrinsic uses a smaller integer
573                         // size than the C intrinsic's signature, so
574                         // we have to trim it down here.
575                         vec![bcx.trunc(llarg, Type::ix(bcx.ccx, llvm_width as u64))]
576                     }
577                     _ => vec![llarg],
578                 }
579             }
580
581
582             let mut any_changes_needed = false;
583             let inputs = intr.inputs.iter()
584                                     .flat_map(|t| ty_to_type(ccx, t, &mut any_changes_needed))
585                                     .collect::<Vec<_>>();
586
587             let mut out_changes = false;
588             let outputs = one(ty_to_type(ccx, &intr.output, &mut out_changes));
589             // outputting a flattened aggregate is nonsense
590             assert!(!out_changes);
591
592             let llargs = if !any_changes_needed {
593                 // no aggregates to flatten, so no change needed
594                 llargs.to_vec()
595             } else {
596                 // there are some aggregates that need to be flattened
597                 // in the LLVM call, so we need to run over the types
598                 // again to find them and extract the arguments
599                 intr.inputs.iter()
600                            .zip(llargs)
601                            .zip(arg_tys)
602                            .flat_map(|((t, llarg), ty)| modify_as_needed(bcx, t, ty, *llarg))
603                            .collect()
604             };
605             assert_eq!(inputs.len(), llargs.len());
606
607             let val = match intr.definition {
608                 intrinsics::IntrinsicDef::Named(name) => {
609                     let f = declare::declare_cfn(ccx,
610                                                  name,
611                                                  Type::func(&inputs, &outputs));
612                     bcx.call(f, &llargs, None)
613                 }
614             };
615
616             match *intr.output {
617                 intrinsics::Type::Aggregate(flatten, ref elems) => {
618                     // the output is a tuple so we need to munge it properly
619                     assert!(!flatten);
620
621                     for i in 0..elems.len() {
622                         let val = bcx.extract_value(val, i);
623                         let lval = LvalueRef::new_sized_ty(llresult, ret_ty,
624                                                            Alignment::AbiAligned);
625                         let (dest, align) = lval.trans_field_ptr(bcx, i);
626                         bcx.store(val, dest, align.to_align());
627                     }
628                     C_nil(ccx)
629                 }
630                 _ => val,
631             }
632         }
633     };
634
635     if val_ty(llval) != Type::void(ccx) && machine::llsize_of_alloc(ccx, val_ty(llval)) != 0 {
636         if let Some(ty) = fn_ty.ret.cast {
637             let ptr = bcx.pointercast(llresult, ty.ptr_to());
638             bcx.store(llval, ptr, Some(ccx.align_of(ret_ty)));
639         } else {
640             store_ty(bcx, llval, llresult, Alignment::AbiAligned, ret_ty);
641         }
642     }
643 }
644
645 fn copy_intrinsic<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
646                             allow_overlap: bool,
647                             volatile: bool,
648                             tp_ty: Ty<'tcx>,
649                             dst: ValueRef,
650                             src: ValueRef,
651                             count: ValueRef)
652                             -> ValueRef {
653     let ccx = bcx.ccx;
654     let lltp_ty = type_of::type_of(ccx, tp_ty);
655     let align = C_i32(ccx, ccx.align_of(tp_ty) as i32);
656     let size = machine::llsize_of(ccx, lltp_ty);
657     let int_size = machine::llbitsize_of_real(ccx, ccx.int_type());
658
659     let operation = if allow_overlap {
660         "memmove"
661     } else {
662         "memcpy"
663     };
664
665     let name = format!("llvm.{}.p0i8.p0i8.i{}", operation, int_size);
666
667     let dst_ptr = bcx.pointercast(dst, Type::i8p(ccx));
668     let src_ptr = bcx.pointercast(src, Type::i8p(ccx));
669     let llfn = ccx.get_intrinsic(&name);
670
671     bcx.call(llfn,
672         &[dst_ptr,
673         src_ptr,
674         bcx.mul(size, count),
675         align,
676         C_bool(ccx, volatile)],
677         None)
678 }
679
680 fn memset_intrinsic<'a, 'tcx>(
681     bcx: &Builder<'a, 'tcx>,
682     volatile: bool,
683     ty: Ty<'tcx>,
684     dst: ValueRef,
685     val: ValueRef,
686     count: ValueRef
687 ) -> ValueRef {
688     let ccx = bcx.ccx;
689     let align = C_i32(ccx, ccx.align_of(ty) as i32);
690     let lltp_ty = type_of::type_of(ccx, ty);
691     let size = machine::llsize_of(ccx, lltp_ty);
692     let dst = bcx.pointercast(dst, Type::i8p(ccx));
693     call_memset(bcx, dst, val, bcx.mul(size, count), align, volatile)
694 }
695
696 fn try_intrinsic<'a, 'tcx>(
697     bcx: &Builder<'a, 'tcx>,
698     ccx: &CrateContext,
699     func: ValueRef,
700     data: ValueRef,
701     local_ptr: ValueRef,
702     dest: ValueRef,
703 ) {
704     if bcx.sess().no_landing_pads() {
705         bcx.call(func, &[data], None);
706         bcx.store(C_null(Type::i8p(&bcx.ccx)), dest, None);
707     } else if wants_msvc_seh(bcx.sess()) {
708         trans_msvc_try(bcx, ccx, func, data, local_ptr, dest);
709     } else {
710         trans_gnu_try(bcx, ccx, func, data, local_ptr, dest);
711     }
712 }
713
714 // MSVC's definition of the `rust_try` function.
715 //
716 // This implementation uses the new exception handling instructions in LLVM
717 // which have support in LLVM for SEH on MSVC targets. Although these
718 // instructions are meant to work for all targets, as of the time of this
719 // writing, however, LLVM does not recommend the usage of these new instructions
720 // as the old ones are still more optimized.
721 fn trans_msvc_try<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
722                             ccx: &CrateContext,
723                             func: ValueRef,
724                             data: ValueRef,
725                             local_ptr: ValueRef,
726                             dest: ValueRef) {
727     let llfn = get_rust_try_fn(ccx, &mut |bcx| {
728         let ccx = bcx.ccx;
729
730         bcx.set_personality_fn(bcx.ccx.eh_personality());
731
732         let normal = bcx.build_sibling_block("normal");
733         let catchswitch = bcx.build_sibling_block("catchswitch");
734         let catchpad = bcx.build_sibling_block("catchpad");
735         let caught = bcx.build_sibling_block("caught");
736
737         let func = llvm::get_param(bcx.llfn(), 0);
738         let data = llvm::get_param(bcx.llfn(), 1);
739         let local_ptr = llvm::get_param(bcx.llfn(), 2);
740
741         // We're generating an IR snippet that looks like:
742         //
743         //   declare i32 @rust_try(%func, %data, %ptr) {
744         //      %slot = alloca i64*
745         //      invoke %func(%data) to label %normal unwind label %catchswitch
746         //
747         //   normal:
748         //      ret i32 0
749         //
750         //   catchswitch:
751         //      %cs = catchswitch within none [%catchpad] unwind to caller
752         //
753         //   catchpad:
754         //      %tok = catchpad within %cs [%type_descriptor, 0, %slot]
755         //      %ptr[0] = %slot[0]
756         //      %ptr[1] = %slot[1]
757         //      catchret from %tok to label %caught
758         //
759         //   caught:
760         //      ret i32 1
761         //   }
762         //
763         // This structure follows the basic usage of throw/try/catch in LLVM.
764         // For example, compile this C++ snippet to see what LLVM generates:
765         //
766         //      #include <stdint.h>
767         //
768         //      int bar(void (*foo)(void), uint64_t *ret) {
769         //          try {
770         //              foo();
771         //              return 0;
772         //          } catch(uint64_t a[2]) {
773         //              ret[0] = a[0];
774         //              ret[1] = a[1];
775         //              return 1;
776         //          }
777         //      }
778         //
779         // More information can be found in libstd's seh.rs implementation.
780         let i64p = Type::i64(ccx).ptr_to();
781         let slot = bcx.alloca(i64p, "slot", None);
782         bcx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(),
783             None);
784
785         normal.ret(C_i32(ccx, 0));
786
787         let cs = catchswitch.catch_switch(None, None, 1);
788         catchswitch.add_handler(cs, catchpad.llbb());
789
790         let tcx = ccx.tcx();
791         let tydesc = match tcx.lang_items.msvc_try_filter() {
792             Some(did) => ::consts::get_static(ccx, did),
793             None => bug!("msvc_try_filter not defined"),
794         };
795         let tok = catchpad.catch_pad(cs, &[tydesc, C_i32(ccx, 0), slot]);
796         let addr = catchpad.load(slot, None);
797         let arg1 = catchpad.load(addr, None);
798         let val1 = C_i32(ccx, 1);
799         let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), None);
800         let local_ptr = catchpad.bitcast(local_ptr, i64p);
801         catchpad.store(arg1, local_ptr, None);
802         catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), None);
803         catchpad.catch_ret(tok, caught.llbb());
804
805         caught.ret(C_i32(ccx, 1));
806     });
807
808     // Note that no invoke is used here because by definition this function
809     // can't panic (that's what it's catching).
810     let ret = bcx.call(llfn, &[func, data, local_ptr], None);
811     bcx.store(ret, dest, None);
812 }
813
814 // Definition of the standard "try" function for Rust using the GNU-like model
815 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
816 // instructions).
817 //
818 // This translation is a little surprising because we always call a shim
819 // function instead of inlining the call to `invoke` manually here. This is done
820 // because in LLVM we're only allowed to have one personality per function
821 // definition. The call to the `try` intrinsic is being inlined into the
822 // function calling it, and that function may already have other personality
823 // functions in play. By calling a shim we're guaranteed that our shim will have
824 // the right personality function.
825 fn trans_gnu_try<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
826                            ccx: &CrateContext,
827                            func: ValueRef,
828                            data: ValueRef,
829                            local_ptr: ValueRef,
830                            dest: ValueRef) {
831     let llfn = get_rust_try_fn(ccx, &mut |bcx| {
832         let ccx = bcx.ccx;
833
834         // Translates the shims described above:
835         //
836         //   bcx:
837         //      invoke %func(%args...) normal %normal unwind %catch
838         //
839         //   normal:
840         //      ret 0
841         //
842         //   catch:
843         //      (ptr, _) = landingpad
844         //      store ptr, %local_ptr
845         //      ret 1
846         //
847         // Note that the `local_ptr` data passed into the `try` intrinsic is
848         // expected to be `*mut *mut u8` for this to actually work, but that's
849         // managed by the standard library.
850
851         let then = bcx.build_sibling_block("then");
852         let catch = bcx.build_sibling_block("catch");
853
854         let func = llvm::get_param(bcx.llfn(), 0);
855         let data = llvm::get_param(bcx.llfn(), 1);
856         let local_ptr = llvm::get_param(bcx.llfn(), 2);
857         bcx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
858         then.ret(C_i32(ccx, 0));
859
860         // Type indicator for the exception being thrown.
861         //
862         // The first value in this tuple is a pointer to the exception object
863         // being thrown.  The second value is a "selector" indicating which of
864         // the landing pad clauses the exception's type had been matched to.
865         // rust_try ignores the selector.
866         let lpad_ty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)],
867                                     false);
868         let vals = catch.landing_pad(lpad_ty, bcx.ccx.eh_personality(), 1, catch.llfn());
869         catch.add_clause(vals, C_null(Type::i8p(ccx)));
870         let ptr = catch.extract_value(vals, 0);
871         catch.store(ptr, catch.bitcast(local_ptr, Type::i8p(ccx).ptr_to()), None);
872         catch.ret(C_i32(ccx, 1));
873     });
874
875     // Note that no invoke is used here because by definition this function
876     // can't panic (that's what it's catching).
877     let ret = bcx.call(llfn, &[func, data, local_ptr], None);
878     bcx.store(ret, dest, None);
879 }
880
881 // Helper function to give a Block to a closure to translate a shim function.
882 // This is currently primarily used for the `try` intrinsic functions above.
883 fn gen_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
884                     name: &str,
885                     inputs: Vec<Ty<'tcx>>,
886                     output: Ty<'tcx>,
887                     trans: &mut for<'b> FnMut(Builder<'b, 'tcx>))
888                     -> ValueRef {
889     let rust_fn_ty = ccx.tcx().mk_fn_ptr(ty::Binder(ccx.tcx().mk_fn_sig(
890         inputs.into_iter(),
891         output,
892         false,
893         hir::Unsafety::Unsafe,
894         Abi::Rust
895     )));
896     let llfn = declare::define_internal_fn(ccx, name, rust_fn_ty);
897     let bcx = Builder::new_block(ccx, llfn, "entry-block");
898     trans(bcx);
899     llfn
900 }
901
902 // Helper function used to get a handle to the `__rust_try` function used to
903 // catch exceptions.
904 //
905 // This function is only generated once and is then cached.
906 fn get_rust_try_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
907                              trans: &mut for<'b> FnMut(Builder<'b, 'tcx>))
908                              -> ValueRef {
909     if let Some(llfn) = ccx.rust_try_fn().get() {
910         return llfn;
911     }
912
913     // Define the type up front for the signature of the rust_try function.
914     let tcx = ccx.tcx();
915     let i8p = tcx.mk_mut_ptr(tcx.types.i8);
916     let fn_ty = tcx.mk_fn_ptr(ty::Binder(tcx.mk_fn_sig(
917         iter::once(i8p),
918         tcx.mk_nil(),
919         false,
920         hir::Unsafety::Unsafe,
921         Abi::Rust
922     )));
923     let output = tcx.types.i32;
924     let rust_try = gen_fn(ccx, "__rust_try", vec![fn_ty, i8p, i8p], output, trans);
925     ccx.rust_try_fn().set(Some(rust_try));
926     return rust_try
927 }
928
929 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
930     span_err!(a, b, E0511, "{}", c);
931 }
932
933 fn generic_simd_intrinsic<'a, 'tcx>(
934     bcx: &Builder<'a, 'tcx>,
935     name: &str,
936     callee_ty: Ty<'tcx>,
937     llargs: &[ValueRef],
938     ret_ty: Ty<'tcx>,
939     llret_ty: Type,
940     span: Span
941 ) -> ValueRef {
942     // macros for error handling:
943     macro_rules! emit_error {
944         ($msg: tt) => {
945             emit_error!($msg, )
946         };
947         ($msg: tt, $($fmt: tt)*) => {
948             span_invalid_monomorphization_error(
949                 bcx.sess(), span,
950                 &format!(concat!("invalid monomorphization of `{}` intrinsic: ",
951                                  $msg),
952                          name, $($fmt)*));
953         }
954     }
955     macro_rules! require {
956         ($cond: expr, $($fmt: tt)*) => {
957             if !$cond {
958                 emit_error!($($fmt)*);
959                 return C_nil(bcx.ccx)
960             }
961         }
962     }
963     macro_rules! require_simd {
964         ($ty: expr, $position: expr) => {
965             require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
966         }
967     }
968
969
970
971     let tcx = bcx.tcx();
972     let sig = tcx.erase_late_bound_regions_and_normalize(&callee_ty.fn_sig());
973     let arg_tys = sig.inputs();
974
975     // every intrinsic takes a SIMD vector as its first argument
976     require_simd!(arg_tys[0], "input");
977     let in_ty = arg_tys[0];
978     let in_elem = arg_tys[0].simd_type(tcx);
979     let in_len = arg_tys[0].simd_size(tcx);
980
981     let comparison = match name {
982         "simd_eq" => Some(hir::BiEq),
983         "simd_ne" => Some(hir::BiNe),
984         "simd_lt" => Some(hir::BiLt),
985         "simd_le" => Some(hir::BiLe),
986         "simd_gt" => Some(hir::BiGt),
987         "simd_ge" => Some(hir::BiGe),
988         _ => None
989     };
990
991     if let Some(cmp_op) = comparison {
992         require_simd!(ret_ty, "return");
993
994         let out_len = ret_ty.simd_size(tcx);
995         require!(in_len == out_len,
996                  "expected return type with length {} (same as input type `{}`), \
997                   found `{}` with length {}",
998                  in_len, in_ty,
999                  ret_ty, out_len);
1000         require!(llret_ty.element_type().kind() == llvm::Integer,
1001                  "expected return type with integer elements, found `{}` with non-integer `{}`",
1002                  ret_ty,
1003                  ret_ty.simd_type(tcx));
1004
1005         return compare_simd_types(bcx,
1006                                   llargs[0],
1007                                   llargs[1],
1008                                   in_elem,
1009                                   llret_ty,
1010                                   cmp_op)
1011     }
1012
1013     if name.starts_with("simd_shuffle") {
1014         let n: usize = match name["simd_shuffle".len()..].parse() {
1015             Ok(n) => n,
1016             Err(_) => span_bug!(span,
1017                                 "bad `simd_shuffle` instruction only caught in trans?")
1018         };
1019
1020         require_simd!(ret_ty, "return");
1021
1022         let out_len = ret_ty.simd_size(tcx);
1023         require!(out_len == n,
1024                  "expected return type of length {}, found `{}` with length {}",
1025                  n, ret_ty, out_len);
1026         require!(in_elem == ret_ty.simd_type(tcx),
1027                  "expected return element type `{}` (element of input `{}`), \
1028                   found `{}` with element type `{}`",
1029                  in_elem, in_ty,
1030                  ret_ty, ret_ty.simd_type(tcx));
1031
1032         let total_len = in_len as u128 * 2;
1033
1034         let vector = llargs[2];
1035
1036         let indices: Option<Vec<_>> = (0..n)
1037             .map(|i| {
1038                 let arg_idx = i;
1039                 let val = const_get_elt(vector, &[i as libc::c_uint]);
1040                 match const_to_opt_u128(val, true) {
1041                     None => {
1042                         emit_error!("shuffle index #{} is not a constant", arg_idx);
1043                         None
1044                     }
1045                     Some(idx) if idx >= total_len => {
1046                         emit_error!("shuffle index #{} is out of bounds (limit {})",
1047                                     arg_idx, total_len);
1048                         None
1049                     }
1050                     Some(idx) => Some(C_i32(bcx.ccx, idx as i32)),
1051                 }
1052             })
1053             .collect();
1054         let indices = match indices {
1055             Some(i) => i,
1056             None => return C_null(llret_ty)
1057         };
1058
1059         return bcx.shuffle_vector(llargs[0], llargs[1], C_vector(&indices))
1060     }
1061
1062     if name == "simd_insert" {
1063         require!(in_elem == arg_tys[2],
1064                  "expected inserted type `{}` (element of input `{}`), found `{}`",
1065                  in_elem, in_ty, arg_tys[2]);
1066         return bcx.insert_element(llargs[0], llargs[2], llargs[1])
1067     }
1068     if name == "simd_extract" {
1069         require!(ret_ty == in_elem,
1070                  "expected return type `{}` (element of input `{}`), found `{}`",
1071                  in_elem, in_ty, ret_ty);
1072         return bcx.extract_element(llargs[0], llargs[1])
1073     }
1074
1075     if name == "simd_cast" {
1076         require_simd!(ret_ty, "return");
1077         let out_len = ret_ty.simd_size(tcx);
1078         require!(in_len == out_len,
1079                  "expected return type with length {} (same as input type `{}`), \
1080                   found `{}` with length {}",
1081                  in_len, in_ty,
1082                  ret_ty, out_len);
1083         // casting cares about nominal type, not just structural type
1084         let out_elem = ret_ty.simd_type(tcx);
1085
1086         if in_elem == out_elem { return llargs[0]; }
1087
1088         enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1089
1090         let (in_style, in_width) = match in_elem.sty {
1091             // vectors of pointer-sized integers should've been
1092             // disallowed before here, so this unwrap is safe.
1093             ty::TyInt(i) => (Style::Int(true), i.bit_width().unwrap()),
1094             ty::TyUint(u) => (Style::Int(false), u.bit_width().unwrap()),
1095             ty::TyFloat(f) => (Style::Float, f.bit_width()),
1096             _ => (Style::Unsupported, 0)
1097         };
1098         let (out_style, out_width) = match out_elem.sty {
1099             ty::TyInt(i) => (Style::Int(true), i.bit_width().unwrap()),
1100             ty::TyUint(u) => (Style::Int(false), u.bit_width().unwrap()),
1101             ty::TyFloat(f) => (Style::Float, f.bit_width()),
1102             _ => (Style::Unsupported, 0)
1103         };
1104
1105         match (in_style, out_style) {
1106             (Style::Int(in_is_signed), Style::Int(_)) => {
1107                 return match in_width.cmp(&out_width) {
1108                     Ordering::Greater => bcx.trunc(llargs[0], llret_ty),
1109                     Ordering::Equal => llargs[0],
1110                     Ordering::Less => if in_is_signed {
1111                         bcx.sext(llargs[0], llret_ty)
1112                     } else {
1113                         bcx.zext(llargs[0], llret_ty)
1114                     }
1115                 }
1116             }
1117             (Style::Int(in_is_signed), Style::Float) => {
1118                 return if in_is_signed {
1119                     bcx.sitofp(llargs[0], llret_ty)
1120                 } else {
1121                     bcx.uitofp(llargs[0], llret_ty)
1122                 }
1123             }
1124             (Style::Float, Style::Int(out_is_signed)) => {
1125                 return if out_is_signed {
1126                     bcx.fptosi(llargs[0], llret_ty)
1127                 } else {
1128                     bcx.fptoui(llargs[0], llret_ty)
1129                 }
1130             }
1131             (Style::Float, Style::Float) => {
1132                 return match in_width.cmp(&out_width) {
1133                     Ordering::Greater => bcx.fptrunc(llargs[0], llret_ty),
1134                     Ordering::Equal => llargs[0],
1135                     Ordering::Less => bcx.fpext(llargs[0], llret_ty)
1136                 }
1137             }
1138             _ => {/* Unsupported. Fallthrough. */}
1139         }
1140         require!(false,
1141                  "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1142                  in_ty, in_elem,
1143                  ret_ty, out_elem);
1144     }
1145     macro_rules! arith {
1146         ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1147             $(
1148                 if name == stringify!($name) {
1149                     match in_elem.sty {
1150                         $(
1151                             $(ty::$p(_))|* => {
1152                                 return bcx.$call(llargs[0], llargs[1])
1153                             }
1154                             )*
1155                         _ => {},
1156                     }
1157                     require!(false,
1158                              "unsupported operation on `{}` with element `{}`",
1159                              in_ty,
1160                              in_elem)
1161                 })*
1162         }
1163     }
1164     arith! {
1165         simd_add: TyUint, TyInt => add, TyFloat => fadd;
1166         simd_sub: TyUint, TyInt => sub, TyFloat => fsub;
1167         simd_mul: TyUint, TyInt => mul, TyFloat => fmul;
1168         simd_div: TyFloat => fdiv;
1169         simd_shl: TyUint, TyInt => shl;
1170         simd_shr: TyUint => lshr, TyInt => ashr;
1171         simd_and: TyUint, TyInt => and;
1172         simd_or: TyUint, TyInt => or;
1173         simd_xor: TyUint, TyInt => xor;
1174     }
1175     span_bug!(span, "unknown SIMD intrinsic");
1176 }
1177
1178 // Returns the width of an int TypeVariant, and if it's signed or not
1179 // Returns None if the type is not an integer
1180 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1181 // stuffs.
1182 fn int_type_width_signed<'tcx>(sty: &ty::TypeVariants<'tcx>, ccx: &CrateContext)
1183         -> Option<(u64, bool)> {
1184     use rustc::ty::{TyInt, TyUint};
1185     match *sty {
1186         TyInt(t) => Some((match t {
1187             ast::IntTy::Is => {
1188                 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
1189                     "16" => 16,
1190                     "32" => 32,
1191                     "64" => 64,
1192                     tws => bug!("Unsupported target word size for isize: {}", tws),
1193                 }
1194             },
1195             ast::IntTy::I8 => 8,
1196             ast::IntTy::I16 => 16,
1197             ast::IntTy::I32 => 32,
1198             ast::IntTy::I64 => 64,
1199             ast::IntTy::I128 => 128,
1200         }, true)),
1201         TyUint(t) => Some((match t {
1202             ast::UintTy::Us => {
1203                 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
1204                     "16" => 16,
1205                     "32" => 32,
1206                     "64" => 64,
1207                     tws => bug!("Unsupported target word size for usize: {}", tws),
1208                 }
1209             },
1210             ast::UintTy::U8 => 8,
1211             ast::UintTy::U16 => 16,
1212             ast::UintTy::U32 => 32,
1213             ast::UintTy::U64 => 64,
1214             ast::UintTy::U128 => 128,
1215         }, false)),
1216         _ => None,
1217     }
1218 }
1219
1220 // Returns the width of a float TypeVariant
1221 // Returns None if the type is not a float
1222 fn float_type_width<'tcx>(sty: &ty::TypeVariants<'tcx>)
1223         -> Option<u64> {
1224     use rustc::ty::TyFloat;
1225     match *sty {
1226         TyFloat(t) => Some(match t {
1227             ast::FloatTy::F32 => 32,
1228             ast::FloatTy::F64 => 64,
1229         }),
1230         _ => None,
1231     }
1232 }