]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/intrinsic.rs
Generalized SynchronisationScope for BuilderMethods
[rust.git] / src / librustc_codegen_llvm / 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 attributes;
14 use intrinsics::{self, Intrinsic};
15 use llvm::{self, TypeKind};
16 use llvm_util;
17 use abi::{Abi, FnType, LlvmType, PassMode};
18 use mir::place::PlaceRef;
19 use mir::operand::{OperandRef, OperandValue};
20 use base::*;
21 use common::*;
22 use declare;
23 use glue;
24 use type_::Type;
25 use type_of::LayoutLlvmExt;
26 use rustc::ty::{self, Ty};
27 use rustc::ty::layout::LayoutOf;
28 use rustc::hir;
29 use syntax::ast;
30 use syntax::symbol::Symbol;
31 use builder::Builder;
32 use value::Value;
33
34 use traits::{BuilderMethods, AtomicRmwBinOp, SynchronizationScope};
35
36 use rustc::session::Session;
37 use syntax_pos::Span;
38
39 use std::cmp::Ordering;
40 use std::iter;
41
42 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
43     let llvm_name = match name {
44         "sqrtf32" => "llvm.sqrt.f32",
45         "sqrtf64" => "llvm.sqrt.f64",
46         "powif32" => "llvm.powi.f32",
47         "powif64" => "llvm.powi.f64",
48         "sinf32" => "llvm.sin.f32",
49         "sinf64" => "llvm.sin.f64",
50         "cosf32" => "llvm.cos.f32",
51         "cosf64" => "llvm.cos.f64",
52         "powf32" => "llvm.pow.f32",
53         "powf64" => "llvm.pow.f64",
54         "expf32" => "llvm.exp.f32",
55         "expf64" => "llvm.exp.f64",
56         "exp2f32" => "llvm.exp2.f32",
57         "exp2f64" => "llvm.exp2.f64",
58         "logf32" => "llvm.log.f32",
59         "logf64" => "llvm.log.f64",
60         "log10f32" => "llvm.log10.f32",
61         "log10f64" => "llvm.log10.f64",
62         "log2f32" => "llvm.log2.f32",
63         "log2f64" => "llvm.log2.f64",
64         "fmaf32" => "llvm.fma.f32",
65         "fmaf64" => "llvm.fma.f64",
66         "fabsf32" => "llvm.fabs.f32",
67         "fabsf64" => "llvm.fabs.f64",
68         "copysignf32" => "llvm.copysign.f32",
69         "copysignf64" => "llvm.copysign.f64",
70         "floorf32" => "llvm.floor.f32",
71         "floorf64" => "llvm.floor.f64",
72         "ceilf32" => "llvm.ceil.f32",
73         "ceilf64" => "llvm.ceil.f64",
74         "truncf32" => "llvm.trunc.f32",
75         "truncf64" => "llvm.trunc.f64",
76         "rintf32" => "llvm.rint.f32",
77         "rintf64" => "llvm.rint.f64",
78         "nearbyintf32" => "llvm.nearbyint.f32",
79         "nearbyintf64" => "llvm.nearbyint.f64",
80         "roundf32" => "llvm.round.f32",
81         "roundf64" => "llvm.round.f64",
82         "assume" => "llvm.assume",
83         "abort" => "llvm.trap",
84         _ => return None
85     };
86     Some(cx.get_intrinsic(&llvm_name))
87 }
88
89 /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs,
90 /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics,
91 /// add them to librustc_codegen_llvm/context.rs
92 pub fn codegen_intrinsic_call(
93     bx: &Builder<'a, 'll, 'tcx>,
94     callee_ty: Ty<'tcx>,
95     fn_ty: &FnType<'tcx, Ty<'tcx>>,
96     args: &[OperandRef<'tcx, &'ll Value>],
97     llresult: &'ll Value,
98     span: Span,
99 ) {
100     let cx = bx.cx;
101     let tcx = cx.tcx;
102
103     let (def_id, substs) = match callee_ty.sty {
104         ty::FnDef(def_id, substs) => (def_id, substs),
105         _ => bug!("expected fn item type, found {}", callee_ty)
106     };
107
108     let sig = callee_ty.fn_sig(tcx);
109     let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
110     let arg_tys = sig.inputs();
111     let ret_ty = sig.output();
112     let name = &*tcx.item_name(def_id).as_str();
113
114     let llret_ty = cx.layout_of(ret_ty).llvm_type(cx);
115     let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align);
116
117     let simple = get_simple_intrinsic(cx, name);
118     let llval = match name {
119         _ if simple.is_some() => {
120             bx.call(simple.unwrap(),
121                     &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
122                     None)
123         }
124         "unreachable" => {
125             return;
126         },
127         "likely" => {
128             let expect = cx.get_intrinsic(&("llvm.expect.i1"));
129             bx.call(expect, &[args[0].immediate(), C_bool(cx, true)], None)
130         }
131         "unlikely" => {
132             let expect = cx.get_intrinsic(&("llvm.expect.i1"));
133             bx.call(expect, &[args[0].immediate(), C_bool(cx, false)], None)
134         }
135         "try" => {
136             try_intrinsic(bx, cx,
137                           args[0].immediate(),
138                           args[1].immediate(),
139                           args[2].immediate(),
140                           llresult);
141             return;
142         }
143         "breakpoint" => {
144             let llfn = cx.get_intrinsic(&("llvm.debugtrap"));
145             bx.call(llfn, &[], None)
146         }
147         "size_of" => {
148             let tp_ty = substs.type_at(0);
149             C_usize(cx, cx.size_of(tp_ty).bytes())
150         }
151         "size_of_val" => {
152             let tp_ty = substs.type_at(0);
153             if let OperandValue::Pair(_, meta) = args[0].val {
154                 let (llsize, _) =
155                     glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
156                 llsize
157             } else {
158                 C_usize(cx, cx.size_of(tp_ty).bytes())
159             }
160         }
161         "min_align_of" => {
162             let tp_ty = substs.type_at(0);
163             C_usize(cx, cx.align_of(tp_ty).abi())
164         }
165         "min_align_of_val" => {
166             let tp_ty = substs.type_at(0);
167             if let OperandValue::Pair(_, meta) = args[0].val {
168                 let (_, llalign) =
169                     glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
170                 llalign
171             } else {
172                 C_usize(cx, cx.align_of(tp_ty).abi())
173             }
174         }
175         "pref_align_of" => {
176             let tp_ty = substs.type_at(0);
177             C_usize(cx, cx.align_of(tp_ty).pref())
178         }
179         "type_name" => {
180             let tp_ty = substs.type_at(0);
181             let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
182             C_str_slice(cx, ty_name)
183         }
184         "type_id" => {
185             C_u64(cx, cx.tcx.type_id_hash(substs.type_at(0)))
186         }
187         "init" => {
188             let ty = substs.type_at(0);
189             if !cx.layout_of(ty).is_zst() {
190                 // Just zero out the stack slot.
191                 // If we store a zero constant, LLVM will drown in vreg allocation for large data
192                 // structures, and the generated code will be awful. (A telltale sign of this is
193                 // large quantities of `mov [byte ptr foo],0` in the generated code.)
194                 memset_intrinsic(bx, false, ty, llresult, C_u8(cx, 0), C_usize(cx, 1));
195             }
196             return;
197         }
198         // Effectively no-ops
199         "uninit" | "forget" => {
200             return;
201         }
202         "needs_drop" => {
203             let tp_ty = substs.type_at(0);
204
205             C_bool(cx, bx.cx.type_needs_drop(tp_ty))
206         }
207         "offset" => {
208             let ptr = args[0].immediate();
209             let offset = args[1].immediate();
210             bx.inbounds_gep(ptr, &[offset])
211         }
212         "arith_offset" => {
213             let ptr = args[0].immediate();
214             let offset = args[1].immediate();
215             bx.gep(ptr, &[offset])
216         }
217
218         "copy_nonoverlapping" => {
219             copy_intrinsic(bx, false, false, substs.type_at(0),
220                            args[1].immediate(), args[0].immediate(), args[2].immediate())
221         }
222         "copy" => {
223             copy_intrinsic(bx, true, false, substs.type_at(0),
224                            args[1].immediate(), args[0].immediate(), args[2].immediate())
225         }
226         "write_bytes" => {
227             memset_intrinsic(bx, false, substs.type_at(0),
228                              args[0].immediate(), args[1].immediate(), args[2].immediate())
229         }
230
231         "volatile_copy_nonoverlapping_memory" => {
232             copy_intrinsic(bx, false, true, substs.type_at(0),
233                            args[0].immediate(), args[1].immediate(), args[2].immediate())
234         }
235         "volatile_copy_memory" => {
236             copy_intrinsic(bx, true, true, substs.type_at(0),
237                            args[0].immediate(), args[1].immediate(), args[2].immediate())
238         }
239         "volatile_set_memory" => {
240             memset_intrinsic(bx, true, substs.type_at(0),
241                              args[0].immediate(), args[1].immediate(), args[2].immediate())
242         }
243         "volatile_load" | "unaligned_volatile_load" => {
244             let tp_ty = substs.type_at(0);
245             let mut ptr = args[0].immediate();
246             if let PassMode::Cast(ty) = fn_ty.ret.mode {
247                 ptr = bx.pointercast(ptr, ty.llvm_type(cx).ptr_to());
248             }
249             let load = bx.volatile_load(ptr);
250             let align = if name == "unaligned_volatile_load" {
251                 1
252             } else {
253                 cx.align_of(tp_ty).abi() as u32
254             };
255             unsafe {
256                 llvm::LLVMSetAlignment(load, align);
257             }
258             to_immediate(bx, load, cx.layout_of(tp_ty))
259         },
260         "volatile_store" => {
261             let dst = args[0].deref(bx.cx);
262             args[1].val.volatile_store(bx, dst);
263             return;
264         },
265         "unaligned_volatile_store" => {
266             let dst = args[0].deref(bx.cx);
267             args[1].val.unaligned_volatile_store(bx, dst);
268             return;
269         },
270         "prefetch_read_data" | "prefetch_write_data" |
271         "prefetch_read_instruction" | "prefetch_write_instruction" => {
272             let expect = cx.get_intrinsic(&("llvm.prefetch"));
273             let (rw, cache_type) = match name {
274                 "prefetch_read_data" => (0, 1),
275                 "prefetch_write_data" => (1, 1),
276                 "prefetch_read_instruction" => (0, 0),
277                 "prefetch_write_instruction" => (1, 0),
278                 _ => bug!()
279             };
280             bx.call(expect, &[
281                 args[0].immediate(),
282                 C_i32(cx, rw),
283                 args[1].immediate(),
284                 C_i32(cx, cache_type)
285             ], None)
286         },
287         "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
288         "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
289         "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
290         "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" |
291         "rotate_left" | "rotate_right" => {
292             let ty = arg_tys[0];
293             match int_type_width_signed(ty, cx) {
294                 Some((width, signed)) =>
295                     match name {
296                         "ctlz" | "cttz" => {
297                             let y = C_bool(bx.cx, false);
298                             let llfn = cx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
299                             bx.call(llfn, &[args[0].immediate(), y], None)
300                         }
301                         "ctlz_nonzero" | "cttz_nonzero" => {
302                             let y = C_bool(bx.cx, true);
303                             let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
304                             let llfn = cx.get_intrinsic(llvm_name);
305                             bx.call(llfn, &[args[0].immediate(), y], None)
306                         }
307                         "ctpop" => bx.call(cx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
308                                         &[args[0].immediate()], None),
309                         "bswap" => {
310                             if width == 8 {
311                                 args[0].immediate() // byte swap a u8/i8 is just a no-op
312                             } else {
313                                 bx.call(cx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
314                                         &[args[0].immediate()], None)
315                             }
316                         }
317                         "bitreverse" => {
318                             bx.call(cx.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
319                                 &[args[0].immediate()], None)
320                         }
321                         "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
322                             let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
323                                                     if signed { 's' } else { 'u' },
324                                                     &name[..3], width);
325                             let llfn = bx.cx.get_intrinsic(&intrinsic);
326
327                             // Convert `i1` to a `bool`, and write it to the out parameter
328                             let pair = bx.call(llfn, &[
329                                 args[0].immediate(),
330                                 args[1].immediate()
331                             ], None);
332                             let val = bx.extract_value(pair, 0);
333                             let overflow = bx.zext(bx.extract_value(pair, 1), Type::bool(cx));
334
335                             let dest = result.project_field(bx, 0);
336                             bx.store(val, dest.llval, dest.align);
337                             let dest = result.project_field(bx, 1);
338                             bx.store(overflow, dest.llval, dest.align);
339
340                             return;
341                         },
342                         "overflowing_add" => bx.add(args[0].immediate(), args[1].immediate()),
343                         "overflowing_sub" => bx.sub(args[0].immediate(), args[1].immediate()),
344                         "overflowing_mul" => bx.mul(args[0].immediate(), args[1].immediate()),
345                         "exact_div" =>
346                             if signed {
347                                 bx.exactsdiv(args[0].immediate(), args[1].immediate())
348                             } else {
349                                 bx.exactudiv(args[0].immediate(), args[1].immediate())
350                             },
351                         "unchecked_div" =>
352                             if signed {
353                                 bx.sdiv(args[0].immediate(), args[1].immediate())
354                             } else {
355                                 bx.udiv(args[0].immediate(), args[1].immediate())
356                             },
357                         "unchecked_rem" =>
358                             if signed {
359                                 bx.srem(args[0].immediate(), args[1].immediate())
360                             } else {
361                                 bx.urem(args[0].immediate(), args[1].immediate())
362                             },
363                         "unchecked_shl" => bx.shl(args[0].immediate(), args[1].immediate()),
364                         "unchecked_shr" =>
365                             if signed {
366                                 bx.ashr(args[0].immediate(), args[1].immediate())
367                             } else {
368                                 bx.lshr(args[0].immediate(), args[1].immediate())
369                             },
370                         "rotate_left" | "rotate_right" => {
371                             let is_left = name == "rotate_left";
372                             let val = args[0].immediate();
373                             let raw_shift = args[1].immediate();
374                             if llvm_util::get_major_version() >= 7 {
375                                 // rotate = funnel shift with first two args the same
376                                 let llvm_name = &format!("llvm.fsh{}.i{}",
377                                                          if is_left { 'l' } else { 'r' }, width);
378                                 let llfn = cx.get_intrinsic(llvm_name);
379                                 bx.call(llfn, &[val, val, raw_shift], None)
380                             } else {
381                                 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
382                                 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
383                                 let width = C_uint(Type::ix(cx, width), width);
384                                 let shift = bx.urem(raw_shift, width);
385                                 let inv_shift = bx.urem(bx.sub(width, raw_shift), width);
386                                 let shift1 = bx.shl(val, if is_left { shift } else { inv_shift });
387                                 let shift2 = bx.lshr(val, if !is_left { shift } else { inv_shift });
388                                 bx.or(shift1, shift2)
389                             }
390                         },
391                         _ => bug!(),
392                     },
393                 None => {
394                     span_invalid_monomorphization_error(
395                         tcx.sess, span,
396                         &format!("invalid monomorphization of `{}` intrinsic: \
397                                   expected basic integer type, found `{}`", name, ty));
398                     return;
399                 }
400             }
401         },
402         "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
403             let sty = &arg_tys[0].sty;
404             match float_type_width(sty) {
405                 Some(_width) =>
406                     match name {
407                         "fadd_fast" => bx.fadd_fast(args[0].immediate(), args[1].immediate()),
408                         "fsub_fast" => bx.fsub_fast(args[0].immediate(), args[1].immediate()),
409                         "fmul_fast" => bx.fmul_fast(args[0].immediate(), args[1].immediate()),
410                         "fdiv_fast" => bx.fdiv_fast(args[0].immediate(), args[1].immediate()),
411                         "frem_fast" => bx.frem_fast(args[0].immediate(), args[1].immediate()),
412                         _ => bug!(),
413                     },
414                 None => {
415                     span_invalid_monomorphization_error(
416                         tcx.sess, span,
417                         &format!("invalid monomorphization of `{}` intrinsic: \
418                                   expected basic float type, found `{}`", name, sty));
419                     return;
420                 }
421             }
422
423         },
424
425         "discriminant_value" => {
426             args[0].deref(bx.cx).codegen_get_discr(bx, ret_ty)
427         }
428
429         name if name.starts_with("simd_") => {
430             match generic_simd_intrinsic(bx, name,
431                                          callee_ty,
432                                          args,
433                                          ret_ty, llret_ty,
434                                          span) {
435                 Ok(llval) => llval,
436                 Err(()) => return
437             }
438         }
439         // This requires that atomic intrinsics follow a specific naming pattern:
440         // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
441         name if name.starts_with("atomic_") => {
442             use traits::AtomicOrdering::*;
443
444             let split: Vec<&str> = name.split('_').collect();
445
446             let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
447             let (order, failorder) = match split.len() {
448                 2 => (SequentiallyConsistent, SequentiallyConsistent),
449                 3 => match split[2] {
450                     "unordered" => (Unordered, Unordered),
451                     "relaxed" => (Monotonic, Monotonic),
452                     "acq"     => (Acquire, Acquire),
453                     "rel"     => (Release, Monotonic),
454                     "acqrel"  => (AcquireRelease, Acquire),
455                     "failrelaxed" if is_cxchg =>
456                         (SequentiallyConsistent, Monotonic),
457                     "failacq" if is_cxchg =>
458                         (SequentiallyConsistent, Acquire),
459                     _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
460                 },
461                 4 => match (split[2], split[3]) {
462                     ("acq", "failrelaxed") if is_cxchg =>
463                         (Acquire, Monotonic),
464                     ("acqrel", "failrelaxed") if is_cxchg =>
465                         (AcquireRelease, Monotonic),
466                     _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
467                 },
468                 _ => cx.sess().fatal("Atomic intrinsic not in correct format"),
469             };
470
471             let invalid_monomorphization = |ty| {
472                 span_invalid_monomorphization_error(tcx.sess, span,
473                     &format!("invalid monomorphization of `{}` intrinsic: \
474                               expected basic integer type, found `{}`", name, ty));
475             };
476
477             match split[1] {
478                 "cxchg" | "cxchgweak" => {
479                     let ty = substs.type_at(0);
480                     if int_type_width_signed(ty, cx).is_some() {
481                         let weak = split[1] == "cxchgweak";
482                         let pair = bx.atomic_cmpxchg(
483                             args[0].immediate(),
484                             args[1].immediate(),
485                             args[2].immediate(),
486                             order,
487                             failorder,
488                             weak);
489                         let val = bx.extract_value(pair, 0);
490                         let success = bx.zext(bx.extract_value(pair, 1), Type::bool(bx.cx));
491
492                         let dest = result.project_field(bx, 0);
493                         bx.store(val, dest.llval, dest.align);
494                         let dest = result.project_field(bx, 1);
495                         bx.store(success, dest.llval, dest.align);
496                         return;
497                     } else {
498                         return invalid_monomorphization(ty);
499                     }
500                 }
501
502                 "load" => {
503                     let ty = substs.type_at(0);
504                     if int_type_width_signed(ty, cx).is_some() {
505                         let size = cx.size_of(ty);
506                         bx.atomic_load(args[0].immediate(), order, size)
507                     } else {
508                         return invalid_monomorphization(ty);
509                     }
510                 }
511
512                 "store" => {
513                     let ty = substs.type_at(0);
514                     if int_type_width_signed(ty, cx).is_some() {
515                         let size = cx.size_of(ty);
516                         bx.atomic_store(args[1].immediate(), args[0].immediate(), order, size);
517                         return;
518                     } else {
519                         return invalid_monomorphization(ty);
520                     }
521                 }
522
523                 "fence" => {
524                     bx.atomic_fence(order, SynchronizationScope::CrossThread);
525                     return;
526                 }
527
528                 "singlethreadfence" => {
529                     bx.atomic_fence(order, SynchronizationScope::SingleThread);
530                     return;
531                 }
532
533                 // These are all AtomicRMW ops
534                 op => {
535                     let atom_op = match op {
536                         "xchg"  => AtomicRmwBinOp::AtomicXchg,
537                         "xadd"  => AtomicRmwBinOp::AtomicAdd,
538                         "xsub"  => AtomicRmwBinOp::AtomicSub,
539                         "and"   => AtomicRmwBinOp::AtomicAnd,
540                         "nand"  => AtomicRmwBinOp::AtomicNand,
541                         "or"    => AtomicRmwBinOp::AtomicOr,
542                         "xor"   => AtomicRmwBinOp::AtomicXor,
543                         "max"   => AtomicRmwBinOp::AtomicMax,
544                         "min"   => AtomicRmwBinOp::AtomicMin,
545                         "umax"  => AtomicRmwBinOp::AtomicUMax,
546                         "umin"  => AtomicRmwBinOp::AtomicUMin,
547                         _ => cx.sess().fatal("unknown atomic operation")
548                     };
549
550                     let ty = substs.type_at(0);
551                     if int_type_width_signed(ty, cx).is_some() {
552                         bx.atomic_rmw(atom_op, args[0].immediate(), args[1].immediate(), order)
553                     } else {
554                         return invalid_monomorphization(ty);
555                     }
556                 }
557             }
558         }
559
560         "nontemporal_store" => {
561             let dst = args[0].deref(bx.cx);
562             args[1].val.nontemporal_store(bx, dst);
563             return;
564         }
565
566         _ => {
567             let intr = Intrinsic::find(&name).unwrap_or_else(||
568                 bug!("unknown intrinsic '{}'", name));
569
570             fn one<T>(x: Vec<T>) -> T {
571                 assert_eq!(x.len(), 1);
572                 x.into_iter().next().unwrap()
573             }
574             fn ty_to_type(cx: &CodegenCx<'ll, '_>, t: &intrinsics::Type) -> Vec<&'ll Type> {
575                 use intrinsics::Type::*;
576                 match *t {
577                     Void => vec![Type::void(cx)],
578                     Integer(_signed, _width, llvm_width) => {
579                         vec![Type::ix(cx, llvm_width as u64)]
580                     }
581                     Float(x) => {
582                         match x {
583                             32 => vec![Type::f32(cx)],
584                             64 => vec![Type::f64(cx)],
585                             _ => bug!()
586                         }
587                     }
588                     Pointer(ref t, ref llvm_elem, _const) => {
589                         let t = llvm_elem.as_ref().unwrap_or(t);
590                         let elem = one(ty_to_type(cx, t));
591                         vec![elem.ptr_to()]
592                     }
593                     Vector(ref t, ref llvm_elem, length) => {
594                         let t = llvm_elem.as_ref().unwrap_or(t);
595                         let elem = one(ty_to_type(cx, t));
596                         vec![Type::vector::<Value>(elem, length as u64)]
597                     }
598                     Aggregate(false, ref contents) => {
599                         let elems = contents.iter()
600                                             .map(|t| one(ty_to_type(cx, t)))
601                                             .collect::<Vec<_>>();
602                         vec![Type::struct_(cx, &elems, false)]
603                     }
604                     Aggregate(true, ref contents) => {
605                         contents.iter()
606                                 .flat_map(|t| ty_to_type(cx, t))
607                                 .collect()
608                     }
609                 }
610             }
611
612             // This allows an argument list like `foo, (bar, baz),
613             // qux` to be converted into `foo, bar, baz, qux`, integer
614             // arguments to be truncated as needed and pointers to be
615             // cast.
616             fn modify_as_needed(
617                 bx: &Builder<'a, 'll, 'tcx>,
618                 t: &intrinsics::Type,
619                 arg: &OperandRef<'tcx, &'ll Value>,
620             ) -> Vec<&'ll Value> {
621                 match *t {
622                     intrinsics::Type::Aggregate(true, ref contents) => {
623                         // We found a tuple that needs squishing! So
624                         // run over the tuple and load each field.
625                         //
626                         // This assumes the type is "simple", i.e. no
627                         // destructors, and the contents are SIMD
628                         // etc.
629                         assert!(!bx.cx.type_needs_drop(arg.layout.ty));
630                         let (ptr, align) = match arg.val {
631                             OperandValue::Ref(ptr, None, align) => (ptr, align),
632                             _ => bug!()
633                         };
634                         let arg = PlaceRef::new_sized(ptr, arg.layout, align);
635                         (0..contents.len()).map(|i| {
636                             arg.project_field(bx, i).load(bx).immediate()
637                         }).collect()
638                     }
639                     intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
640                         let llvm_elem = one(ty_to_type(bx.cx, llvm_elem));
641                         vec![bx.pointercast(arg.immediate(), llvm_elem.ptr_to())]
642                     }
643                     intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
644                         let llvm_elem = one(ty_to_type(bx.cx, llvm_elem));
645                         vec![
646                             bx.bitcast(arg.immediate(),
647                             Type::vector::<Value>(llvm_elem, length as u64))
648                         ]
649                     }
650                     intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
651                         // the LLVM intrinsic uses a smaller integer
652                         // size than the C intrinsic's signature, so
653                         // we have to trim it down here.
654                         vec![bx.trunc(arg.immediate(), Type::ix(bx.cx, llvm_width as u64))]
655                     }
656                     _ => vec![arg.immediate()],
657                 }
658             }
659
660
661             let inputs = intr.inputs.iter()
662                                     .flat_map(|t| ty_to_type(cx, t))
663                                     .collect::<Vec<_>>();
664
665             let outputs = one(ty_to_type(cx, &intr.output));
666
667             let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
668                 modify_as_needed(bx, t, arg)
669             }).collect();
670             assert_eq!(inputs.len(), llargs.len());
671
672             let val = match intr.definition {
673                 intrinsics::IntrinsicDef::Named(name) => {
674                     let f = declare::declare_cfn(cx,
675                                                  name,
676                                                  Type::func::<Value>(&inputs, outputs));
677                     bx.call(f, &llargs, None)
678                 }
679             };
680
681             match *intr.output {
682                 intrinsics::Type::Aggregate(flatten, ref elems) => {
683                     // the output is a tuple so we need to munge it properly
684                     assert!(!flatten);
685
686                     for i in 0..elems.len() {
687                         let dest = result.project_field(bx, i);
688                         let val = bx.extract_value(val, i as u64);
689                         bx.store(val, dest.llval, dest.align);
690                     }
691                     return;
692                 }
693                 _ => val,
694             }
695         }
696     };
697
698     if !fn_ty.ret.is_ignore() {
699         if let PassMode::Cast(ty) = fn_ty.ret.mode {
700             let ptr = bx.pointercast(result.llval, ty.llvm_type(cx).ptr_to());
701             bx.store(llval, ptr, result.align);
702         } else {
703             OperandRef::from_immediate_or_packed_pair(bx, llval, result.layout)
704                 .val.store(bx, result);
705         }
706     }
707 }
708
709 fn copy_intrinsic(
710     bx: &Builder<'a, 'll, 'tcx>,
711     allow_overlap: bool,
712     volatile: bool,
713     ty: Ty<'tcx>,
714     dst: &'ll Value,
715     src: &'ll Value,
716     count: &'ll Value,
717 ) -> &'ll Value {
718     let cx = bx.cx;
719     let (size, align) = cx.size_and_align_of(ty);
720     let size = C_usize(cx, size.bytes());
721     let align = align.abi();
722     let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
723     let src_ptr = bx.pointercast(src, Type::i8p(cx));
724     if allow_overlap {
725         bx.memmove(dst_ptr, align, src_ptr, align, bx.mul(size, count), volatile)
726     } else {
727         bx.memcpy(dst_ptr, align, src_ptr, align, bx.mul(size, count), volatile)
728     }
729 }
730
731 fn memset_intrinsic(
732     bx: &Builder<'a, 'll, 'tcx>,
733     volatile: bool,
734     ty: Ty<'tcx>,
735     dst: &'ll Value,
736     val: &'ll Value,
737     count: &'ll Value
738 ) -> &'ll Value {
739     let cx = bx.cx;
740     let (size, align) = cx.size_and_align_of(ty);
741     let size = C_usize(cx, size.bytes());
742     let align = C_i32(cx, align.abi() as i32);
743     let dst = bx.pointercast(dst, Type::i8p(cx));
744     call_memset(bx, dst, val, bx.mul(size, count), align, volatile)
745 }
746
747 fn try_intrinsic(
748     bx: &Builder<'a, 'll, 'tcx>,
749     cx: &CodegenCx<'ll, 'tcx>,
750     func: &'ll Value,
751     data: &'ll Value,
752     local_ptr: &'ll Value,
753     dest: &'ll Value,
754 ) {
755     if bx.sess().no_landing_pads() {
756         bx.call(func, &[data], None);
757         let ptr_align = bx.tcx().data_layout.pointer_align;
758         bx.store(C_null(Type::i8p(&bx.cx)), dest, ptr_align);
759     } else if wants_msvc_seh(bx.sess()) {
760         codegen_msvc_try(bx, cx, func, data, local_ptr, dest);
761     } else {
762         codegen_gnu_try(bx, cx, func, data, local_ptr, dest);
763     }
764 }
765
766 // MSVC's definition of the `rust_try` function.
767 //
768 // This implementation uses the new exception handling instructions in LLVM
769 // which have support in LLVM for SEH on MSVC targets. Although these
770 // instructions are meant to work for all targets, as of the time of this
771 // writing, however, LLVM does not recommend the usage of these new instructions
772 // as the old ones are still more optimized.
773 fn codegen_msvc_try(
774     bx: &Builder<'a, 'll, 'tcx>,
775     cx: &CodegenCx<'ll, 'tcx>,
776     func: &'ll Value,
777     data: &'ll Value,
778     local_ptr: &'ll Value,
779     dest: &'ll Value,
780 ) {
781     let llfn = get_rust_try_fn(cx, &mut |bx| {
782         let cx = bx.cx;
783
784         bx.set_personality_fn(bx.cx.eh_personality());
785
786         let normal = bx.build_sibling_block("normal");
787         let catchswitch = bx.build_sibling_block("catchswitch");
788         let catchpad = bx.build_sibling_block("catchpad");
789         let caught = bx.build_sibling_block("caught");
790
791         let func = llvm::get_param(bx.llfn(), 0);
792         let data = llvm::get_param(bx.llfn(), 1);
793         let local_ptr = llvm::get_param(bx.llfn(), 2);
794
795         // We're generating an IR snippet that looks like:
796         //
797         //   declare i32 @rust_try(%func, %data, %ptr) {
798         //      %slot = alloca i64*
799         //      invoke %func(%data) to label %normal unwind label %catchswitch
800         //
801         //   normal:
802         //      ret i32 0
803         //
804         //   catchswitch:
805         //      %cs = catchswitch within none [%catchpad] unwind to caller
806         //
807         //   catchpad:
808         //      %tok = catchpad within %cs [%type_descriptor, 0, %slot]
809         //      %ptr[0] = %slot[0]
810         //      %ptr[1] = %slot[1]
811         //      catchret from %tok to label %caught
812         //
813         //   caught:
814         //      ret i32 1
815         //   }
816         //
817         // This structure follows the basic usage of throw/try/catch in LLVM.
818         // For example, compile this C++ snippet to see what LLVM generates:
819         //
820         //      #include <stdint.h>
821         //
822         //      int bar(void (*foo)(void), uint64_t *ret) {
823         //          try {
824         //              foo();
825         //              return 0;
826         //          } catch(uint64_t a[2]) {
827         //              ret[0] = a[0];
828         //              ret[1] = a[1];
829         //              return 1;
830         //          }
831         //      }
832         //
833         // More information can be found in libstd's seh.rs implementation.
834         let i64p = Type::i64(cx).ptr_to();
835         let ptr_align = bx.tcx().data_layout.pointer_align;
836         let slot = bx.alloca(i64p, "slot", ptr_align);
837         bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
838
839         normal.ret(C_i32(cx, 0));
840
841         let cs = catchswitch.catch_switch(None, None, 1);
842         catchswitch.add_handler(cs, catchpad.llbb());
843
844         let tcx = cx.tcx;
845         let tydesc = match tcx.lang_items().msvc_try_filter() {
846             Some(did) => ::consts::get_static(cx, did),
847             None => bug!("msvc_try_filter not defined"),
848         };
849         let tok = catchpad.catch_pad(cs, &[tydesc, C_i32(cx, 0), slot]);
850         let addr = catchpad.load(slot, ptr_align);
851
852         let i64_align = bx.tcx().data_layout.i64_align;
853         let arg1 = catchpad.load(addr, i64_align);
854         let val1 = C_i32(cx, 1);
855         let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), i64_align);
856         let local_ptr = catchpad.bitcast(local_ptr, i64p);
857         catchpad.store(arg1, local_ptr, i64_align);
858         catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), i64_align);
859         catchpad.catch_ret(tok, caught.llbb());
860
861         caught.ret(C_i32(cx, 1));
862     });
863
864     // Note that no invoke is used here because by definition this function
865     // can't panic (that's what it's catching).
866     let ret = bx.call(llfn, &[func, data, local_ptr], None);
867     let i32_align = bx.tcx().data_layout.i32_align;
868     bx.store(ret, dest, i32_align);
869 }
870
871 // Definition of the standard "try" function for Rust using the GNU-like model
872 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
873 // instructions).
874 //
875 // This codegen is a little surprising because we always call a shim
876 // function instead of inlining the call to `invoke` manually here. This is done
877 // because in LLVM we're only allowed to have one personality per function
878 // definition. The call to the `try` intrinsic is being inlined into the
879 // function calling it, and that function may already have other personality
880 // functions in play. By calling a shim we're guaranteed that our shim will have
881 // the right personality function.
882 fn codegen_gnu_try(
883     bx: &Builder<'a, 'll, 'tcx>,
884     cx: &CodegenCx<'ll, 'tcx>,
885     func: &'ll Value,
886     data: &'ll Value,
887     local_ptr: &'ll Value,
888     dest: &'ll Value,
889 ) {
890     let llfn = get_rust_try_fn(cx, &mut |bx| {
891         let cx = bx.cx;
892
893         // Codegens the shims described above:
894         //
895         //   bx:
896         //      invoke %func(%args...) normal %normal unwind %catch
897         //
898         //   normal:
899         //      ret 0
900         //
901         //   catch:
902         //      (ptr, _) = landingpad
903         //      store ptr, %local_ptr
904         //      ret 1
905         //
906         // Note that the `local_ptr` data passed into the `try` intrinsic is
907         // expected to be `*mut *mut u8` for this to actually work, but that's
908         // managed by the standard library.
909
910         let then = bx.build_sibling_block("then");
911         let catch = bx.build_sibling_block("catch");
912
913         let func = llvm::get_param(bx.llfn(), 0);
914         let data = llvm::get_param(bx.llfn(), 1);
915         let local_ptr = llvm::get_param(bx.llfn(), 2);
916         bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
917         then.ret(C_i32(cx, 0));
918
919         // Type indicator for the exception being thrown.
920         //
921         // The first value in this tuple is a pointer to the exception object
922         // being thrown.  The second value is a "selector" indicating which of
923         // the landing pad clauses the exception's type had been matched to.
924         // rust_try ignores the selector.
925         let lpad_ty = Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)], false);
926         let vals = catch.landing_pad(lpad_ty, bx.cx.eh_personality(), 1);
927         catch.add_clause(vals, C_null(Type::i8p(cx)));
928         let ptr = catch.extract_value(vals, 0);
929         let ptr_align = bx.tcx().data_layout.pointer_align;
930         catch.store(ptr, catch.bitcast(local_ptr, Type::i8p(cx).ptr_to()), ptr_align);
931         catch.ret(C_i32(cx, 1));
932     });
933
934     // Note that no invoke is used here because by definition this function
935     // can't panic (that's what it's catching).
936     let ret = bx.call(llfn, &[func, data, local_ptr], None);
937     let i32_align = bx.tcx().data_layout.i32_align;
938     bx.store(ret, dest, i32_align);
939 }
940
941 // Helper function to give a Block to a closure to codegen a shim function.
942 // This is currently primarily used for the `try` intrinsic functions above.
943 fn gen_fn<'ll, 'tcx>(
944     cx: &CodegenCx<'ll, 'tcx>,
945     name: &str,
946     inputs: Vec<Ty<'tcx>>,
947     output: Ty<'tcx>,
948     codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
949 ) -> &'ll Value {
950     let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
951         inputs.into_iter(),
952         output,
953         false,
954         hir::Unsafety::Unsafe,
955         Abi::Rust
956     ));
957     let llfn = declare::define_internal_fn(cx, name, rust_fn_sig);
958     attributes::from_fn_attrs(cx, llfn, None);
959     let bx = Builder::new_block(cx, llfn, "entry-block");
960     codegen(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<'ll, 'tcx>(
969     cx: &CodegenCx<'ll, 'tcx>,
970     codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
971 ) -> &'ll Value {
972     if let Some(llfn) = cx.rust_try_fn.get() {
973         return llfn;
974     }
975
976     // Define the type up front for the signature of the rust_try function.
977     let tcx = cx.tcx;
978     let i8p = tcx.mk_mut_ptr(tcx.types.i8);
979     let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
980         iter::once(i8p),
981         tcx.mk_unit(),
982         false,
983         hir::Unsafety::Unsafe,
984         Abi::Rust
985     )));
986     let output = tcx.types.i32;
987     let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
988     cx.rust_try_fn.set(Some(rust_try));
989     rust_try
990 }
991
992 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
993     span_err!(a, b, E0511, "{}", c);
994 }
995
996 fn generic_simd_intrinsic(
997     bx: &Builder<'a, 'll, 'tcx>,
998     name: &str,
999     callee_ty: Ty<'tcx>,
1000     args: &[OperandRef<'tcx, &'ll Value>],
1001     ret_ty: Ty<'tcx>,
1002     llret_ty: &'ll Type,
1003     span: Span
1004 ) -> Result<&'ll Value, ()> {
1005     // macros for error handling:
1006     macro_rules! emit_error {
1007         ($msg: tt) => {
1008             emit_error!($msg, )
1009         };
1010         ($msg: tt, $($fmt: tt)*) => {
1011             span_invalid_monomorphization_error(
1012                 bx.sess(), span,
1013                 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1014                          name, $($fmt)*));
1015         }
1016     }
1017
1018     macro_rules! return_error {
1019         ($($fmt: tt)*) => {
1020             {
1021                 emit_error!($($fmt)*);
1022                 return Err(());
1023             }
1024         }
1025     }
1026
1027     macro_rules! require {
1028         ($cond: expr, $($fmt: tt)*) => {
1029             if !$cond {
1030                 return_error!($($fmt)*);
1031             }
1032         };
1033     }
1034
1035     macro_rules! require_simd {
1036         ($ty: expr, $position: expr) => {
1037             require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1038         }
1039     }
1040
1041     let tcx = bx.tcx();
1042     let sig = tcx.normalize_erasing_late_bound_regions(
1043         ty::ParamEnv::reveal_all(),
1044         &callee_ty.fn_sig(tcx),
1045     );
1046     let arg_tys = sig.inputs();
1047
1048     // every intrinsic takes a SIMD vector as its first argument
1049     require_simd!(arg_tys[0], "input");
1050     let in_ty = arg_tys[0];
1051     let in_elem = arg_tys[0].simd_type(tcx);
1052     let in_len = arg_tys[0].simd_size(tcx);
1053
1054     let comparison = match name {
1055         "simd_eq" => Some(hir::BinOpKind::Eq),
1056         "simd_ne" => Some(hir::BinOpKind::Ne),
1057         "simd_lt" => Some(hir::BinOpKind::Lt),
1058         "simd_le" => Some(hir::BinOpKind::Le),
1059         "simd_gt" => Some(hir::BinOpKind::Gt),
1060         "simd_ge" => Some(hir::BinOpKind::Ge),
1061         _ => None
1062     };
1063
1064     if let Some(cmp_op) = comparison {
1065         require_simd!(ret_ty, "return");
1066
1067         let out_len = ret_ty.simd_size(tcx);
1068         require!(in_len == out_len,
1069                  "expected return type with length {} (same as input type `{}`), \
1070                   found `{}` with length {}",
1071                  in_len, in_ty,
1072                  ret_ty, out_len);
1073         require!(llret_ty.element_type().kind() == TypeKind::Integer,
1074                  "expected return type with integer elements, found `{}` with non-integer `{}`",
1075                  ret_ty,
1076                  ret_ty.simd_type(tcx));
1077
1078         return Ok(compare_simd_types(bx,
1079                                      args[0].immediate(),
1080                                      args[1].immediate(),
1081                                      in_elem,
1082                                      llret_ty,
1083                                      cmp_op))
1084     }
1085
1086     if name.starts_with("simd_shuffle") {
1087         let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1088             span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1089
1090         require_simd!(ret_ty, "return");
1091
1092         let out_len = ret_ty.simd_size(tcx);
1093         require!(out_len == n,
1094                  "expected return type of length {}, found `{}` with length {}",
1095                  n, ret_ty, out_len);
1096         require!(in_elem == ret_ty.simd_type(tcx),
1097                  "expected return element type `{}` (element of input `{}`), \
1098                   found `{}` with element type `{}`",
1099                  in_elem, in_ty,
1100                  ret_ty, ret_ty.simd_type(tcx));
1101
1102         let total_len = in_len as u128 * 2;
1103
1104         let vector = args[2].immediate();
1105
1106         let indices: Option<Vec<_>> = (0..n)
1107             .map(|i| {
1108                 let arg_idx = i;
1109                 let val = const_get_elt(vector, i as u64);
1110                 match const_to_opt_u128(val, true) {
1111                     None => {
1112                         emit_error!("shuffle index #{} is not a constant", arg_idx);
1113                         None
1114                     }
1115                     Some(idx) if idx >= total_len => {
1116                         emit_error!("shuffle index #{} is out of bounds (limit {})",
1117                                     arg_idx, total_len);
1118                         None
1119                     }
1120                     Some(idx) => Some(C_i32(bx.cx, idx as i32)),
1121                 }
1122             })
1123             .collect();
1124         let indices = match indices {
1125             Some(i) => i,
1126             None => return Ok(C_null(llret_ty))
1127         };
1128
1129         return Ok(bx.shuffle_vector(args[0].immediate(),
1130                                     args[1].immediate(),
1131                                     C_vector(&indices)))
1132     }
1133
1134     if name == "simd_insert" {
1135         require!(in_elem == arg_tys[2],
1136                  "expected inserted type `{}` (element of input `{}`), found `{}`",
1137                  in_elem, in_ty, arg_tys[2]);
1138         return Ok(bx.insert_element(args[0].immediate(),
1139                                     args[2].immediate(),
1140                                     args[1].immediate()))
1141     }
1142     if name == "simd_extract" {
1143         require!(ret_ty == in_elem,
1144                  "expected return type `{}` (element of input `{}`), found `{}`",
1145                  in_elem, in_ty, ret_ty);
1146         return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1147     }
1148
1149     if name == "simd_select" {
1150         let m_elem_ty = in_elem;
1151         let m_len = in_len;
1152         let v_len = arg_tys[1].simd_size(tcx);
1153         require!(m_len == v_len,
1154                  "mismatched lengths: mask length `{}` != other vector length `{}`",
1155                  m_len, v_len
1156         );
1157         match m_elem_ty.sty {
1158             ty::Int(_) => {},
1159             _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1160         }
1161         // truncate the mask to a vector of i1s
1162         let i1 = Type::i1(bx.cx);
1163         let i1xn = Type::vector::<Value>(i1, m_len as u64);
1164         let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1165         return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1166     }
1167
1168     fn simd_simple_float_intrinsic(
1169         name: &str,
1170         in_elem: &::rustc::ty::TyS,
1171         in_ty: &::rustc::ty::TyS,
1172         in_len: usize,
1173         bx: &Builder<'a, 'll, 'tcx>,
1174         span: Span,
1175         args: &[OperandRef<'tcx, &'ll Value>],
1176     ) -> Result<&'ll Value, ()> {
1177         macro_rules! emit_error {
1178             ($msg: tt) => {
1179                 emit_error!($msg, )
1180             };
1181             ($msg: tt, $($fmt: tt)*) => {
1182                 span_invalid_monomorphization_error(
1183                     bx.sess(), span,
1184                     &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1185                              name, $($fmt)*));
1186             }
1187         }
1188         macro_rules! return_error {
1189             ($($fmt: tt)*) => {
1190                 {
1191                     emit_error!($($fmt)*);
1192                     return Err(());
1193                 }
1194             }
1195         }
1196         let ety = match in_elem.sty {
1197             ty::Float(f) if f.bit_width() == 32 => {
1198                 if in_len < 2 || in_len > 16 {
1199                     return_error!(
1200                         "unsupported floating-point vector `{}` with length `{}` \
1201                          out-of-range [2, 16]",
1202                         in_ty, in_len);
1203                 }
1204                 "f32"
1205             },
1206             ty::Float(f) if f.bit_width() == 64 => {
1207                 if in_len < 2 || in_len > 8 {
1208                     return_error!("unsupported floating-point vector `{}` with length `{}` \
1209                                    out-of-range [2, 8]",
1210                                   in_ty, in_len);
1211                 }
1212                 "f64"
1213             },
1214             ty::Float(f) => {
1215                 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1216                               f, in_ty);
1217             },
1218             _ => {
1219                 return_error!("`{}` is not a floating-point type", in_ty);
1220             }
1221         };
1222
1223         let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1224         let intrinsic = bx.cx.get_intrinsic(&llvm_name);
1225         let c = bx.call(intrinsic,
1226                         &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1227                         None);
1228         unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1229         Ok(c)
1230     }
1231
1232     match name {
1233         "simd_fsqrt" => {
1234             return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1235         }
1236         "simd_fsin" => {
1237             return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1238         }
1239         "simd_fcos" => {
1240             return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1241         }
1242         "simd_fabs" => {
1243             return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1244         }
1245         "simd_floor" => {
1246             return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1247         }
1248         "simd_ceil" => {
1249             return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1250         }
1251         "simd_fexp" => {
1252             return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1253         }
1254         "simd_fexp2" => {
1255             return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1256         }
1257         "simd_flog10" => {
1258             return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1259         }
1260         "simd_flog2" => {
1261             return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1262         }
1263         "simd_flog" => {
1264             return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1265         }
1266         "simd_fpowi" => {
1267             return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1268         }
1269         "simd_fpow" => {
1270             return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1271         }
1272         "simd_fma" => {
1273             return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1274         }
1275         _ => { /* fallthrough */ }
1276     }
1277
1278     // FIXME: use:
1279     //  https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1280     //  https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1281     fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1282         let p0s: String = "p0".repeat(no_pointers);
1283         match elem_ty.sty {
1284             ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1285             ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1286             ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1287             _ => unreachable!(),
1288         }
1289     }
1290
1291     fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1292                       mut no_pointers: usize) -> &'ll Type {
1293         // FIXME: use cx.layout_of(ty).llvm_type() ?
1294         let mut elem_ty = match elem_ty.sty {
1295             ty::Int(v) => Type::int_from_ty(cx, v),
1296             ty::Uint(v) => Type::uint_from_ty(cx, v),
1297             ty::Float(v) => Type::float_from_ty(cx, v),
1298             _ => unreachable!(),
1299         };
1300         while no_pointers > 0 {
1301             elem_ty = elem_ty.ptr_to();
1302             no_pointers -= 1;
1303         }
1304         Type::vector::<Value>(elem_ty, vec_len as u64)
1305     }
1306
1307
1308     if name == "simd_gather" {
1309         // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1310         //             mask: <N x i{M}>) -> <N x T>
1311         // * N: number of elements in the input vectors
1312         // * T: type of the element to load
1313         // * M: any integer width is supported, will be truncated to i1
1314
1315         // All types must be simd vector types
1316         require_simd!(in_ty, "first");
1317         require_simd!(arg_tys[1], "second");
1318         require_simd!(arg_tys[2], "third");
1319         require_simd!(ret_ty, "return");
1320
1321         // Of the same length:
1322         require!(in_len == arg_tys[1].simd_size(tcx),
1323                  "expected {} argument with length {} (same as input type `{}`), \
1324                   found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1325                  arg_tys[1].simd_size(tcx));
1326         require!(in_len == arg_tys[2].simd_size(tcx),
1327                  "expected {} argument with length {} (same as input type `{}`), \
1328                   found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1329                  arg_tys[2].simd_size(tcx));
1330
1331         // The return type must match the first argument type
1332         require!(ret_ty == in_ty,
1333                  "expected return type `{}`, found `{}`",
1334                  in_ty, ret_ty);
1335
1336         // This counts how many pointers
1337         fn ptr_count(t: ty::Ty) -> usize {
1338             match t.sty {
1339                 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1340                 _ => 0,
1341             }
1342         }
1343
1344         // Non-ptr type
1345         fn non_ptr(t: ty::Ty) -> ty::Ty {
1346             match t.sty {
1347                 ty::RawPtr(p) => non_ptr(p.ty),
1348                 _ => t,
1349             }
1350         }
1351
1352         // The second argument must be a simd vector with an element type that's a pointer
1353         // to the element type of the first argument
1354         let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1355             ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1356                                                  non_ptr(arg_tys[1].simd_type(tcx))),
1357             _ => {
1358                 require!(false, "expected element type `{}` of second argument `{}` \
1359                                  to be a pointer to the element type `{}` of the first \
1360                                  argument `{}`, found `{}` != `*_ {}`",
1361                          arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1362                          arg_tys[1].simd_type(tcx).sty, in_elem);
1363                 unreachable!();
1364             }
1365         };
1366         assert!(pointer_count > 0);
1367         assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1368         assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1369
1370         // The element type of the third argument must be a signed integer type of any width:
1371         match arg_tys[2].simd_type(tcx).sty {
1372             ty::Int(_) => (),
1373             _ => {
1374                 require!(false, "expected element type `{}` of third argument `{}` \
1375                                  to be a signed integer type",
1376                          arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1377             }
1378         }
1379
1380         // Alignment of T, must be a constant integer value:
1381         let alignment_ty = Type::i32(bx.cx);
1382         let alignment = C_i32(bx.cx, bx.cx.align_of(in_elem).abi() as i32);
1383
1384         // Truncate the mask vector to a vector of i1s:
1385         let (mask, mask_ty) = {
1386             let i1 = Type::i1(bx.cx);
1387             let i1xn = Type::vector::<Value>(i1, in_len as u64);
1388             (bx.trunc(args[2].immediate(), i1xn), i1xn)
1389         };
1390
1391         // Type of the vector of pointers:
1392         let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count);
1393         let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1394
1395         // Type of the vector of elements:
1396         let llvm_elem_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count - 1);
1397         let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1398
1399         let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1400                                      llvm_elem_vec_str, llvm_pointer_vec_str);
1401         let f = declare::declare_cfn(bx.cx, &llvm_intrinsic,
1402                                      Type::func::<Value>(&[
1403                                          llvm_pointer_vec_ty,
1404                                          alignment_ty,
1405                                          mask_ty,
1406                                          llvm_elem_vec_ty], llvm_elem_vec_ty));
1407         llvm::SetUnnamedAddr(f, false);
1408         let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1409                         None);
1410         return Ok(v);
1411     }
1412
1413     if name == "simd_scatter" {
1414         // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1415         //             mask: <N x i{M}>) -> ()
1416         // * N: number of elements in the input vectors
1417         // * T: type of the element to load
1418         // * M: any integer width is supported, will be truncated to i1
1419
1420         // All types must be simd vector types
1421         require_simd!(in_ty, "first");
1422         require_simd!(arg_tys[1], "second");
1423         require_simd!(arg_tys[2], "third");
1424
1425         // Of the same length:
1426         require!(in_len == arg_tys[1].simd_size(tcx),
1427                  "expected {} argument with length {} (same as input type `{}`), \
1428                   found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1429                  arg_tys[1].simd_size(tcx));
1430         require!(in_len == arg_tys[2].simd_size(tcx),
1431                  "expected {} argument with length {} (same as input type `{}`), \
1432                   found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1433                  arg_tys[2].simd_size(tcx));
1434
1435         // This counts how many pointers
1436         fn ptr_count(t: ty::Ty) -> usize {
1437             match t.sty {
1438                 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1439                 _ => 0,
1440             }
1441         }
1442
1443         // Non-ptr type
1444         fn non_ptr(t: ty::Ty) -> ty::Ty {
1445             match t.sty {
1446                 ty::RawPtr(p) => non_ptr(p.ty),
1447                 _ => t,
1448             }
1449         }
1450
1451         // The second argument must be a simd vector with an element type that's a pointer
1452         // to the element type of the first argument
1453         let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1454             ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1455                 => (ptr_count(arg_tys[1].simd_type(tcx)),
1456                     non_ptr(arg_tys[1].simd_type(tcx))),
1457             _ => {
1458                 require!(false, "expected element type `{}` of second argument `{}` \
1459                                  to be a pointer to the element type `{}` of the first \
1460                                  argument `{}`, found `{}` != `*mut {}`",
1461                          arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1462                          arg_tys[1].simd_type(tcx).sty, in_elem);
1463                 unreachable!();
1464             }
1465         };
1466         assert!(pointer_count > 0);
1467         assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1468         assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1469
1470         // The element type of the third argument must be a signed integer type of any width:
1471         match arg_tys[2].simd_type(tcx).sty {
1472             ty::Int(_) => (),
1473             _ => {
1474                 require!(false, "expected element type `{}` of third argument `{}` \
1475                                  to be a signed integer type",
1476                          arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1477             }
1478         }
1479
1480         // Alignment of T, must be a constant integer value:
1481         let alignment_ty = Type::i32(bx.cx);
1482         let alignment = C_i32(bx.cx, bx.cx.align_of(in_elem).abi() as i32);
1483
1484         // Truncate the mask vector to a vector of i1s:
1485         let (mask, mask_ty) = {
1486             let i1 = Type::i1(bx.cx);
1487             let i1xn = Type::vector::<Value>(i1, in_len as u64);
1488             (bx.trunc(args[2].immediate(), i1xn), i1xn)
1489         };
1490
1491         let ret_t = Type::void(bx.cx);
1492
1493         // Type of the vector of pointers:
1494         let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count);
1495         let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1496
1497         // Type of the vector of elements:
1498         let llvm_elem_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count - 1);
1499         let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1500
1501         let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1502                                      llvm_elem_vec_str, llvm_pointer_vec_str);
1503         let f = declare::declare_cfn(bx.cx, &llvm_intrinsic,
1504                                      Type::func::<Value>(&[llvm_elem_vec_ty,
1505                                                   llvm_pointer_vec_ty,
1506                                                   alignment_ty,
1507                                                   mask_ty], ret_t));
1508         llvm::SetUnnamedAddr(f, false);
1509         let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1510                         None);
1511         return Ok(v);
1512     }
1513
1514     macro_rules! arith_red {
1515         ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1516             if name == $name {
1517                 require!(ret_ty == in_elem,
1518                          "expected return type `{}` (element of input `{}`), found `{}`",
1519                          in_elem, in_ty, ret_ty);
1520                 return match in_elem.sty {
1521                     ty::Int(_) | ty::Uint(_) => {
1522                         let r = bx.$integer_reduce(args[0].immediate());
1523                         if $ordered {
1524                             // if overflow occurs, the result is the
1525                             // mathematical result modulo 2^n:
1526                             if name.contains("mul") {
1527                                 Ok(bx.mul(args[1].immediate(), r))
1528                             } else {
1529                                 Ok(bx.add(args[1].immediate(), r))
1530                             }
1531                         } else {
1532                             Ok(bx.$integer_reduce(args[0].immediate()))
1533                         }
1534                     },
1535                     ty::Float(f) => {
1536                         // ordered arithmetic reductions take an accumulator
1537                         let acc = if $ordered {
1538                             let acc = args[1].immediate();
1539                             // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1540                             // * if the accumulator of the fadd isn't 0, incorrect
1541                             //   code is generated
1542                             // * if the accumulator of the fmul isn't 1, incorrect
1543                             //   code is generated
1544                             match const_get_real(acc) {
1545                                 None => return_error!("accumulator of {} is not a constant", $name),
1546                                 Some((v, loses_info)) => {
1547                                     if $name.contains("mul") && v != 1.0_f64 {
1548                                         return_error!("accumulator of {} is not 1.0", $name);
1549                                     } else if $name.contains("add") && v != 0.0_f64 {
1550                                         return_error!("accumulator of {} is not 0.0", $name);
1551                                     } else if loses_info {
1552                                         return_error!("accumulator of {} loses information", $name);
1553                                     }
1554                                 }
1555                             }
1556                             acc
1557                         } else {
1558                             // unordered arithmetic reductions do not:
1559                             match f.bit_width() {
1560                                 32 => C_undef(Type::f32(bx.cx)),
1561                                 64 => C_undef(Type::f64(bx.cx)),
1562                                 v => {
1563                                     return_error!(r#"
1564 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1565                                         $name, in_ty, in_elem, v, ret_ty
1566                                     )
1567                                 }
1568                             }
1569                         };
1570                         Ok(bx.$float_reduce(acc, args[0].immediate()))
1571                     }
1572                     _ => {
1573                         return_error!(
1574                             "unsupported {} from `{}` with element `{}` to `{}`",
1575                             $name, in_ty, in_elem, ret_ty
1576                         )
1577                     },
1578                 }
1579             }
1580         }
1581     }
1582
1583     arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1584     arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1585     arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1586     arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1587
1588     macro_rules! minmax_red {
1589         ($name:tt: $int_red:ident, $float_red:ident) => {
1590             if name == $name {
1591                 require!(ret_ty == in_elem,
1592                          "expected return type `{}` (element of input `{}`), found `{}`",
1593                          in_elem, in_ty, ret_ty);
1594                 return match in_elem.sty {
1595                     ty::Int(_i) => {
1596                         Ok(bx.$int_red(args[0].immediate(), true))
1597                     },
1598                     ty::Uint(_u) => {
1599                         Ok(bx.$int_red(args[0].immediate(), false))
1600                     },
1601                     ty::Float(_f) => {
1602                         Ok(bx.$float_red(args[0].immediate()))
1603                     }
1604                     _ => {
1605                         return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1606                                       $name, in_ty, in_elem, ret_ty)
1607                     },
1608                 }
1609             }
1610
1611         }
1612     }
1613
1614     minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1615     minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1616
1617     minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1618     minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1619
1620     macro_rules! bitwise_red {
1621         ($name:tt : $red:ident, $boolean:expr) => {
1622             if name == $name {
1623                 let input = if !$boolean {
1624                     require!(ret_ty == in_elem,
1625                              "expected return type `{}` (element of input `{}`), found `{}`",
1626                              in_elem, in_ty, ret_ty);
1627                     args[0].immediate()
1628                 } else {
1629                     match in_elem.sty {
1630                         ty::Int(_) | ty::Uint(_) => {},
1631                         _ => {
1632                             return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1633                                           $name, in_ty, in_elem, ret_ty)
1634                         }
1635                     }
1636
1637                     // boolean reductions operate on vectors of i1s:
1638                     let i1 = Type::i1(bx.cx);
1639                     let i1xn = Type::vector::<Value>(i1, in_len as u64);
1640                     bx.trunc(args[0].immediate(), i1xn)
1641                 };
1642                 return match in_elem.sty {
1643                     ty::Int(_) | ty::Uint(_) => {
1644                         let r = bx.$red(input);
1645                         Ok(
1646                             if !$boolean {
1647                                 r
1648                             } else {
1649                                 bx.zext(r, Type::bool(bx.cx))
1650                             }
1651                         )
1652                     },
1653                     _ => {
1654                         return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1655                                       $name, in_ty, in_elem, ret_ty)
1656                     },
1657                 }
1658             }
1659         }
1660     }
1661
1662     bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1663     bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1664     bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1665     bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1666     bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1667
1668     if name == "simd_cast" {
1669         require_simd!(ret_ty, "return");
1670         let out_len = ret_ty.simd_size(tcx);
1671         require!(in_len == out_len,
1672                  "expected return type with length {} (same as input type `{}`), \
1673                   found `{}` with length {}",
1674                  in_len, in_ty,
1675                  ret_ty, out_len);
1676         // casting cares about nominal type, not just structural type
1677         let out_elem = ret_ty.simd_type(tcx);
1678
1679         if in_elem == out_elem { return Ok(args[0].immediate()); }
1680
1681         enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1682
1683         let (in_style, in_width) = match in_elem.sty {
1684             // vectors of pointer-sized integers should've been
1685             // disallowed before here, so this unwrap is safe.
1686             ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1687             ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1688             ty::Float(f) => (Style::Float, f.bit_width()),
1689             _ => (Style::Unsupported, 0)
1690         };
1691         let (out_style, out_width) = match out_elem.sty {
1692             ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1693             ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1694             ty::Float(f) => (Style::Float, f.bit_width()),
1695             _ => (Style::Unsupported, 0)
1696         };
1697
1698         match (in_style, out_style) {
1699             (Style::Int(in_is_signed), Style::Int(_)) => {
1700                 return Ok(match in_width.cmp(&out_width) {
1701                     Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1702                     Ordering::Equal => args[0].immediate(),
1703                     Ordering::Less => if in_is_signed {
1704                         bx.sext(args[0].immediate(), llret_ty)
1705                     } else {
1706                         bx.zext(args[0].immediate(), llret_ty)
1707                     }
1708                 })
1709             }
1710             (Style::Int(in_is_signed), Style::Float) => {
1711                 return Ok(if in_is_signed {
1712                     bx.sitofp(args[0].immediate(), llret_ty)
1713                 } else {
1714                     bx.uitofp(args[0].immediate(), llret_ty)
1715                 })
1716             }
1717             (Style::Float, Style::Int(out_is_signed)) => {
1718                 return Ok(if out_is_signed {
1719                     bx.fptosi(args[0].immediate(), llret_ty)
1720                 } else {
1721                     bx.fptoui(args[0].immediate(), llret_ty)
1722                 })
1723             }
1724             (Style::Float, Style::Float) => {
1725                 return Ok(match in_width.cmp(&out_width) {
1726                     Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1727                     Ordering::Equal => args[0].immediate(),
1728                     Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1729                 })
1730             }
1731             _ => {/* Unsupported. Fallthrough. */}
1732         }
1733         require!(false,
1734                  "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1735                  in_ty, in_elem,
1736                  ret_ty, out_elem);
1737     }
1738     macro_rules! arith {
1739         ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1740             $(if name == stringify!($name) {
1741                 match in_elem.sty {
1742                     $($(ty::$p(_))|* => {
1743                         return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1744                     })*
1745                     _ => {},
1746                 }
1747                 require!(false,
1748                          "unsupported operation on `{}` with element `{}`",
1749                          in_ty,
1750                          in_elem)
1751             })*
1752         }
1753     }
1754     arith! {
1755         simd_add: Uint, Int => add, Float => fadd;
1756         simd_sub: Uint, Int => sub, Float => fsub;
1757         simd_mul: Uint, Int => mul, Float => fmul;
1758         simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1759         simd_rem: Uint => urem, Int => srem, Float => frem;
1760         simd_shl: Uint, Int => shl;
1761         simd_shr: Uint => lshr, Int => ashr;
1762         simd_and: Uint, Int => and;
1763         simd_or: Uint, Int => or;
1764         simd_xor: Uint, Int => xor;
1765         simd_fmax: Float => maxnum;
1766         simd_fmin: Float => minnum;
1767     }
1768     span_bug!(span, "unknown SIMD intrinsic");
1769 }
1770
1771 // Returns the width of an int Ty, and if it's signed or not
1772 // Returns None if the type is not an integer
1773 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1774 // stuffs.
1775 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1776     match ty.sty {
1777         ty::Int(t) => Some((match t {
1778             ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1779             ast::IntTy::I8 => 8,
1780             ast::IntTy::I16 => 16,
1781             ast::IntTy::I32 => 32,
1782             ast::IntTy::I64 => 64,
1783             ast::IntTy::I128 => 128,
1784         }, true)),
1785         ty::Uint(t) => Some((match t {
1786             ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1787             ast::UintTy::U8 => 8,
1788             ast::UintTy::U16 => 16,
1789             ast::UintTy::U32 => 32,
1790             ast::UintTy::U64 => 64,
1791             ast::UintTy::U128 => 128,
1792         }, false)),
1793         _ => None,
1794     }
1795 }
1796
1797 // Returns the width of a float TypeVariant
1798 // Returns None if the type is not a float
1799 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1800     match *sty {
1801         ty::Float(t) => Some(t.bit_width() as u64),
1802         _ => None,
1803     }
1804 }