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