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